如何为多线程制作 Thrift 客户端?

How to make a Thrift client for multiple threads?

我在下面的代码片段中有一个可用的 Thrift 客户端。

TTransport transport = new THttpClient(new Uri("http://localhost:8080/api/"));
TProtocol protocol = new TBinaryProtocol(transport);
TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, "UserService");
UserService.Client userServiceClient = new UserService.Client(mp);
System.out.println(userServiceClient.getUserById(100));

当运行多线程环境中的客户端

threads[i] = new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println(userServiceClient.getUserById(someId));
    }
}

我遇到异常:乱序响应

org.apache.thrift.TApplicationException: getUserById failed: out of sequence response
at org.apache.thrift.TServiceClient.receiveBase(TServiceClient.java:76)

我猜是Thrift生成的Client不是线程安全的。 但是如果我想让多客户端同时调用同一个方法getUserById(),怎么实现呢?

Thrift 客户端不是为跨线程共享而设计的。如果您需要多个客户端线程,请为每个线程设置一个 Thrift 客户端。

But if I want multi-clients to call the same method getUserById() simultaneously, how can I make it?

我们不太了解上下文,所以我不得不猜测一下。如果问题是一次有很多这样的电话打进来,一个可能的解决办法是分组通话以节省往返时间:

service wtf {
  list<string>  getUsersById( 1 : list<int> userIds)
}

这只是一个简短的想法。也许您想 return list<user_data_struct> 代替。出于实际原因,我还建议将 returned 列表包装到一个结构中,这样整个事情就变得可扩展了。