egg-rpc4js

2.2.0 • Public • Published

egg-rpc4js

NPM version build status Test coverage David deps Known Vulnerabilities npm download

依赖说明

依赖的 egg 版本

egg-rpc4js 版本 egg 1.x
1.x 😁
0.x

依赖的插件

安装插件

$ npm i egg-rpc4js
或者
$ yarn add egg-rpc4js

开启插件

// config/plugin.js
exports.rpc4js = {
  enable: true,
  package: 'egg-rpc4js',
};

使用场景

  • Why and What: 微服务架构一个主要的问题就是服务间通讯,传统的HttpClient方式性能低、过程复杂,因而采用sofarpc的node版本替代传统方案,sofarpc实现了服务注册、发现、负载均衡、故障熔断等功能,本项目作为sofa-rpc-node的 egg 插件版本,帮助开发者更快的集成rpc功能。
  • How: 本插件依赖 zookeeper 作为注册中心,应先在本地或服务器上部署 zookeeper,默认启动端口为 2181

详细配置

exports.rpc4js = {
    registry: {
        address: '127.0.0.1:2181' // zookeeper地址 根据实际情况配置
    },
    client: {
        services: [{
            namespace: 'account', // 服务命名空间
            modules: ['wallet', 'security'] // 选择消费该服务下的模块功能
        }],
        responseTimeout: 3000 // 响应超时(单位:ms)
    },
    server: {
        namespace: 'market', // 服务命名空间
        port: 12200 // 监听端口
    }
}

接口实现

rpc应用目录结构:

egg-example
├── app
│   ├── controller // 普通接口实现目录
│   │   └── home.js
|   ├── rpc // RPC接口实现目录
|   |   └── m1.js
|   |   └── m2.js
│   └── router.js
├── config
│   └── config.default.js
└── package.json

实现类:

// ${baseDir}/app/rpc/handler.js
'use strict';
 
class Handler {
    constructor(app, ctx) {
        this.app = app;
        this.ctx = ctx;
    }
 
    async getUser() {
        // ...
    }
    // ...
}
 
module.exports = Handler;

调用RPC服务

// ...
await ctx.rpc.namespace.module.interfaceName(...args);
// 或者
await app.rpc.namespace.module.interfaceName(...args);
/**
 * 说明
 * namespace 为服务命名空间
 * module 为该服务提供的rpc模块
 * interfaceName 为该模块的接口
 * 
 * 请在使用中根据实际情况进行替换
 * /

单元测试

提问交流

请到 egg-rpc4js issues 异步交流。

License

MIT

Dependents (0)

Package Sidebar

Install

npm i egg-rpc4js

Weekly Downloads

1

Version

2.2.0

License

MIT

Unpacked Size

9.75 kB

Total Files

6

Last publish

Collaborators

  • iamljw