Creating A Thrift Service Step by Step
Posted on Sun 09 October 2011 in 我用(IT)
- 生成基础代码
1) 创建接口定义文件
namespace java com.li3huo.thrift.example
struct UserProfile { 1: i32 uid, 2: string name, 3: string email } service UserStorage { void store(1: UserProfile user), UserProfile retrieve(1: i32 uid) } 2) 生成Java基础代码
thrift -r -gen java:java5 example.thrift2. 在eclipse中编写代码 1) 创建eclipse工程
mkdir java #own code mkdir lib
把以下jar包拷贝入lib文件夹 libthrift-0.7.0.jar slf4j-api-1.5.8.jar log4j-1.2.14.jar slf4j-log4j12-1.5.8.jar
创建java工程
2) 编写服务端代码
首先创建UserStorageHandler,继承UserStorage.Iface,在以下的代码中完成相关逻辑
public class UserStorageHandler implements UserStorage.Iface {public void store(UserProfile user) throws TException { System.out.println("store:"+user); } public UserProfile retrieve(int uid) throws TException { return new UserProfile(uid,"li3huo","twotwo.li@163.com"); }}
然后创建一个简单服务 使用TBinaryProtocol(客户端)配合TServerSocket及TSimpleServer(服务器)
public class SimpleServer { public static final int PORT = 2222;/** * @param args * @throws TException */ @SuppressWarnings("unchecked") public static void main(String[] args) throws TException { // 创建处理器,包含实际处理逻辑UserStorageHandler @SuppressWarnings("rawtypes") final UserStorage.Processor processor = new UserStorage.Processor(new UserStorageHandler()); // 创建简单服务 final TServerTransport socket = new TServerSocket(PORT); final TServer server = new TSimpleServer(new Args(socket).processor(processor)); server.serve(); }}
3) 编写Java客户端代码
public class SimpleClient { public static final int PORT = 2222; public static final String HOST = "localhost"; public static final int SOCKET_TIMEOUT = 1000; //1 second /** * @param args * @throws TException */ public static void main(String[] args) throws TException { //Setup the transport and protocol final TTransport socket = new TSocket(HOST, PORT); final TProtocol protocol = new TBinaryProtocol(socket); final UserStorage.Client client = new UserStorage.Client(protocol); //The transport must be opened before you can begin using socket.open(); //All hooked up, start using the service UserProfile user = client.retrieve(22); System.out.println("get user: " + user); user.setEmail("admin@li3huo.com"); client.store(user); socket.close(); } }
-
启动SimpleServer和SimpleClient
-
reference 1) example http://thrift.apache.org/ 2) Good intro for Java Developers on ociweb.com http://jnb.ociweb.com/jnb/jnbJun2009.html