[英]Asynchronous request with Thrift in Java
我正在尋找一個如何使用Thrift在Java中創建異步請求的示例。 看看生成的代碼這似乎是可能的,但我找不到一個如何的例子。
以下是生成代碼的示例,該代碼表明存在異步接口:
...
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);
}
}
...
關於如何使用它的任何指針?
使用上面的界面進行這樣的異步調用(代碼提到了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());
您沒有給出任何背景信息,因此我將為您提供您需要的基本部分:
以下代表了這些元素的基本示例:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.