A Nest module for communication between master and worker processes based on node-cluster-hub
To begin using it, we first install the required dependency.
$ npm install --save nest-cluster-hub
Once the installation is complete, import the ClusterHubModule
into the root AppModule
and run the forRoot()
static method as shown below:
import { Module } from '@nestjs/common';
import { ClusterHubModule } from 'nest-cluster-hub';
@Module({
imports: [
ClusterHubModule.forRoot(),
],
})
export class AppModule {}
Next, inject the ClusterHub
instance using the @InjectClusterHub()
decorator.
constructor(@InjectClusterHub() private readonly hub: ClusterHub) {}
if (cluster.isPrimary) {
this.hub.sendToWorker(worker, 'master-to-worker', 1);
}
You can just pass any string instead of cluster.Worker
. The library uses HashRing to let you find the correct worker for the key which is closest to the point after what the given key hashes to.
if (cluster.isPrimary) {
this.hub.sendToRandomWorker('master-to-worker', 1);
}
if (cluster.isPrimary) {
this.hub.sendToWorkers('master-to-worker', 1);
}
if (cluster.isPrimary) {
this.hub.sendToMaster('master-to-master', 1);
}
if (cluster.isWorker) {
this.hub.sendToMaster('worker-to-worker', 1);
}
if (cluster.isPrimary) {
this.hub.on('master-to-master', (data) => {
console.log('master-to-master received');
});
this.hub.on('worker-to-master', (data) => {
console.log('worker-to-master received');
});
}
if (cluster.isWorker) {
this.hub.on('master-to-worker', (data) => {
console.log('master-to-worker received');
});
}
@OnMessage('master-to-worker')
async handleMessage(data) {
console.log('master-to-worker received');
}
if (cluster.isPrimary) {
this.hub.requestWorker(worker, 'mult', { a: 5, b: 7 }, (err, sum) => {
console.log('Mult in master: ' + sum);
});
}
You can also pass any string instead of cluster.Worker
to find the correct worker.
if (cluster.isPrimary) {
this.hub.requestRandomWorker('mult', { a: 5, b: 7 }, (err, sum) => {
console.log('Mult in master: ' + sum);
});
}
if (cluster.isPrimary) {
this.hub.requestMaster('sum', { a: 5, b: 7 }, (err, sum) => {
console.log('Sum in master: ' + sum);
});
}
if (cluster.isWorker) {
this.hub.requestMaster('sum', { a: 5, b: 7 }, (err, sum) => {
console.log('Sum in worker: ' + sum);
});
}
if (cluster.isPrimary) {
this.hub.on('sum', (data, sender, callback) => {
callback(null, data.a + data.b);
});
}
if (cluster.isWorker) {
this.hub.on('mult', (data, sender, callback) => {
callback(null, data.a * data.b);
});
}
@OnRequest('mult')
async handleMessage(data, sender, callback) {
callback(null, data.a * data.b);
}
this.hub.set('foo', 'bar', () => {
this.hub.get('foo', (err, value) => {
console.log(value === 'bar'); // true
});
});
if (cluster.isPrimary) {
this.hub.getWorker('foo');
}
if (cluster.isPrimary) {
this.hub.getWorkers();
}
A working example is available here.