Thrift 非阻塞异步I/O例子

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值