文档章节

netty的reconnect方式之一

go4it
 go4it
发布于 2016/10/08 17:04
字数 298
阅读 26
收藏 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

© 著作权归作者所有

共有 人打赏支持
go4it
粉丝 64
博文 740
码字总数 533483
作品 0
深圳
storm 一个报错 Async loop died! & reconnect

Async loop died! 重启任务后发现任务一直异常,日志中有大量reconnect。 b.s.m.n.Client [INFO] Reconnect started for Netty-Client-192.168.1.2/192.168.1.21:6724... [26] telnet到对应级......

wennan
2014/11/07
0
0
Netty5.0 用在android 上

12-14 17:28:38.906 23413-24753/com.dami.tkhxs I/NettyClient: connect failed Unable to create Channel from class class io.netty.channel.socket.nio.NioSocketChannel reconnect dela......

uglyApple
2016/12/14
186
1
Lettuce 5.1.0.M1 发布,带来 5 大功能特性变更

Lettuce 5.1.0.M1 发布,这是 Lettuce 5.1 发布的第一个预览版本,包含改进和错误修复。Lettuce 5.1.0.M1 需要 Java 8,Java 9 或 Java 10 环境。 此次比较显著的变化有: Redis Streams 的 ...

淡漠悠然
05/15
0
0
聊聊lettuce的shareNativeConnection参数

序 本文主要研究一下lettuce的shareNativeConnection参数 LettuceConnectionFactory spring-data-redis-2.0.10.RELEASE-sources.jar!/org/springframework/data/redis/connection/lettuce/L......

go4it
09/16
0
0
netty客户端重连的问题

public class ReconnectTimer extends TimerTask { @Override public void run() { System.out.println("正在尝试与服务器连接......"); try { new TelnetClient("192.168.0.107", 9090).run......

天王盖地虎626
2014/07/04
5.4K
3

没有更多内容

加载失败,请刷新页面

加载更多

#mysql50# not Exist

data 目录有中文名称,可能是复制的"复件...."

少年不搬砖老大徒伤悲
18分钟前
1
0
在yii2中,让你action参数支持POST数据的小方法

我们先来看一段代码 class RaController extends Controller { public $enableCsrfValidation = false; public function actionSay($username = '',$city = ''){ echo "{$......

阿北2017
27分钟前
2
0
macOS 10.14 Mojave

在近日发布的 macOS 10.14 Mojave 操作系统中,有人发现它(在某些机型中)悄然禁用了先前的「次像素平滑渲染」选项,导致部分(尤其是使用非高分辨率显示器)用户觉得字体比先前的更细更难看...

火力全開
31分钟前
1
0
 实现分布式锁的正确姿势

实现分布式锁的正确姿势 原理分析 最近看到好多博主都在推分布式锁,实现方式很多,基于db、redis、zookeeper。zookeeper方式实现起来比较繁琐,这里我们就谈谈基于redis实现分布式锁的正确实...

DemonsI
36分钟前
1
0
微信小程序 、支付宝小程序、百度小程序和钉钉e应用的汇总

2018年9月25日 百度小程序开放企业申请 微信小程序:现在微信小游戏都热火朝天了,而且已经有了云开发,包括提供的能力、文档、社区等都相对完善,也有相关的变现方式; 支付宝小程序:https...

to_be_better
38分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部