Netty 客户端请求在发送到多个服务器时超时



首先,我将解释背景:
我已经实现了Netty框架,并且有一个客户端向超过44个服务器发送HTTP请求。服务器正在响应该请求。
在我的客户端中,我通过覆盖channelActive函数并从函数读取响应并将所有响应存储在数据结构中来发送请求channelRead0
因为,发送 HTTP 请求并从 44 台服务器获取响应需要时间。我正在使用超时值,结构如下所示:

for (final InetAddress target : remoteIPAddresses.values()) {
httpClient.connect(target);
}
// wait for the timeout. Hoping client send request to all
// the targets and get response.
Uninterruptibles.sleepUninterruptibly(timeout, TimeUnit.MILLISECONDS);
httpClient.stop();
fetchResults();

获取结果从channelRead0中提到的数据结构中获取结果 连接方法包含如下所示的netty实现:

public void connect(final InetAddress remoteAddress){
new Bootstrap()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout)
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(httpNettyClientChannelInitializer)
.connect(remoteAddress, serverPort)
.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
future.cancel(!future.isSuccess());
}
});
}  

Netty 中使用的参数

connectionTimeout = 100ms  
Timeout value = 400ms    
Eventloop = 1 (Tried with 2 , 5 and 10) 

问题
44 个目标中,我得到了多个目标的超时。目标每次都不同。使用线程睡眠不是一个好的做法,我无法找到任何其他方法来完成任务。 有没有更好的方法可以做到这一点?我已经看过这个视频了。我被封锁了。任何线索都会非常有帮助。

与其睡觉并希望您有所有必需的响应,不如使用 CountDownLatch。将此闩锁传递给您的处理程序,每次响应到达时,处理程序都会对其进行计数(以channelRead0为单位)。然后,您的主线程可以等待所有具有全局超时的响应,并显示await()

您的处理程序可能如下所示:

@ChannelHandler.Sharable
public class HttpResponseHandler extends SimpleChannelInboundHandler<HttpObject> {
final CountDownLatch responseLatch;
public HttpResponseHandler(CountDownLatch responseLatch) {
this.responseLatch = responseLatch;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
....
responseLatch.countDown();
}
}

在主线程中:

CountDownLatch responseLatch = new CountDownLatch(remoteIpAddresses.size());
HttpResponseHandler handler = new HttpResponseHandler(responseLatch);
// your for loop to connect to servers here
responseLatch.await(timeout, TimeUnit.MILLISECONDS);

我没有考虑处理程序中的错误条件(套接字连接/读取超时、无效响应等),因此请确保处理这些条件。

最新更新