1.在node.js 服务下创建node_modules文件,npm install thrift 下载thrift到该文件下。
2.编写idl文件。user.thrift 内容如下:
struct User{
1: string uid,
2: string uname,
3: bool usex,
4: i16 uage,
}
service UserService{
void add(1: User u),
User get(1: string uid),
}
3.生成代码:
运行:thrift --gen js:node user.thrift
会在当前目录下生成一个gen -nodejs文件夹,里面就是我们需要的js代码,将js代码拷贝到我们的项目中。
4.创建node.js服务段和客户端
服务端:
var thrift = require(‘thrift‘);
var UserService = require(‘./gen-nodejs/UserService.js‘),
ttypes = require(‘./gen-nodejs/user_types‘);
var users = {};
var server = thrift.createServer(UserService, {
add: function(user, callback) {
console.log("server stored:", user.uname);
users[user.uid] = user;
callback();
}
});
server.listen(7911);
console.log(‘server start‘);
客户端:
var thrift = require(‘thrift‘);
var UserStorage = require(‘./gen-nodejs/UserStorage.js‘),
ttypes = require(‘./gen-nodejs/user_types‘);
var connection = thrift.createConnection(‘localhost‘, 9090),
client = thrift.createClient(UserStorage, connection);
var user = new ttypes.UserProfile({uid: 1,
name: "Mark Slee",
blurb: "I‘ll find something to put here."});
connection.on(‘error‘, function(err) {
console.error(err);
});
client.store(user, function(err, response) {
if (err) {
console.error(err);
} else {
console.log("client stored:", user.uid);
client.retrieve(user.uid, function(err, responseUser) {
if (err) {
console.error(err);
} else {
console.log("client retrieved:", responseUser.uid);
connection.end();
}
});
}
});
现在就可以测试了。