Thrift快速入门实例
Thrift是Facebook的核心框架之一,使不同的开发语言开发的系统可以通过该框架实现彼此的通信,类似于webservice,但是Thrift提供了近乎变态的效率和开发的方便性,是webservice所不能比拟的。给分布式开发带来了极大的方便。但是这柄利器也有一些不完美。
安装thrift
1、./configure –with-boost=/usr/include
2、make
3、make install
定义接口文件
-
vim chen.thrift
-
#!/usr/local/bin/thrift –gen java
-
namespace java com.chen
-
service Hello{
-
i32 hello()
-
}
生成代码
- thrift –gen java chen.thrift
要使用1.6的jdk 实现server代码:
-
/**
-
* @author 54chen(陈臻) [chenzhen@xiaomi.com cc0cc@126.com]
-
* @since 2011-6-24 下午08:11:15
-
*/
-
package com.chen;
-
import org.apache.thrift.TException;
-
public class HelloImpl implements Hello.Iface {
-
public void HelloImpl() {
-
}
-
public int hello() throws TException {
-
System.out.println(“hello 54chen”);
-
return 0;
-
}
-
}
通过下面的代码启动server
-
TServerSocket serverTransport = new TServerSocket(7911);
-
Hello.Processor processor = new Hello.Processor(new HelloImpl());
-
Factory protFactory = new TBinaryProtocol.Factory(true, true);
-
TServer server = new TThreadPoolServer(processor, serverTransport, protFactory);
-
System.out.println(“Starting server on port 7911 …");
-
server.serve();
通过下面代码启动client
- TTransport transport = new TSocket(“localhost”, 7911);
- TProtocol protocol = new TBinaryProtocol(transport);
- Hello.Client client = new Hello.Client(protocol);
- transport.open();
- System.out.println(“Client calls hello()");
- client.hello();
- transport.close();
原创文章如转载,请注明:转载自五四陈科学院[http://www.54chen.com]
Posted by 54chen java