egg-rpc-base

rpc base plugin for eggjs

egg-rpc

egg-rpc plugin for egg framework

Install

$ npm i egg-rpc-base --save

Usage

Enable the plugin

Change ${app_root}/config/plugin.jsto enable egg-rpc plugin:

exports.rpc = {
  enable: true,
  package: 'egg-rpc-base',
};

RPC Service Discovery

By default, We use zookeeper for service discovery. Therefore you need to configure the zk address:

// ${app_root}/config/config.${env}.js
config.rpc = {
  registry: {
    address: '127.0.0.1:2181', // configure your real zk address
  },
};

We plan to provide more implementations of service discovery. And also you can implement it by yourself, you can follow this article

RPC Client

By using the plugin, you can call rpc services provided by other system.

1. Get the RPC Interface Definition

We use protobuf interface definition lanagugeto describe the RPC service. So you need to get the *.proto files and put them into ${app_root}/protofolder

2. Global RPC Client Configuration

Configure RPC Client information in ${app_root}/config/config.{env}.js:

// ${app_root}config/config.${env}.js
exports.rpc = {
  client: {
    responseTimeout: 3000,
  },
};
  • responseTimeout(optional): RPC timeout in milliseconds, default value is 3000

3. Configure the Interface in proxy.js

${app_root}/config/proxy.jsis a very important config file for rpc client, you should configure the services you needed, then executing the egg-rpc-generatortool to generate the proxy files.

Let's see a simple example of proxy.js. It declare a interface named: org.eggjs.rpc.test.ProtoServiceprovided by rpc-demoapplication

'use strict';

module.exports = {
  services: [{
    appName: 'rpc-demo',
    api: {
      ProtoService: 'org.eggjs.rpc.test.ProtoService',
    },
  }],
};

Refer this acticlefor more details

4. Generate the Proxy

Run egg-rpc-generatorto generate the proxy files. After running success, it will generate a file: ProtoService.jsunder ${app_root}/app/proxy

$ egg-rpc-generator

[EggRpcGenerator] framework: /egg-rpc-demo/node_modules/egg, baseDir: /egg-rpc-demo
[ProtoRPCPlugin] found "org.eggjs.rpc.test.ProtoService" in proto file
[ProtoRPCPlugin] save all proto info into "/egg-rpc-demo/run/proto.json"

5. Call the Service

You can call the RPC service by using ctx.proxy.proxyName. The proxyName is keyvalue of api object you configure in proxy.js. In our example, it's ProtoService, and proxyName using lower camelcase, so it's ctx.proxy.protoService

'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    const res = await ctx.proxy.protoService.echoObj({
      name: 'gxcsoccer',
        group: 'A',
    });
    ctx.body = res;
  }
}

module.exports = HomeController;

As above, you can call remote service as a local method.

RPC Server

By using the plugin, you also can publish your own RPC service to other system.

1. Define the RPC Interface

Writing the *.proto files, and put them into ${app_root}/protofolder

# ProtoService.proto
syntax = "proto3";

package org.eggjs.rpc.test;
option java_multiple_files = true; // 可选
option java_outer_classname = "ProtoServiceModels"; // 可选

service ProtoService {
    rpc echoObj (EchoRequest) returns (EchoResponse) {}
}

message EchoRequest {
    string name = 1;
    Group group = 2;
}

message EchoResponse {
    int32 code = 1;
    string message = 2;
}

enum Group {
    A = 0;
    B = 1;
}

2. Global RPC Server Configuration

Configure RPC Server information in ${app_root}/config/config.{env}.js:

module.exports = {
    rpc: {
    server: {
      namespace: 'org.eggjs.rpc.test',
    },
    },
},
  • namespace(required): the default namespace of all rpc service
  • selfPublish(optional): whether every node process publish service independent, default is true
  • port(optional): the TCP port will be listen on
  • maxIdleTime(optional): server will disconnect the socket if idle for long time
  • responseTimeout(optional): Number of milliseconds to wait for a response to begin arriving back from the remote system after sending a request
  • codecType(optional): recommended serialization method,default is protobuf

3. Implemenation the RPC Interface

Put your implementation code under ${app_root}/app/rpcfolder

// ${app_root}/app/rpc/ProtoService.js
exports.echoObj = async function(req) {
  return {
    code: 200,
    message: 'hello ' + req.name + ', you are in ' + req.group,
  };
};

4. RPC Unittest in Eggjs

RPC Client Unittest (mock)

'use strict';

const mm = require('egg-mock');
const assert = require('assert');

