Thrift 非阻塞非同步I/O例子
阿新 • • 發佈:2019-01-01
Thrift支援多路複用I/O通訊模型。需要客戶端和服務端同時採用非同步I/O模型。
HelloService.thrift
namespace java thrift
service 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>() { @Override public void onError(Exception e) { e.printStackTrace(); } @Override public void onComplete(String response) { System.out.println("Response: " + response); } }); Thread.sleep(1000); socket.close(); } }