Netty Client重连实现
当我们用Netty实现一个TCP client时,我们当然希望当连接断掉的时候Netty能够自动重连。
Netty Client有两种情况下需要重连:
- Netty Client启动的时候需要重连
- 在程序运行中连接断掉需要重连。
对于第一种情况,Netty的作者在stackoverflow上给出了解决方案,
对于第二种情况,Netty的例子uptime中实现了一种解决方案。
而Thomas在他的文章中提供了这两种方式的实现的例子。
实现ChannelFutureListener 用来启动时监测是否连接成功,不成功的话重试:
在发送请求的地方:
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future)
throws Exception {
if (future.isSuccess()) {
LOG.debug("connect the frontend server success");
} else {
syncSender.setExceptionCause(reqId, future.cause());
LOG.error("Error occurs in the channel, with the error message: "
+ future.cause().getLocalizedMessage());
future.channel().eventLoop().schedule(new Runnable() {
@Override
public void run() {
try {
retryConnect();
} catch (InterruptedException e) {
// TODO: Throw Exception
e.printStackTrace();
}
}
},5, TimeUnit.SECONDS);
}
}
});
参考: http://colobu.com/2015/08/14/netty-tcp-client-with-reconnect-handling/