使dubbo2.js在eggjs项目中可配置化

使用步骤:

  1. 引入依赖包
npm install dubbo2.js require-all --save
  1. 改造app.js获取dubbo2.js的配置方式
const { Dubbo, setting } = require('dubbo2.js');
const fs = require('fs');
const dubboServices = require('require-all')({
  dirname: __dirname + '/app/dubbo_services'
});

class AppBootHook {
  constructor(app) {
    this.app = app;
  }

  async willReady() {
    const app = this.app;
    const dubboSettingArr = [];
    const serviceObj = {};

    Object.keys(dubboServices).forEach(item => {
      const aSetting = dubboServices[item];
      const { basic, service: aService } = aSetting.provider(app);
      dubboSettingArr.push(basic);
      Object.assign(serviceObj, aService);
    });

    const dubboSetting = (() => {
      let ds = null;
      dubboSettingArr.forEach(item => {
        if (ds === null) {
          ds = setting.match(item.address, item.config);
        } else {
          ds = ds.match(item.address, item.config);
        }
      });
      return ds;
    })();

    const dubbo = Dubbo.from({
      application: {
        name: 'hello-dubbo'
      },
      register:'注册中心地址',
      service: serviceObj,
      dubboSetting
    });

    try {
      await dubbo.ready();
    } catch (ex) {
      app.logger.error('dubbo.ready()失败', ex);
    }

    this.app.dubbo = dubbo;

  }
}

module.exports = AppBootHook;
  1. 新建dubbo2服务的配置文件
    新建文件app/dubbo_services/name.js
    内容参考如下:
const { java } = require('dubbo2.js');

exports.provider = app => {
  return {
    basic: {
      address: ['com.bbb.aaa.someService'
      ],
      config: {
        version:'0.0.1'
      }
    },
    service: {
      SomeServiceProvider: dubbo => dubbo.proxyService({
        dubboInterface: 'com.bbb.aaa.someService',
        methods: {
          queryTask(param) {
            return [
              java.combine('com.bbb.aaa.model.someDTO', param)
            ];
          },
        }
      }),
    }
  };
};

  1. 调用dubbo2服务
    在Controller或者Service中执行如下代码,便能获取到rpc返回结果。
    res是正常响应信息,err是异常信息。
const { res, err } =  = await this.ctx.app.dubbo.service.SomeServiceProvider.queryTask(result.data.documentDTO);

你可能感兴趣的:(使dubbo2.js在eggjs项目中可配置化)