nodejs rpc
sonorpc是一个轻量级、高性能的node rpc框架,由Registry(注册中心)、Provider(服务提供者)、Consumer(服务消费者)组成,提供远程方法调用、负载均衡、服务自动注册和发现功能。
npm install sonorpc
app/config.js
exports.mysql = {
host: '',
user: '',
password: '',
database: '',
};
app/service/demo.js
const { Service } = requie("sonorpc");
class DemoService extends Service {
async sayHello(arg1, arg2) {
const result = await this.app.mysql.query('select * from user');
return {
success: true,
data: result
};
}
}
scripts/start.js
require('sonorpc').startProvider();
scripts/registry.js
const { startRegistry } = require('sonorpc');
startRegistry({
port: 3006
});
consumer.js
const { registerConsumer } = require('sonorpc');
const consumer = registerConsumer({
// 服务提供者名称
providerName: 'user',
registry: {
port: 3006
}
});
module.exports = consumer;
service/DemoService.js
const consumer = require('../consumer');
class DemoService {
testMe(...args) {
return consumer.invoke('demo.testMe', args);
}
}