gpt4 book ai didi

java - netty维护连接以及如何通知失败到channelfuture

转载 作者:行者123 更新时间:2023-12-02 00:10:32 25 4
gpt4 key购买 nike

我尝试在客户端中创建一个 while 循环,试图维持与服务器的多个连接。当 channel 处理程序从服务器收到某些响应(错误)时,它应该关闭 channel 并标记该 channel 将来失败。

Channel channel = this.channelPool.acquire().syncUninterruptibly().getNow();
// release channel when closed to unblock creating new channel.
channel.closeFuture().addListener((ChannelFutureListener) future -> {
// not success wait and retry
if(!future.isSuccess()){
trySleep();
}
// close normally, no error, release so can create another connection immediately
this.channelPool.release(future.channel());
});

这里有两个问题

  1. 使用 while 循环和 FixChannelPool 来维护从客户端到服务器的连接数量是否正确?
  2. 如何让channelFuture失败?调用 setClosed() 时 CloseFuture 类始终设置成功 https://github.com/netty/netty/blob/4.1/transport/src/main/java/io/netty/channel/AbstractChannel.java#L1159

这个例子是保持一个连接的好方法。但它需要单例,这是我想避免的。谢谢!

最佳答案

发现只是使用 ChannelAttribute 来传递信息。

ctx.channel().attr(OneAttribute).set(true);
ctx.close();

然后

channel.closeFuture().addListener((ChannelFutureListener) future -> {
// not success wait and retry
if(future.channel().attr(OneAttribute) == some value){
trySleep();
}
// close normally, no error, release so can create another connection immediately
this.channelPool.release(future.channel());

关于java - netty维护连接以及如何通知失败到channelfuture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58125089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com