netty的reconnect方式之一
博客专区 > go4it 的博客 > 博客详情
netty的reconnect方式之一
go4it 发表于1年前
netty的reconnect方式之一
  • 发表于 1年前
  • 阅读 19
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 十分钟定制你的第一个小程序>>>   

##使用timer

bootstrap.setPipelineFactory(
        new ChannelPipelineFactory() {
          public ChannelPipeline getPipeline() {
            final ChannelPipeline p = Channels.pipeline();

            // Reconnections
            p.addLast("reconnect", new ReconnectHandler(
                bootstrap,
                timer,
                reconnectDelay,
                TimeUnit.MILLISECONDS));

###timer

timer = HashedWheelTimerFactory.CreateDaemonHashedWheelTimer();

###HashedWheelTimerFactory

public class HashedWheelTimerFactory {

    public static ThreadFactory daemonThreadFactory = new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread retVal = Executors.defaultThreadFactory().newThread(r);
            retVal.setDaemon(true);

            return retVal;
        }
    };

    /**
     * Creates hashed wheel timer that uses daemon threads
     *
     * @return HashedWheelTimer
     */
    public static HashedWheelTimer CreateDaemonHashedWheelTimer() {
        return new HashedWheelTimer(daemonThreadFactory);
    }

}

###ReconnectHandler

public class ReconnectHandler extends SimpleChannelUpstreamHandler {
  final Bootstrap bootstrap;
  public final Timer timer;
  public long startTime = -1;
  public final AtomicLong delay;
  public final TimeUnit unit;

  public ReconnectHandler(ClientBootstrap bootstrap, Timer timer, AtomicLong delay, TimeUnit unit) {
    this.bootstrap = bootstrap;
    this.timer = timer;
    this.delay = delay;
    this.unit = unit;
  }
  
  public ReconnectHandler(ConnectionlessBootstrap bootstrap, Timer timer, AtomicLong delay, TimeUnit unit) {
    this.bootstrap = bootstrap;
    this.timer = timer;
    this.delay = delay;
    this.unit = unit;
  }

  InetSocketAddress getRemoteAddress() {
    Resolver resolver = (Resolver) bootstrap.getOption("resolver");
    return resolver.resolve();
  }

  @Override
  public void channelDisconnected(ChannelHandlerContext c, ChannelStateEvent e) throws Exception {
    // Go ahead and close. I don't know why Netty doesn't close disconnected
    // TCP sockets, but it seems not to.
    e.getChannel().close();
    super.channelDisconnected(c, e);
  }

  @Override
  public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    try {
      timer.newTimeout(new TimerTask() {
        public void run(Timeout timeout) throws Exception {
          if (bootstrap instanceof ClientBootstrap) {
            ClientBootstrap b = (ClientBootstrap) bootstrap;
            b.setOption("remoteAddress", getRemoteAddress());
            b.connect();
          } else if (bootstrap instanceof ConnectionlessBootstrap) {
            ConnectionlessBootstrap b = (ConnectionlessBootstrap) bootstrap;
            b.setOption("remoteAddress", getRemoteAddress());
            b.connect();
          }
        }
      }, delay.get(), unit);
    } catch (java.lang.IllegalStateException ex) {
      // The timer must have been stopped.
    }
    super.channelClosed(ctx, e);
  }

  @Override
  public void channelConnected(ChannelHandlerContext c, ChannelStateEvent e) throws Exception {
    if (startTime < 0) {
      startTime = System.currentTimeMillis();
    }
    super.channelConnected(c, e);
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext c, ExceptionEvent e) {
    final Throwable cause = e.getCause();

    if (cause instanceof ConnectException) {
      startTime = -1;
    } else if (cause instanceof ReadTimeoutException) {
      // The connection was OK but there was no traffic for the last period.
    } else {
     c.sendUpstream(e);
    }
    c.getChannel().close();
  }
}

##docs

标签: Netty
共有 人打赏支持
粉丝 13
博文 393
码字总数 186214
×
go4it
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: