from:http://itindex.net/detail/54161-netty-client
當我們用Netty實現一個TCP client時,我們當然希望當連接斷掉的時候Netty能夠自動重連。
Netty Client有兩種情況下需要重連:
- Netty Client啟動的時候需要重連
- 在程序運行中連接斷掉需要重連。
對於第一種情況,Netty的作者在stackoverflow上給出了 解決方案,
對於第二種情況,Netty的例子uptime中實現了一種 解決方案。
而Thomas在他的 文章中提供了這兩種方式的實現的例子。
實現ChannelFutureListener 用來啟動時監測是否連接成功,不成功的話重試:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(handler);
}
});
bootstrap.remoteAddress("localhost", 8888);
bootstrap.connect().addListener(new ConnectionListener(this));
}
return bootstrap;
}
public void run() {
createBootstrap(new Bootstrap(), loop);
}
}
|
ConnectionListener 負責重連:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class ConnectionListener implements ChannelFutureListener {
private Client client;
public ConnectionListener(Client client) {
this.client = client;
}
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
if (!channelFuture.isSuccess()) {
System.out.println("Reconnect");
final EventLoop loop = channelFuture.channel().eventLoop();
loop.schedule(new Runnable() {
@Override
public void run() {
client.createBootstrap(new Bootstrap(), loop);
}
}, 1L, TimeUnit.SECONDS);
}
}
}
|
同樣在ChannelHandler監測連接是否斷掉,斷掉的話也要重連:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class MyInboundHandler extends SimpleChannelInboundHandler {
private Client client;
public MyInboundHandler(Client client) {
this.client = client;
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
final EventLoop eventLoop = ctx.channel().eventLoop();
eventLoop.schedule(new Runnable() {
@Override
public void run() {
client.createBootstrap(new Bootstrap(), eventLoop);
}
}, 1L, TimeUnit.SECONDS);
super.channelInactive(ctx);
}
}
|
參考文檔
- http://stackoverflow.com/questions/19739054/whats-the-best-way-to-reconnect-after-connection-closed-in-netty
- https://github.com/netty/netty/blob/master/example/src/main/java/io/netty/example/uptime/UptimeClientHandler.java
- http://tterm.blogspot.jp/2014/03/netty-tcp-client-with-reconnect-handling.html
- ctx.close vs ctx.channel().close
- ctx.write vs ctx.channel().write