Java 中使用 Thrift 的异步请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7465435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Asynchronous request with Thrift in Java
提问by MasterScrat
I'm looking for an example of how to make an asynchronous request in Java using Thrift. Looking at the generated code this seems to be possible, but I can't find a single example of how.
我正在寻找如何使用 Thrift 在 Java 中发出异步请求的示例。查看生成的代码这似乎是可能的,但我找不到一个关于如何操作的示例。
Here is an example of generated code that suggest the existence of an Asynchronous interface:
下面是一个生成的代码示例,表明存在异步接口:
...
AsyncIface {
public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
private org.apache.thrift.async.TAsyncClientManager clientManager;
private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
this.clientManager = clientManager;
this.protocolFactory = protocolFactory;
}
public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
return new AsyncClient(protocolFactory, clientManager, transport);
}
}
...
Any pointer on how to use it?
关于如何使用它的任何指示?
采纳答案by Ishan
Use the above interface to make the async call like this (The code mentions Cassandra but will easily generalize to your application):
使用上面的接口进行这样的异步调用(代码提到了 Cassandra,但很容易推广到您的应用程序):
TNonblockingTransport transport = new TNonblockingSocket("127.0.0.1", 9160);
TAsyncClientManager clientManager = new TAsyncClientManager();
TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();
Cassandra.AsyncClient client = new Cassandra.AsyncClient(protocolFactory, clientManager, transport);
Cassandra.method_call(parameters, new Callback());
回答by Bohemian
You haven't given any context, so I'll give you the basic parts you'll need:
您没有提供任何上下文,所以我会给您提供您需要的基本部分:
- To perform an asynchronous call, you'll need make it in a thread
- To get the result, you'll need some kind of call back
- 要执行异步调用,您需要在线程中进行
- 为了得到结果,你需要某种回调
The following represents a basic example of these elements in play:
以下是这些元素的基本示例:
final MyClient client; // Who will get a call back to the their sendResult() method when asynch call finished
ExecutorService executor = Executors.newSingleThreadExecutor(); // Handy way to run code in a thread
Runnable task = new Runnable() {
public void run() { // Where the "do the call" code sits
int result = someService.call(someParamter);
client.sendResult(result); // For example, expecting an int result
}
};
executor.submit(task); // This scheduled the runnable to be run