Cluster library

Contents

This API provides cluster related functions.

Usage

Add the following to your build.gradle file:

dependencies {
  include xplibs.cluster
}

Add the import statement to your code:

import clusterLib from '/lib/xp/cluster';

You are now ready to use the API.

Functions

isLeader

Tests whether the current node is the leader for the calling application. Useful for guarding work that should run on a single node — scheduled initialization, one-shot tasks, or event handlers that must not fire on every cluster node.

Parameters

None

Returns

boolean : true if the current node is the leader; false otherwise.

Examples

Initialize data only on the leader node
import {isLeader} from '/lib/xp/cluster';
if (isLeader()) {
    initializeRepo();
}
Run a named task only on the leader
import {isLeader} from '/lib/xp/cluster';
import {submitTask} from '/lib/xp/task';

if (isLeader()) {
    submitTask({
        descriptor: 'longRunningTask'
    });
}
Handle an event only on the leader
import {isLeader} from '/lib/xp/cluster';
import {listener} from '/lib/xp/event';

listener({
    type: 'node.pushed',
    localOnly: false,
    callback: (event) => {
        if (isLeader()) {
            log.info('event: %s', JSON.stringify(event));
        }
    }
});

isMaster

Deprecated since XP 8 — use isLeader instead.

Tests whether the current node is the master node in the cluster. Same signature and return type as isLeader.

import {isMaster} from '/lib/xp/cluster';
if (isMaster()) {
    initializeRepo();
}

Contents

Contents