Thrift 非阻塞异步I/O例子

来源:互联网 发布:被x是什么体验 知乎 编辑:程序博客网 时间:2024/05/29 17:59

Thrift支持多路复用I/O通信模型。需要客户端和服务端同时采用异步I/O模型。


HelloService.thrift

namespace java thriftservice HelloService {    string sayHello(1:string name)}

服务器端代码:

import org.apache.thrift.TProcessor;import org.apache.thrift.server.THsHaServer;import org.apache.thrift.transport.TNonblockingServerSocket;public class ThriftAsyncServer {public static void main(String[] args) throws Exception {TNonblockingServerSocket transport = new TNonblockingServerSocket(1001);TProcessor processor = new HelloService.Processor<HelloServiceHandler>(new HelloServiceHandler());THsHaServer server = new THsHaServer(new THsHaServer.Args(transport).processor(processor));server.serve();}}

客户端代码:

import org.apache.thrift.async.AsyncMethodCallback;import org.apache.thrift.async.TAsyncClientManager;import org.apache.thrift.protocol.TBinaryProtocol;import org.apache.thrift.protocol.TProtocolFactory;import org.apache.thrift.transport.TNonblockingSocket;public class ThriftAsyncClient {public static void main(String[] args) throws Exception {TNonblockingSocket socket = new TNonblockingSocket("127.0.0.1", 1001);TAsyncClientManager clientManager = new TAsyncClientManager();TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();HelloService.AsyncClient client = new HelloService.AsyncClient(protocolFactory , clientManager, socket);client.sayHello("Andy", new AsyncMethodCallback<String>() {@Overridepublic void onError(Exception e) {e.printStackTrace();}@Overridepublic void onComplete(String response) {System.out.println("Response: " + response);}});Thread.sleep(1000);socket.close();}}


阅读全文
0 0
原创粉丝点击