Scenario

We know that EggBornJS is based on EggJS to support cluster mode, so as to start multiple working processes at the same time to provide services for the frontend

EggBornJS adds a broadcast mechanism, which allows sending a broadcast to all working processes, so that all working processes can perform a task at the same time

Let’s take the module test-party as an example to develop a Broadcast

Declaration of Broadcast

src/module/test-party/backend/src/config/config.js

module.exports = appInfo => {
  const config = {};

  // broadcasts
  config.broadcasts = {
    broadcastTest: {
      path: 'test/feat/broadcast',
    },
  };

  return config;
};
Name Description
broadcastTest Broadcast Name
path API Route to be performed

Declaration of API Route

src/module/test-party/backend/src/routes.js

{ method: 'post', path: 'test/feat/broadcast', controller: testFeatBroadcast, middlewares: 'inner' },
Name Description
middlewares Specify the middleware inner, only allowed performed inner access

Controller Action

src/module/test-party/backend/src/controller/test/feat/broadcast.js

async broadcast() {
  const { sameAsCaller, message } = this.ctx.request.body;
  if (!sameAsCaller) {
    // do something
  }
  assert.equal(message, 'hello');
  this.ctx.success();
}
Name Description
sameAsCaller Identify whether the current working process emiting broadcast
message Custom parameters

Emit Broadcast

src/module/test-party/backend/src/controller/test/feat/broadcast.js

async emit() {
  this.ctx.app.meta.broadcast.emit({
    subdomain: this.ctx.subdomain,
    module: 'test-party',
    broadcastName: 'broadcastTest',
    data: { message: 'hello' },
  });
  this.ctx.success();
}
Name Description
subdomain The corresponding subdomain name of the current instance, so as to return to the running environment of the current instance correctly when executing the broadcast task
module Module Name
broadcastName Broadcast Name
data Parameters passed to the broadcast task

Special Broadcast: Reload All Working Processes

EggBornJS provides a special broadcast to restart all working processes. Emit this broadcast as follows:

this.ctx.app.meta.broadcast.reload();