Nodejs thrift协议0.14.1的使用示例

echo.thrift

namespace go echo

struct EchoReq {
    1: required string msg
}

struct EchoRes {
    1: required string msg
}

service Echo {
    EchoRes echo(1: EchoReq req)
}

 如果是win10的话直接下载exe并执行以下命令即可生成js代码,其它系统可能需要编译安装thrift代码生成器。下载地址https://downloads.apache.org/thrift/

thrift-0.14.1.exe -r --gen js:node echo.thrift

生成的目录结构如下: 

gen-nodejs/
├── CookieService.js
├── cookie_types.js
├── Echo.js
└── echo_types.js

安装thrift包

npm install [email protected] --registry=https://registry.npmjs.org/

server.js

var thrift = require("thrift");
var echo = require('./gen-nodejs/Echo.js');
var ttypes = require('./gen-nodejs/echo_types');

var users = {};

//默认传输协议为thrift.TBufferedTransport
//也可以设置为其它传输协议如thrift.TFramedTransport
//默认编码协议为thrift.TBinaryProtocol,
//也可以设置为其它编码协议如:thrift.TCompactProtocol,thrift.TJSONProtocol
var options = {
        transport : thrift.TBufferedTransport
        protocol: thrift.TBinaryProtocol
};

var handler = {
        echo: function(req, callback) {
                console.log("msg:", req.msg);

                callback(null, new ttypes.EchoRes({
                        msg: 'success'
                }));
        }
};
var server = thrift.createServer(echo, handler, options);

server.listen(9898);
console.log("server start");

server.on("error", function(e) {
        console.log(e);
});

client.js

var thrift = require('thrift');

var echo = require('./gen-nodejs/Echo.js');
var ttypes = require('./gen-nodejs/echo_types');

//默认协议为thrift.TBinaryProtocol,
//也可以设置为其它协议如:thrift.TCompactProtocol,thrift.TJSONProtocol
var options = {
        protocol: thrift.TBinaryProtocol
};

var connection = thrift.createConnection('127.0.0.1', 9898, options);
var client = thrift.createClient(echo, connection);

connection.on("error", function(e) {
        console.log(e);
});

connection.on('connect', function() {
        console.log("connected to the thrift server");
});

var x = new ttypes.EchoReq({
        msg: 'You are welcome.'
});

client.echo(x, function(err, res) {
        if (err) {
                console.log(err);
        } else {
                console.log(res);
        }
});

需要注意的是服务端和客户端在protocol参数的设置上必须是相同的协议否则会调用失败。

相关文章:

《thrift协议0.14.1在Nodejs和Go语言之间的跨语言调用的兼容性测试》

猜你喜欢

转载自blog.csdn.net/pengpengzhou/article/details/114885332