擁抱你們庭,nodejs走thrift。最賤的例子,nodejs與nodejs之間走thrift對傳。javascript
1,官網下載java
http://mirrors.cnnic.cn/apache/thrift/0.9.1/thrift-0.9.1.exe node
2,編輯xuser.thriftapache
struct User{ 1: string uid, 2: string uname, 3: bool usex, 4: i16 uage } service UserService{ void add(1: User u), string adduname(1: string uname), User get(1: string uid) }
3,生成IDLnpm
thrift --gen js:node xuser.thriftui
4,目錄下會多出文件spa
5,編輯server.js3d
var thrift=require("thrift"); var UserService=require('./gen-nodejs/UserService.js'); var ttypes=require('./gen-nodejs/xuser_types'); var users={}; var server=thrift.createServer(UserService, { add:function(user,callback){ console.log("add stored:",user.uname); users[user.uid]=user; console.log(users); callback();}, adduname:function(x,callback){ console.log("adduname stored:",x); callback(null,"MMMMM"); }, get:function(uid,callback){ console.log("get received:", uid); console.log(users[uid]); callback(null,users[uid]); } } ); server.listen(3000); console.log("server start"); server.on("error",function(e){ console.log(e); });
6,編輯client.jsserver
var thrift =require('thrift'); var UserService = require('./gen-nodejs/UserService.js'); var ttypes = require('./gen-nodejs/xuser_types'); var connection = thrift.createConnection('127.0.0.1', 3000); var client = thrift.createClient(UserService, connection); connection.on("error",function(e) { console.log(e); }); var x=new ttypes.User({ uid:'112', uname:'aab', usex:0, uage:'181' }); client.add(x,function(err, res){ console.log("ADD OK1"); client.get('112',function(err, res){ if (err) { console.error(err); } else { console.log("Res:",res); connection.end(); } }); client.adduname('112',function(err, res){ if (err) { console.error(err); } else { console.log("Res:",res); connection.end(); } }); });
7,裝nodejs的thrift包blog
npm install thrift
8,node server.js
9,node client.js
OK,小功告成。