Thrift连接node.js客户端与python服务端

本地实现不同语言的前后端交互

1. 通过网上其它教程本地安装好node.js与python

2. 定义好后缀名为thrift的接口文件,如下:

service userService {
string test1(1:string name)
}

其中,userService是通过node.js前端所定义的一个变量,而test1是python后端某类的一个函数名。

3. 生成各自的接口文件

thrift -out 存储路径 --gen 接口语言 thrift全称文件名

4. 通过定义好的接口文件开始编写前后端各自的函数:

4.1  python服务端

from gen_py.thri import userService
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer


class Test:
def test1(self, dic):
print("one")
return dic


if __name__ == "__main__":
port = 8000
ip = "127.0.0.1"
# 创建服务端
handler = Test() # 自定义类
processor = userService.Processor(handler) # userService为python接口文件自动生成
# 监听端口
transport = TSocket.TServerSocket(ip, port) # ip与port位置不可交换
# 选择传输层
tfactory = TTransport.TBufferedTransportFactory()
# 选择传输协议
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
# 创建服务端
server = TServer.TThreadedServer(processor, transport, tfactory, pfactory)
print("start server in python")
server.serve()
print("Done")

4.2 node.js客户端

var thrift = require('thrift');
var userService = require('./gen-nodejs/UserService.js');
var ttypes = require('./gen-nodejs/thri_types.js');
// 创建thrift连接,client 这里即可调用nodejs Server or python Server
// 只要接口存根定义的是一致的
var thriftConnection = thrift.createConnection('127.0.0.1', 8000);
// 创建client
var thriftClient = thrift.createClient(userService,thriftConnection);
thriftConnection.on("error",function(e)
{
console.log(e);
});

// 已上是标准定义,以下是自定义
var dic = {name:"yy"}
dic = JSON.stringify(dic);

thriftClient.test1(dic, function(err, res) {
if (err) {
console.log(err);
} else {
console.log('res', res)
}
})

5. 启动服务

5.1 先在终端输入pyhton python后端文件全名,启动服务端;

5.2 再在终端输入node js前端文件全名,启动前端,即可成功。

5.3 如果后端启动失败,请将后端接口文件gen-py改为gen_py。





猜你喜欢

转载自www.cnblogs.com/yyml181231/p/10300470.html