egg-grpc-server
Install
npm install egg-plugin-grpc-server --save
Usage
// {app_root}/config/plugin.jsexportsgrpcServer = enable: true package: 'egg-plugin-grpc-server';
Configuration
// {app_root}/config/config.default.jsexportsgrpcServer = port: 50051 // grpc监听端口 host: '127.0.0.1' // 监听地址 timeOut: 5000 // 超时时间 protoDir: 'app/proto' // proto文件所在文件夹 grpcDir: 'app/grpc' // 接口实现所在文件夹 { // 全局统一错误处理 // TODO // this 为ctx,接受error参数 };
see config/config.default.js for more detail.
Example
启动
- 插件在app上挂载了GrpcServer的class,需要在项目启动时实例化并调用start方法
- 启动方式一:直接在app.js实例化并启动不推荐(在多进程模式下会报错)
// ${app_root}/app.jsmodule { const grpcServer = app; grpcServerstart; Reflect;};
- 启动方式二:使用cluster-client管理启动
- agent上创建leader,管理work中server实例
// ${app_root}/app.jsmodule { const registryClient = app app // 退出时关闭 grpc server 并 像 leader 发送 close 信号 app process process}
// ${app_root}/agent.jsmodule { const registryClient = agent agent process}
- proto/xxx.proto service中的的接口名 grpc/xxx.js 中的接口名 二者应当同名(grpc/xxx.js文件名可不大写)
config.dir
配置目录,默认app/proto
proto 文件,可通过
// {app_root}/app/protos/hello.protosyntax = "proto3"; package eggnode; service Hello rpc {}; rpc {}; message HelloReq string name = 1; int32 group = 2; message HelloResp int32 code = 1; string message = 2; message BufRequest string name = 1; message BufResp string message = 1; int32 code = 2;
this
为egg
的Context
,接受一个参数为请求的call
(grpc中的call,call.request
为请求参数)
接口实现, // {app_root}/app/grpc/hello.js'use strict'; exports { const request = call; { return { ; }; } await ; return code: 200 message: 'hello ' + requestname + ', you are in ' + requestgroup ;}; exports { call; call;};
单元测试
- 在
unittest
环境中app挂载了grpcServerTest
方法用于测试
const assert app = ;const path = ;const PROTO_PATH_HELLO = path;const grpc = ;
Questions & Suggestions
Please open an issue here.