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

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

  hot3.png

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

转载于:https://my.oschina.net/go4it/blog/755318

你可能感兴趣的文章
DataTable
查看>>
POJ 2226 Muddy Fields 二分图(难点在于建图)
查看>>
STM32软件仿真的一个注意点
查看>>
[LeetCode]题解(python):119-Pascal's Triangle II
查看>>
[LeetCode]题解(python):121-Best Time to Buy and Sell Stock
查看>>
Selenium-ActionChainsApi--鼠标连贯操作
查看>>
android基于MBR的bootkit病毒学习笔记
查看>>
Flask学习
查看>>
VC++文件操作大全
查看>>
队列的顺序存储---顺序队列
查看>>
NOIP
查看>>
MicroPython-GPS教程之TPYBoardv702控制5110显示当前经纬度
查看>>
ListView简单使用
查看>>
用HTML/JS/PHP方式实现页面延时跳转
查看>>
【Redis】安装PHP的redis驱动(二)
查看>>
java中string和int互相转化
查看>>
什么是序列化,为什么要序列化
查看>>
Java保留小数点后有效数字
查看>>
CommonHelper
查看>>
excel操作for(lutai)
查看>>