# 先确认 node 环境是否正常
E:\nodeproject\thriftnodejs>node --version
v12.18.0
# 在项目下,安装 npm 依赖
E:\nodeproject\thriftnodejs>cnpm install thrift --save
√ Installed 1 packages
√ Linked 1 latest versions
√ Run 0 scripts
√ All packages installed (used 208ms(network 205ms), speed 21.03KB/s, json 1(4.31KB), tarball 0B)
E:\JVMDemo\demo2022>thrift --gen js:node src/main/java/thrift/Student.thrift
并将这两个文件复制到 node 项目下
E:\nodeproject\thriftnodejs
var thrift = require("thrift");
var StudentService = require('./StudentService');
// 启动服务器,默认只支持 TBufferedTransport 和 TBinaryProtocol
var server;
var transport = thrift.TFramedTransport;
var protocol = thrift.TBinaryProtocol;
var options = {transport: transport, protocol: protocol};
server = thrift.createServer(StudentService, {
addStudent: function (name, age) {
console.log("--NodeJs服务端,模拟增加操作--");
console.log(name + "," + age + "增加成功!");
return true;
},
queryStudents: function () {
console.log("--NodeJs服务端,模拟查询操作--");
var students = [{name: "zs", age: 23}, {name: "ls", age: 24}];
console.log("--查询完毕--");
return students;
}
}, options);
server.listen(8888);
var thrift = require('thrift');
var StudentService = require('./StudentService.js');
var ttypes = require('./Student_types');
var transport = thrift.TFramedTransport;
var protocol = thrift.TBinaryProtocol;
var options = {transport: transport, protocol: protocol};
var connection = thrift.createConnection("127.0.0.1", 8888, options);
// 创建客户端
client = thrift.createClient(StudentService, connection);
// 处理异常
connection.on('error', function (err) {
console.error(err);
});
client.addStudent("ww", 25, function (err, result) {
console.log(result ? "增加成功" : "增加失败");
});
client.queryStudents(function (err, result) {
result.forEach(function (student, index) {
console.log("查询结果如下:")
console.log(student.name + "," + student.age)
});
});
编写完后的项目结构如下:
Java 服务端打印如下
--Java服务端,模拟增加操作--
增加成功:ww,25
--Java服务端,模拟查询操作--
--查询完毕--
NodeJs 客户端打印如下
E:\nodeproject\thriftnodejs>node thriftClient.js
增加成功
查询结果如下:
zs,23
查询结果如下:
ls,24
客户端打印如下
RPC调用服务端的queryStudents()方法
zs 23
ls 24
RPC调用服务端的addStudent()方法
增加成功!
服务端打印如下
--NodeJs服务端,模拟查询操作--
--查询完毕--
--NodeJs服务端,模拟增加操作--
ww,25增加成功!
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/chengqiuming/article/details/125113328
内容来源于网络,如有侵权,请联系作者删除!