Coder Social home page Coder Social logo

egg-dubbo-rpc's Introduction

egg-dubbo-rpc

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

Dubbo RPC plugin for Egg.js

Install

$ npm i egg-dubbo-rpc --save

Usage

1. Enable the Plugin

enable egg-dubbo-rpc plugin in ${app_root}/config/plugin.js:

// {app_root}/config/plugin.js
exports.dubboRpc = {
  enable: true,
  package: 'egg-dubbo-rpc',
};

2. Configuration

// @example
exports.rpc = {
  registry: {
    address: '127.0.0.1:2181', // configure your real zk address
  },
  client: {
    responseTimeout: 3000,
  },
  server: {
    namespace: 'org.eggjs.rpc.test',
    port: 12200,
    maxIdleTime: 90 * 1000,
    codecType: 'hessian2',
    selfPublish: true,
    version: '1.0.0',
    group: 'DUBBO',
    autoServe: true,
  },
};

all configuations is under rpc property

  • registry (we use zookeeper as service registry in dubbo)
    • address:(required) the zookeeper address
  • client
    • responseTimeout:(optional) number of milliseconds to wait for a response, if timeout will get an exception, the default value is 3000(ms)
  • server
    • namespace:(required) the default namespace to publish all services
    • port:(optional) the port which RPC server listening on, the default value is 12200
    • maxIdleTime:(optional) maximum idle time (in milliseconds) for a connection
    • codecType:(optional) the serialization type, default value is hessian2
    • selfPublish:(optional) if set to true (default), every worker process will listen on different ports
    • version:(optional) the service version, default value is 1.0.0
    • group:(optional) the service group, default value is DUBBO
    • autoServe:(optional) if set to true (default), will launce Dubbo RPC server automatically

3. Call Dubbo Services as Consumer

Configure the Interface in proxy.js

First, you need to put the JAR file (which contains the API interfaces) into {app_root}/assembly folder.

And then you need to config $app_root/config/proxy.js, which is a very important config file for RPC client, you should configure the services you needed, then executing the egg-rpc-generator tool to generate the proxy files.

Let's see a simple example of proxy.js. It declare a interface named: org.eggjs.dubbo.UserService provided by dubbo application

'use strict';

module.exports = {
  group: 'HSF',
  version: '1.0.0',
  services: [{
    appName: 'dubbo',
    api: {
      UserService: {
        interfaceName: 'org.eggjs.dubbo.UserService',
      },
    },
    dependency: [{
      groupId: 'eggjs',
      artifactId: 'dubbo-demo-api',
      version: '1.0-SNAPSHOT',
    }],
  }],
};

details as follows:

  • version:(optional) service version, the global config
  • group:(optional) service group
  • errorAsNull:(optional) if set true, we are returning null instead of throwing an exception while error appears
  • services:(required) RPC services configuation
    • appName:(required) the name of RPC provider
    • api:(required) API details
      • interfaceName:(required) interface name
      • version:(optional) service version, it will overwrite the global one
      • group:(optional) service group, it will overwrite the global one
    • dependency:(required) like Maven pom config
      • groupId:(required) uniquely identifies your project across all projects
      • artifactId:(required) the name of the jar without version
      • version:(required) the jar version

Generate the Proxy

Run egg-rpc-generator to generate the proxy files. After running success, it will generate all proxy files under ${app_root}/app/proxy

install egg-rpc-generator

$ npm i egg-rpc-generator --save-dev

add rpc command into scripts of package.json

{
  "scripts": {
    "rpc": "egg-rpc-generator"
  },
}

execute the rpc command

$ npm run rpc

Call Dubbo Service

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

'use strict';

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

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    const result = await ctx.proxy.userService.echoUser({
      id: 123456,
      name: 'gxcsoccer',
      address: 'Space C',
      salary: 100000000,
    });
    ctx.body = result;
  }
}

module.exports = HomeController;

Unittest of RPC Client in Egg.js

you can use app.mockProxy to mock the RPC interface

'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) {
      return 'hello ' + name + ' from mock';
    });

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

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

4. Expose Dubbo Services as Provider

Define the RPC Interface

create a JAR file that contains the API interface

Implemenation the RPC Interface

Put your implementation code under ${app_root}/app/rpc folder

// ${app_root}/app/rpc/UserService.js
exports.echoUser = async function(user) {
  return user;
};

exports.interfaceName = 'org.eggjs.dubbo.UserService';
exports.version = '1.0.0';
exports.group = 'DUBBO';

Unittest of your RPC Server in Egg.js

'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.dubbo.UserService')
      .invoke('echoUser')
      .send([{
        id: 123456,
        name: 'gxcsoccer',
        address: 'Space C',
        salary: 100000000,
      }])
      .expect({
        id: 123456,
        name: 'gxcsoccer',
        address: 'Space C',
        salary: 100000000,
      }, done);
  });
});

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

Reference List

Questions & Suggestions

Please open an issue here.

License

Apache License V2

egg-dubbo-rpc's People

Contributors

beiwei30 avatar gxcsoccer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

egg-dubbo-rpc's Issues

some actions for transfer to dubbo group

  • Make sure the project is under Apache License V2
  • Make sure every source files contain Apache license header
  • Make sure all comments, documentation, README are in English
  • Pls. contact @ralf0131 to sign ICLA.

咋npm还是1.0.0呢

我看你的release是1.2.1了,但是npm上还是1.0.0,能不能发布更新呢

请问这一步是什么意思?

请问这一步是什么意思?
First, you need to put the JAR file (which contains the API interfaces) into {app_root}/assembly folder.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.