首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java中使用Thrift的异步请求

Java中使用Thrift的异步请求
EN

Stack Overflow用户
提问于 2011-09-19 08:39:20
回答 2查看 13K关注 0票数 10

我正在寻找如何使用Thrift在Java中发出异步请求的示例。看一下生成的代码,这似乎是可能的,但我找不到一个如何实现的示例。

下面是一个生成的代码示例,它表明存在一个异步接口:

代码语言:javascript
运行
复制
...
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);
      }
    }
 ...

关于如何使用它有什么建议吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-10 21:11:54

使用上面的接口像这样进行异步调用(代码提到了Cassandra,但很容易推广到您的应用程序):

代码语言:javascript
运行
复制
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());
票数 10
EN

Stack Overflow用户

发布于 2011-09-19 11:56:33

您还没有给出任何上下文,所以我将给出您需要的基本部分:

  • 要执行异步调用,您将需要在线程中进行
  • 以获得结果,您将需要某种类型的回调

下面是这些元素的一个基本示例:

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7465435

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档