【问题标题】:netty maintain connections and how to notify fail to channelfuturenetty 维护连接以及如何通知失败到 channelfuture
【发布时间】:2020-01-27 05:19:22
【问题描述】:

我正在尝试在客户端中创建一个 while 循环,以保持与服务器的多个连接。 当通道处理程序从服务器获得某些响应(错误)时,它应该关闭通道并将此通道标记为未来失败。

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 循环和 FixedChannelPool 来维持从客户端到服务器的连接数是否正确?
  2. 如何使 channelFuture 失败?调用 setClosed() 时,CloseFuture 类总是设置成功 https://github.com/netty/netty/blob/4.1/transport/src/main/java/io/netty/channel/AbstractChannel.java#L1159

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

【问题讨论】:

    标签: java netty


    【解决方案1】:

    想出只是使用 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());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      • 2017-07-11
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多