【问题标题】:Asynchronous request with Thrift in JavaJava中使用Thrift的异步请求
【发布时间】:2011-11-19 21:28:46
【问题描述】:

我正在寻找如何使用 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);
      }
    }
 ...

关于如何使用它的任何指针?

【问题讨论】:

    标签: java asynchronous thrift


    【解决方案1】:

    使用上面的接口进行这样的异步调用(代码中提到了 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());
    

    【讨论】:

      【解决方案2】:

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

      • 要执行异步调用,您需要在线程中进行调用
      • 要获得结果,您需要某种回调方式

      以下是这些元素的基本示例:

      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
      

      【讨论】:

      • 这是一种方法,但似乎 Thrift 生成的代码专门用于实现异步客户端。我已经编辑了我的问题以使其更清晰。
      • @Bohemian,我知道您正在尝试提供帮助,但这些“工作示例”适用于同步客户端,而不是异步客户端。而链接的 Wiki 文章就更没用了。
      • 是的,这也违背了我们的目的。我们在模拟中发现,如果我们模拟异步版本,我们在文件上传的 100k 行上的请求时间从 30 秒变为 3 秒,这样我们就不会在系统中阻塞线程。
      猜你喜欢
      • 1970-01-01
      • 2019-07-21
      • 2018-04-24
      • 2019-01-05
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      相关资源
      最近更新 更多