拥抱大家庭,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
1
2
3
4
5
6
7
8
9
10
11 |
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 |
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 |
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,小功告成。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。