Roc*_*lee 5 java multithreading thrift
我在下面的代码段中有一个可用的 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));
Run Code Online (Sandbox Code Playgroud)
在多线程环境中运行客户端时
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(userServiceClient.getUserById(someId));
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个例外:乱序响应
org.apache.thrift.TApplicationException: getUserById failed: out of sequence response
at org.apache.thrift.TServiceClient.receiveBase(TServiceClient.java:76)
Run Code Online (Sandbox Code Playgroud)
我猜原因是 Thrift 生成的 Client 不是线程安全的。但是如果我想让多个客户端同时调用同一个方法getUserById(),我该怎么做呢?
Thrift 客户端并非设计为跨线程共享。如果您需要多个客户端线程,请为每个线程设置一个 Thrift 客户端。
但是如果我想让多个客户端同时调用同一个方法 getUserById() ,我该怎么做呢?
我们对上下文了解不多,所以我必须猜测一下。如果问题是一次有很多此类呼叫进入,可能的解决方案是将呼叫分组以节省往返时间:
service wtf {
list<string> getUsersById( 1 : list<int> userIds)
}
Run Code Online (Sandbox Code Playgroud)
这只是一个简短的想法。也许你想返回list<user_data_struct>。出于实际原因,我还建议将返回的列表包装到一个结构中,以便整个事情变得可扩展。