slf4j-api-1.5.6.jar slf4j-log4j12-1.5.6.jar log4j-1.2.14.jar libthrift-0.9.1.jar thrift-0.9.1.exe
namespace java com.zero.thrift # 定义生成代码的命名空间,与定义的package相对应 struct User{ 1:i64 id, 2:string name, 3:i64 timestamp, 4:bool vip } service IUserService{ User getById(1:i64 id) }
package com.zero.thrift; import java.util.Date; import org.apache.thrift.TException; public class UserServiceImpl implements IUserService.Iface{ @Override public User getById(long id) throws TException { // TODO Auto-generated method stub System.out.println("getById()..."); return new User(10000L, "zero", new Date().getTime(), true); } }
package com.zero.thrift; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TBinaryProtocol.Factory; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TSimpleServer; import org.apache.thrift.transport.TServerSocket; public class TSimpleServerDemo { public static void main(String[] args) { // TODO Auto-generated method stub new TSimpleServerDemo().startServer(); } public void startServer() { try { System.out.println("TSimpleServer start ...."); // 设置服务器端口为7911 TServerSocket serverTransport = new TServerSocket(7911); // 设置协议工厂为TBinaryProtocol.Factory Factory protocolFactory = new TBinaryProtocol.Factory(); // 关联IUserService.Processor处理器与IUserService服务的实现类UserServiceImpl TProcessor processor = new IUserService.Processor<IUserService.Iface>( new UserServiceImpl()); TServer.Args tArgs = new TServer.Args(serverTransport); tArgs.processor(processor); tArgs.protocolFactory(protocolFactory); TServer server = new TSimpleServer(tArgs); server.serve(); } catch (Exception e) { System.out.println("Server start error!!!"); e.printStackTrace(); } } }TSimpleClientDemo.java
package com.zero.thrift; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; public class TSimpleClientDemo { public static void main(String[] args) { // TODO Auto-generated method stub new TSimpleClientDemo().startClient(); } public void startClient() { TTransport transport = null; try { transport = new TSocket("localhost", 7911, 5000); // 协议要和服务端一致 TProtocol protocol = new TBinaryProtocol(transport); // TProtocol protocol = new TCompactProtocol(transport); // TProtocol protocol = new TJSONProtocol(transport); IUserService.Client client = new IUserService.Client( protocol); transport.open(); User user = client.getById(1000L); user.setName(user.getName()+"007"); System.out.println("TSimpleClientDemo client, result = " + user); } catch (TTransportException e) { e.printStackTrace(); } catch (TException e) { e.printStackTrace(); } finally { if (null != transport) { transport.close(); } } } }客户端运行结果:
TSimpleClientDemo client, result = User(id:10000, name:zero007, timestamp:1442977728903, vip:true)
package com.zero.thrift; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TBinaryProtocol.Factory; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.transport.TServerSocket; public class TThreadPoolServerDemo { public static void main(String[] args) { // TODO Auto-generated method stub new TThreadPoolServerDemo().startServer(); } public void startServer() { try { System.out.println("TThreadPoolServer start ...."); // 设置服务器端口为7911 TServerSocket serverTransport = new TServerSocket(7911); // 设置协议工厂为TBinaryProtocol.Factory Factory protocolFactory = new TBinaryProtocol.Factory(); // 关联IUserService.Processor处理器与IUserService服务的实现类UserServiceImpl TProcessor processor = new IUserService.Processor<IUserService.Iface>( new UserServiceImpl()); TThreadPoolServer.Args tArgs = new TThreadPoolServer.Args( serverTransport); tArgs.processor(processor); tArgs.protocolFactory(protocolFactory); // 线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。 TServer server = new TThreadPoolServer(tArgs); server.serve(); } catch (Exception e) { System.out.println("Server start error!!!"); e.printStackTrace(); } } }TThreadPoolClientDemo.java
package com.zero.thrift; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; public class TThreadPoolClientDemo { public static void main(String[] args) { // TODO Auto-generated method stub new TThreadPoolClientDemo().startClient(); } public void startClient() { TTransport transport = null; try { // 设置传输通道 transport = new TSocket("localhost", 7911, 5000); // 协议要和服务端一致 TProtocol protocol = new TBinaryProtocol(transport); // TProtocol protocol = new TCompactProtocol(transport); // TProtocol protocol = new TJSONProtocol(transport); IUserService.Client client = new IUserService.Client(protocol); transport.open(); long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { User user = client.getById(1000L); user.setName(user.getName() + "007"); System.out .println("TThreadPoolClientDemo client, result = " + user); } System.out.println("耗时:" + (System.currentTimeMillis() - start)); } catch (TTransportException e) { e.printStackTrace(); } catch (TException e) { e.printStackTrace(); } finally { if (null != transport) { transport.close(); } } } }
package com.zero.thrift; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TBinaryProtocol.Factory; import org.apache.thrift.server.TNonblockingServer; import org.apache.thrift.server.TServer; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TNonblockingServerSocket; public class TNonblockingServerDemo { public static void main(String[] args) { // TODO Auto-generated method stub new TNonblockingServerDemo().startServer(); } public void startServer() { try { System.out.println("TNonblockingServer start ...."); // 设置服务器端口为7911 TNonblockingServerSocket tnbSocketTransport = new TNonblockingServerSocket( 7911); // 设置协议工厂为TBinaryProtocol.Factory Factory protocolFactory = new TBinaryProtocol.Factory(); // 关联IUserService.Processor处理器与IUserService服务的实现类UserServiceImpl TProcessor processor = new IUserService.Processor<IUserService.Iface>( new UserServiceImpl()); TNonblockingServer.Args tArgs = new TNonblockingServer.Args( tnbSocketTransport); tArgs.processor(processor); tArgs.protocolFactory(protocolFactory); tArgs.transportFactory(new TFramedTransport.Factory()); // 使用非阻塞式IO,服务端和客户端需要指定TFramedTransport数据传输的方式 TServer server = new TNonblockingServer(tArgs); server.serve(); } catch (Exception e) { System.out.println("Server start error!!!"); e.printStackTrace(); } } }TNonblockingClientDemo.java
package com.zero.thrift; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; public class TNonblockingClientDemo { public static void main(String[] args) { // TODO Auto-generated method stub new TNonblockingClientDemo().startClient(); } public void startClient() { TTransport transport = null; try { transport = new TFramedTransport(new TSocket("localhost", 7911, 5000)); transport.open(); // 协议要和服务端一致 TProtocol protocol = new TBinaryProtocol(transport); IUserService.Client client = new IUserService.Client(protocol); long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { User user = client.getById(1000L); user.setName(user.getName() + "007"); System.out.println("TNonblockingClientDemo client, result = " + user); } System.out.println("耗时:" + (System.currentTimeMillis() - start)); } catch (TTransportException e) { e.printStackTrace(); } catch (TException e) { e.printStackTrace(); } finally { if (null != transport) { transport.close(); } } } }
package com.zero.thrift; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.THsHaServer; import org.apache.thrift.server.TServer; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TNonblockingServerSocket; public class THsHaServerDemo { public static void main(String[] args) { // TODO Auto-generated method stub new THsHaServerDemo().startServer(); } public void startServer() { try { System.out.println("THsHaServer start ...."); TProcessor tprocessor = new IUserService.Processor<IUserService.Iface>( new UserServiceImpl()); TNonblockingServerSocket tnbSocketTransport = new TNonblockingServerSocket( 7911); THsHaServer.Args thhsArgs = new THsHaServer.Args(tnbSocketTransport); thhsArgs.processor(tprocessor); thhsArgs.transportFactory(new TFramedTransport.Factory()); thhsArgs.protocolFactory(new TBinaryProtocol.Factory()); // 半同步半异步的服务模型 TServer server = new THsHaServer(thhsArgs); server.serve(); } catch (Exception e) { System.out.println("Server start error!!!"); e.printStackTrace(); } } }客户端同TNonblockingClientDemo,只需要注意传输协议一致以及指定传输方式为TFramedTransport。
package com.zero.thrift; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.async.TAsyncClientManager; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.transport.TNonblockingSocket; import org.apache.thrift.transport.TNonblockingTransport; import com.zero.thrift.IUserService.AsyncClient.getById_call; public class AsynClientDemo { public static void main(String[] args) { // TODO Auto-generated method stub new AsynClientDemo().startClient(); } public void startClient() { try { // 异步调用管理器 TAsyncClientManager clientManager = new TAsyncClientManager(); // 设置传输通道,调用非阻塞IO TNonblockingTransport transport = new TNonblockingSocket( "localhost", 7911, 5000); // 设置协议 TProtocolFactory tprotocol = new TBinaryProtocol.Factory(); // 创建Client IUserService.AsyncClient asyncClient = new IUserService.AsyncClient( tprotocol, clientManager, transport); System.out.println("Client start ....."); CountDownLatch latch = new CountDownLatch(1); AsynCallback callBack = new AsynCallback(latch); System.out.println("call method sayHello start ..."); asyncClient.getById(1000L, callBack); System.out.println("call method sayHello .... end"); boolean wait = latch.await(5, TimeUnit.SECONDS); System.out.println("latch.await = " + wait); } catch (Exception e) { e.printStackTrace(); } System.out.println("startClient end."); } public class AsynCallback implements AsyncMethodCallback<IUserService.AsyncClient.getById_call> { private CountDownLatch latch; public AsynCallback(CountDownLatch latch) { this.latch = latch; } @Override public void onComplete(getById_call response) { System.out.println("onComplete"); try { System.out.println("AsynCall result =:" + response.getResult().toString()); } catch (TException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { latch.countDown(); } } @Override public void onError(Exception exception) { System.out.println("onError :" + exception.getMessage()); latch.countDown(); } } }运行结果:
Client start ..... call method sayHello start ... call method sayHello .... end onComplete AsynCall result =:User(id:10000, name:zero, timestamp:1442989991561, vip:true) latch.await = true startClient end.