专栏名称: ImportNew
伯乐在线旗下账号,专注Java技术分享,包括Java基础技术、进阶技能、架构设计和Java技术领域动态等。
目录
相关文章推荐
51好读  ›  专栏  ›  ImportNew

Netty Client 重连实现

ImportNew  · 公众号  · Java  · 2017-06-16 14:25

正文

(点击 上方公众号 ,可快速关注)


来源:鸟窝 ,

colobu.com/2015/08/14/netty-tcp-client-with-reconnect-handling/

如有好文章投稿,请点击 → 这里了解详情


当我们用Netty实现一个TCP client时,我们当然希望当连接断掉的时候Netty能够自动重连。


Netty Client有两种情况下需要重连:


  • Netty Client启动的时候需要重连

  • 在程序运行中连接断掉需要重连。


对于第一种情况,Netty的作者在stackoverflow上给出了解决方案,


https://stackoverflow.com/questions/19739054/whats-the-best-way-to-reconnect-after-connection-closed-in-netty


对于第二种情况,Netty的例子uptime中实现了一种解决方案。


https://github.com/netty/netty/blob/master/example/src/main/java/io/netty/example/uptime/UptimeClientHandler.java


而Thomas在他的文章中提供了这两种方式的实现的例子。


实现ChannelFutureListener 用来启动时监测是否连接成功,不成功的话重试:


public class Client

{

private EventLoopGroup loop = new NioEventLoopGroup();

public static void main( String[] args )

{

new Client().run();

}

public Bootstrap createBootstrap(Bootstrap bootstrap, EventLoopGroup eventLoop) {

if (bootstrap != null) {

final MyInboundHandler handler = new MyInboundHandler(this);

bootstrap.group(eventLoop);

bootstrap.channel(NioSocketChannel.class);

bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

bootstrap.handler(new ChannelInitializer () {

@Override

protected void initChannel(SocketChannel socketChannel) throws Exception {

socketChannel.pipeline().addLast(handler);

}

});

bootstrap.remoteAddress("localhost", 8888);

bootstrap.connect().addListener(new ConnectionListener(this));







请到「今天看啥」查看全文