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();
}
}