Netty简单的重连机制

时间:2023-03-09 21:30:52
Netty简单的重连机制

其实重连机制并不是多么多高深的技术,其实就是一个在客户端做一个简单的判断,如果连接断了,那么就重新调用连接服务端的代码

当然,我们重连的动作肯定是发生在断连之后发生的,我们可以在上篇的心跳机制的基础上,简单地修改一下客户端的启动代码就可以了:

我们在连接断了之后,我们一般会在finally的方法中去释放资源,这边我们应该不去释放资源,我们在finally里面进行重连:

Netty简单的重连机制

整个客户端的代码如下:

  1. package com.lyncc.netty.heartbeats;
  2. import java.util.concurrent.TimeUnit;
  3. import io.netty.bootstrap.Bootstrap;
  4. import io.netty.channel.ChannelFuture;
  5. import io.netty.channel.ChannelInitializer;
  6. import io.netty.channel.ChannelOption;
  7. import io.netty.channel.ChannelPipeline;
  8. import io.netty.channel.EventLoopGroup;
  9. import io.netty.channel.nio.NioEventLoopGroup;
  10. import io.netty.channel.socket.SocketChannel;
  11. import io.netty.channel.socket.nio.NioSocketChannel;
  12. import io.netty.handler.codec.string.StringDecoder;
  13. import io.netty.handler.codec.string.StringEncoder;
  14. import io.netty.handler.logging.LogLevel;
  15. import io.netty.handler.logging.LoggingHandler;
  16. import io.netty.handler.timeout.IdleStateHandler;
  17. public class HeartBeatsClient {
  18. public void connect(int port, String host) throws Exception {
  19. // Configure the client.
  20. EventLoopGroup group = new NioEventLoopGroup();
  21. ChannelFuture future = null;
  22. try {
  23. Bootstrap b = new Bootstrap();
  24. b.group(group)
  25. .channel(NioSocketChannel.class)
  26. .option(ChannelOption.TCP_NODELAY, true)
  27. .handler(new LoggingHandler(LogLevel.INFO))
  28. .handler(new ChannelInitializer<SocketChannel>() {
  29. @Override
  30. public void initChannel(SocketChannel ch) throws Exception {
  31. ChannelPipeline p = ch.pipeline();
  32. p.addLast("ping", new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS));
  33. p.addLast("decoder", new StringDecoder());
  34. p.addLast("encoder", new StringEncoder());
  35. p.addLast(new HeartBeatClientHandler());
  36. }
  37. });
  38. future = b.connect(host, port).sync();
  39. future.channel().closeFuture().sync();
  40. } finally {
  41. //          group.shutdownGracefully();
  42. if (null != future) {
  43. if (future.channel() != null && future.channel().isOpen()) {
  44. future.channel().close();
  45. }
  46. }
  47. System.out.println("准备重连");
  48. connect(port, host);
  49. System.out.println("重连成功");
  50. }
  51. }
  52. /**
  53. * @param args
  54. * @throws Exception
  55. */
  56. public static void main(String[] args) throws Exception {
  57. int port = 8080;
  58. if (args != null && args.length > 0) {
  59. try {
  60. port = Integer.valueOf(args[0]);
  61. } catch (NumberFormatException e) {
  62. // 采用默认值
  63. }
  64. }
  65. new HeartBeatsClient().connect(port, "127.0.0.1");
  66. }
  67. }

我们再看看服务器端和客户端启动之后的控制台打印信息:

服务器控制台:

Netty简单的重连机制

客户端:

Netty简单的重连机制

好了,这样就可以重连~这只是一个简单的Demo,真实的生产场景用法可能并不是这样