安装
下载
下载地址:http://archive.apache.org/dist/thrift/0.10.0/
将thrift-0.10.0.exe放到一个文件下,如f:\thrift下,将其重命名为thrift.exe。如果不重命名,需要使用thrift-0.10.0调用thrift命令。
配置环境变量
向path
中添加变量值,值为thrift.exe
的地址,如f:\thrift。
测试
命令行输入thrift -version
,如果输出thrift的版本即表明安装成功。
使用
编写idl接口
helloservice.thrift
1
2
3
4
|
namespace java com.thrift.demo.service service helloservice{ string sayhello( 1 :string username) } |
编译
编译之后会生成类helloservice
。
1
|
thrift -gen java helloservice.thrift |
编写实现类
helloserviceimpl.java
1
2
3
4
5
6
|
public class helloserviceimpl implements helloservice.iface { @override public string sayhello(string username) throws texception { return "hello thrift service : " + username; } } |
编写服务端代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class helloserver { public static final int server_port = 8090 ; public void startserver() { try { system.out.println( "helloservice tsimpleserver start ...." ); tprocessor tprocessor = new helloservice.processor<helloservice.iface>( new helloserviceimpl()); // 简单的单线程服务模型,一般用于测试 tserversocket servertransport = new tserversocket(server_port); tserver.args targs = new tserver.args(servertransport); targs.processor(tprocessor); targs.protocolfactory( new tbinaryprotocol.factory()); tserver server = new tsimpleserver(targs); server.serve(); } catch (exception e) { system.out.println( "server start error!!!" ); e.printstacktrace(); } } public static void main(string[] args) { helloserver server = new helloserver(); server.startserver(); } } |
编写客户端代码
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
|
public class helloclient { public static final string server_ip = "localhost" ; public static final int server_port = 8090 ; public static final int timeout = 30000 ; public void startclient(string username) { ttransport transport = null ; try { transport = new tsocket(server_ip, server_port, timeout); // 协议要和服务端一致 tprotocol protocol = new tbinaryprotocol(transport); helloservice.client client = new helloservice.client(protocol); transport.open(); string result = client.sayhello(username); system.out.println( "thrify client result =: " + result); } catch (ttransportexception e) { e.printstacktrace(); } catch (texception e) { e.printstacktrace(); } finally { if ( null != transport) { transport.close(); } } } public static void main(string[] args) { helloclient client = new helloclient(); client.startclient( "michael" ); } } |
运行
先运行服务端,再运行客户端。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接
原文链接:https://blog.csdn.net/sinat_28394909/article/details/84645782