The core of pomelo is a series of loosely coupled component components. At the same time, we can implement our own component to complete some of our own custom functions. For our chat application, we try to add a component to it to demonstrate how to add a component and manage the lifecycle of the component without paying special attention to the actual functions of this component. Now we add a component helloworld to it. This component only loads and runs on the master server. On the master server, it prints a helloworld on the console at intervals, the specific time interval is specified by the OPTs configuration.
Create the components/helloworld. js file in the app. The Code is as follows:
module.exports = function(app, opts) { return new HelloWorld(app, opts);};var DEFAULT_INTERVAL = 3000;var HelloWorld = function(app, opts) { this.app = app; this.interval = opts.interval | DEFAULT_INTERVAL; this.timerId = null;};HelloWorld.name = ‘__HelloWorld__‘;HelloWorld.prototype.start = function(cb) { console.log(‘Hello World Start‘); var self = this; this.timerId = setInterval(function() { console.log(self.app.getServerId() + ": Hello World!"); }, this.interval); process.nextTick(cb);}HelloWorld.prototype.afterStart = function (cb) { console.log(‘Hello World afterStart‘); process.nextTick(cb);}HelloWorld.prototype.stop = function(force, cb) { cosole.log(‘Hello World stop‘); clearInterval(this.timerId); process.nextTick(cb);}
We can see that each component generally defines the start, afterstart, and stop hook functions for pomelo to call when managing its lifecycle. For the startup of component, pomelo always calls the start function provided by each component it loads. After all the calls are completed, the afterstart method of each component it loads will be called, it is always called in order. Because when afterstart is called, the start of all component has been called, you can add work that requires global readiness. Stop is used to clean the component at the end of the program.
The configuration in APP. JS is as follows:
// app.jsvar helloWorld = require(‘./app/components/HelloWorld‘);app.configure(‘production|development‘, ‘master‘, function() { app.load(helloWorld, {interval: 5000});});
Component of pomelo