我在下面的代码片段中有一个可用的 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)
}
这只是一个简短的想法。也许你想返回 list<user_data_struct>
反而。出于实际原因,我还建议将返回的列表包装到一个结构中,这样整个事情就变得可扩展了。
关于java - 如何为多线程制作 Thrift 客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37674466/