nodejs 微服务框架 seneca

Author Avatar
Splendour 8月 11, 2015

seneca 是基于nodejs的一个微服务框架,支持插件式开发,每一个微服务都是一个小插件。

个人想法是将项目中对不同的数据库进行的操作开发为一个个微服务,提供接口供主程序调用,减轻主程序压力。

下面以 contact 为例,讲述如何添加 web 微服务。

  • 往 app.js 中添加 client,分配端口
    var seneca = require('seneca')()
    .use('api')
    .client({port: 9001, pin: 'role:contact'});
    var app = require('express')()
    .use(require('body-parser').json())
    .use(seneca.export('web'))
    .listen(3003);
    
  • 在 api.js 中,添加路由,并在 init:api 方法下初始化路由。注意有参数时的处理!
    module.exports = function api(options) {
    var valid_ops = {sum: 'sum', product: 'product'}
    this.add('role:api,path:contact', function (msg, respond) {
      var contactMsg = {
        role: 'contact',
        cmd: msg.action
      };
      // 不同方法带有参数,需要在此传入
      if ('findOne' === msg.action) {
        contactMsg.username = msg.username;
      }
      if ('search' === msg.action) {
        contactMsg.keyword = msg.keyword;
      }
      this.act(contactMsg, respond)
    });
    this.add('init:api', function (msg, respond) {
      this.act('role:web', {
        use: {
          prefix: '/api',
          pin: 'role:api,path:*',
          map: {
            contact: {GET: true, suffix: '/:action'}
          }
        }
      });
      respond();
    })
    };
    
  • 新建 contact-pin-service.js 文件,运行该文件时提供服务,注意这里的 listen 要和第一步中添加到 app.js 中的一致
    require('seneca')()
    .use('contact')
    .listen({port: 9001, pin: 'role:contact'});
    
  • 新建 contact 文件,提供服务的主逻辑
    module.exports = function contact(options) {
    this.add('role:contact,cmd:left', function left(msg, respond) {
      respond(null, {result: 'test'})
    });
    };
    

现在,只需要启动 app.js 微服务主线程

node app.js

再启动 contact-pin-service.js 服务线程

node contact-pin-service.js

就可以使用 contact 微服务了~

想要查看详细 log,可以在运行线程时添加指令

node contact-pin-service.js --seneca.log=plugin:contact