Express项目中使用RPC读写分离 - const port = 3000
在Express项目中使用RPC读写分离,可以通过以下步骤实现:
express-rpcexpress-rpc-server
npm install express-rpc express-rpc-server
server.js
const express = require('express');
const rpc = require('express-rpc');
const server = express();
const port = 3000;
// 定义RPC接口
const rpcInterfaces = {
getUser: (id) => `Hello, I am user with id: ${id}`,
addUser: (user) => `Add a new user with id: ${user.id}`,
};
// 创建RPC服务器
const rpcServer = rpc({
interfaces: rpcInterfaces,
});
// 监听端口
server.listen(port, () => {
console.log(`RPC server is running on port ${port}`);
});
server.js
node server.js
app.js
const express = require('express');
const rpc = require('express-rpc');
const app = express();
const port = 3000;
// 创建RPC客户端
const client = new rpc.Client({
url: 'http://localhost:' + port,
protocol: 'https',
});
// 调用服务端的方法
client.call('getUser', 1)
.then((result) => {
console.log(result); // 输出:Hello, I am user with id: 1
})
.catch((error) => {
console.error(error);
}); 拼多多帮助力入口
运行客户端:
node app.js
现在,客户端可以向服务端发起RPC调用,服务端会返回相应的结果。