describe('test/mock.test.js', () => {
  let app;
  before(async function() {
    app = mm.app({
      baseDir: 'apps/mock',
    });
    await app.ready();
  });
  afterEach(mm.restore);
  after(async function() {
    await app.close();
  });

  it('should app.mockProxy ok', async function() {
    app.mockProxy('DemoService', 'sayHello', async function(name) {
      await sleep(1000);

      return 'hello ' + name + ' from mock';
    });

    const ctx = app.createAnonymousContext();
    const res = await ctx.proxy.demoService.sayHello('gxcsoccer');
    assert(res === 'hello gxcsoccer from mock');
  });
});

RPC Server Unittest

'use strict';

const mm = require('egg-mock');

describe('test/index.test.js', () => {
  let app;
  before(async function() {
    app = mm.app({
      baseDir: 'apps/rpcserver',
    });
    await app.ready();
  });
  after(async function() {
    await app.close();
  });

  it('should invoke HelloService', done => {
    app.rpcRequest('org.eggjs.rpc.test.HelloService')
      .invoke('hello')
      .send([ 'gxcsoccer' ])
      .expect('hello gxcsoccer', done);
  });
});

For more details of app.rpcRequest, you can refer to this acticle

Docs

How to Contribute

Please let us know how can we help. Do check out issuesfor bug reports or suggestions first.

To become a contributor, please follow our contributing guide.

License

MIT

HomePage

https://github.com/eggjs/egg-rpc#readme

Repository

https+https://github.com/eggjs/egg-rpc


上一篇:egg-rpc-generator
下一篇:sofa-rpc-node

相关推荐

  • 阿里 Node 企业级框架 - Egg 10000 Star + 2 years ✨✨✨

    『大吉大利,明早吃蛋。』 底部有文化衫活动邀您参加。 2016 年 9 月,我们在 JSConf China 2016 上宣布了 Egg 开源,至今整整 2 年了。

    2 年前
  • 造轮子 - EGGJS的MySQL操作库

    最近学习eggjs,学习过程中使用官方推荐的MySQL库,感觉官方库不太好用,基础的CURD没问题。但是复杂点的操作就不行了,虽然官方还有一个,但是这个这并不妨碍我造轮子。下面介绍一下我的这个轮子。

    1 年前
  • 造了个 Egg.js 的轮子 - Less.js

    (0简介)0. 简介 (1运行)1. 运行 (11node版本)1.1. Node 版本 Koa2 使用了 async/await 等新语法,请保证 Node 版本在 7.6 及以上。

    2 年前
  • 调整图像在JavaScript中不使用帆布Base-64

    调整图像在JavaScript中不使用帆布Base64...

    2 年前
  • 记一次eggjs+axios传输multipart的纠错过程

    总所周知,egg的csrf策略让post每次都要发送token码验证,为了方便,我在axios的interceptor里作了前置拦截。 结果不幸从此发生! 最开始没有看官方文档,以为csrf应该加在...

    1 年前
  • 蚂蚁金服 Basement 后端云服务正式亮相云栖大会

    Serverless 与前端 作为前端,当我们要开发一个新应用时,可能只要很短时间就可以搞定前端,但涉及服务端,却因为要关注服务器、数据库、文件存储、域名备案等等,需要耗费大量精力。

    2 年前
  • 自己制作微信小程序使用base64字体图标

    问题: 1.微信小程序不能随意使用网络资源,如字体,css文件等 2.不能在小程序中使用字体文件 3.不能使用backgroundposition背景图片定位来使用内部png图片 下面就介绍...

    2 年前
  • 纯前端实现base64图片下载,兼容IE10+

    背景 在项目开发过程中,经常会有图片导出的需求,尤其是带有图表类的应用,通常需要将图表下载导出。 在chrome等新版浏览器中实现base64图片的下载还是比较容易的: 1. 创建一个a标签 ...

    2 年前
  • 浏览器/ HTML力下载影像从src=“数据:image/jpeg;base64…”

    alex(https://stackoverflow.com/users/1000569/alex)提出了一个问题:Browser/HTML Force download of image from ...

    2 年前
  • 浅谈 rpc 通信协议设计

    在讲 rpc 之前,先讲讲通信协议的设计。什么是通讯协议,简单地说,是指通信双方对数据传送控制的一种约定。通信不仅仅是把消息传过去,还要保证消息的准确和可靠。 可以先看看 amp 协议的设计, 对于首...

    2 个月前

官方社区

扫码加入 JavaScript 社区