博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
netty的reconnect方式之一
阅读量:7080 次
发布时间:2019-06-28

本文共 3551 字,大约阅读时间需要 11 分钟。

使用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

转载地址:http://wpvml.baihongyu.com/

你可能感兴趣的文章
HDU 1023 Train Problem II( 大数卡特兰 )
查看>>
图片的画图板
查看>>
hdu5521 Meeting
查看>>
android学习笔记之handler(2)
查看>>
【LeetCode每天一题】Group Anagrams(变位词组)
查看>>
python学习笔记(五)文件操作和集合
查看>>
排错之网络映射缓存凭证记录导致备份计划任务失败
查看>>
转 jQuery插件Highcharts、flexigrid实践
查看>>
Windows Phone 8 SDK RC 版推出
查看>>
Database2Sharp代码生成工具使用心得
查看>>
稀疏矩阵的十字链表存储
查看>>
【算法导论第13章】红黑树
查看>>
对PostgreSQL中bufmgr.c 中 bufs_to_lap的初步理解
查看>>
Windows 内存分析之路 --How to use Resource Monitor
查看>>
文件上传
查看>>
理解maven的核心概念
查看>>
一个简单的名片管理程序(C#)
查看>>
max tablename length limit in MySQL is 64
查看>>
Ubuntu 12.04 中国科学技术大学源
查看>>
(转)c#实现WinRAR解压缩
查看>>