zoukankan      html  css  js  c++  java
  • Pomelo的component组件

      pomelo的核心是由一系列松耦合的component组成,同时我们也可以实现我们自己的component来完成一些自己定制的功能。对于我们的聊天应用,我们尝试给其增加一个component,目的是展示如何增加一个component,以及component的生命周期管理,而不会特别关注这个component的实际功能。我们现在就给其增加一个component HelloWorld,这个component仅仅在master服务器上加载运行,在master服务器的话,它将每隔一段时间在console上打印出来一个HelloWorld,具体的时间间隔由opts配置来指定

      在app下建立components/HelloWorld.js文件, 大致代码如下:

    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);
    }
    

      我们看到每一个component一般都要定义start,afterStart,stop这些hook函数,供pomelo管理其生命周期时进行调用。对于component的启动,pomelo总是先调用其加载的每一个component提供的start函数,当全部调用完后,才会去调用其加载的每一个component的afterStart方法,这里总是按顺序调用的。因为调用afterStart的时候,所有component的start已经调用完毕,可以添加一些需要全局就绪的工作。stop用于程序结束时对component进行清理时使用

      在app.js配置如下:

    // app.js
    var helloWorld = require('./app/components/HelloWorld');
    
    app.configure('production|development', 'master', function() {
      app.load(helloWorld, {interval: 5000});
    });
    

      

  • 相关阅读:
    矩阵特征值和椭圆长短轴的关系?
    Harris角点检测原理详解
    SIFT特征提取分析
    Sift中尺度空间、高斯金字塔、差分金字塔(DOG金字塔)、图像金字塔
    图像处理与计算机视觉的经典书籍
    霍夫变换
    熔断原理与实现Golang版
    如何利用go-zero在Go中快速实现JWT认证
    如何让服务在流量暴增的情况下保持稳定输出
    企业级RPC框架zRPC
  • 原文地址:https://www.cnblogs.com/fuland/p/4001063.html
Copyright © 2011-2022 走看看