java thrift异步调用_[转]thrift java多线程非阻塞同步/异步调用实例

server端代码:

public class Server {

public final static int PORT = 8989;

@SuppressWarnings({ "rawtypes", "unchecked" })

private void start() {

try {

TNonblockingServerSocket socket = new TNonblockingServerSocket(PORT);

final Hello.Processor processor = new Hello.Processor(new HelloImpl());

THsHaServer.Args arg = new THsHaServer.Args(socket);

// 高效率的、密集的二进制编码格式进行数据传输

// 使用非阻塞方式,按块的大小进行传输,类似于 Java 中的 NIO

arg.protocolFactory(new TCompactProtocol.Factory());

arg.transportFactory(new TFramedTransport.Factory());

arg.processorFactory(new TProcessorFactory(processor));

TServer server = new THsHaServer(arg);

server.serve();

System.out.println("#服务启动-使用:非阻塞&高效二进制编码");

} catch (TTransportException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}

}

public static void main(String args[]) {

Server srv = new Server();

srv.start();

}

}

client端代码:

public class Client {

public static final String address = "127.0.0.1";

public static final int port = 8989;

public static final int clientTimeout = 30000;

public static void main_syn() {

TTransport transport = new TFramedTransport(new TSocket(address, port, clientTimeout));

TProtocol protocol = new TCompactProtocol(transport);

Hello.Client client = new Hello.Client(protocol);

try {

transport.open();

System.out.println(client.helloString("larry"));

} catch (TApplicationException e) {

System.out.println(e.getMessage() + " " + e.getType());

} catch (TTransportException e) {

e.printStackTrace();

} catch (TException e) {

e.printStackTrace();

}

transport.close();

}

public static void main_asy() throws Exception {

try {

TAsyncClientManager clientManager = new TAsyncClientManager();

TNonblockingTransport transport = new TNonblockingSocket(address, port, clientTimeout);

TProtocolFactory protocol = new TCompactProtocol.Factory();

Hello.AsyncClient asyncClient = new Hello.AsyncClient(protocol, clientManager, transport);

System.out.println("Client calls .....");

MyCallback callBack = new MyCallback();

asyncClient.helloString("larry", callBack);

while (true) {

Thread.sleep(1);

}

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) throws Exception {

main_asy();

}

}

public class MyCallback implements AsyncMethodCallback {

// 返回结果

@Override

public void onComplete(helloString_call response) {

System.out.println("onComplete");

try {

System.out.println(response.getResult().toString());

} catch (TException e) {

e.printStackTrace();

}

}

// 返回异常

@Override

public void onError(Exception exception) {

System.out.println("onError");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值