拥抱大家庭,nodejs走thrift
拥抱大家庭,nodejs走thrift。最贱的例子,nodejs与nodejs之间走thrift对传。
1,官网下载
http://mirrors.cnnic.cn/apache/thrift/0.9.1/thrift-0.9.1.exe
2,编辑xuser.thrift
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,生成IDL
thrift --gen js:node xuser.thrift
4,目录下会多出文件
5,编辑server.js
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.js
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包
npm install thrift
8,node server.js
9,node client.js
OK,小功告成。