以下是偽代碼
方法一
前后代碼省略 //綁定服務器,該實例將提供有關IO操作的結果或狀態的信息 ChannelFuture channelFuture = bootstrap.bind(); this.serverChannel = channelFuture.channel(); //給cf 注冊監聽器,監控我們關心的事件 channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { logger.info("在" + future.channel().localAddress() + "上開啟監聽 成功"); Instance nacos = nacosUtil.registerInstance(); } else { logger.info("在" + future.channel().localAddress() + "上開啟監聽 失敗"); } } });
方法二
ChannelFuture f = bootstrap.connect(); f.addListener(connectedListener); private GenericFutureListener<ChannelFuture> connectedListener = (ChannelFuture f) -> { final EventLoop eventLoop = f.channel().eventLoop(); if (!f.isSuccess()) { logger.info("連接失敗!在10s之后准備嘗試重連! doConnect => {}:{}", host, port); eventLoop.schedule(() -> this.doConnect(), 10, TimeUnit.SECONDS); } else { connectFlag = true; channel = f.channel(); channel.closeFuture().addListener(closeListener); logger.info("連接成功: localAddress => {} remoteAddress => {}", f.channel().localAddress(), f.channel().remoteAddress()); } };
方法三
//綁定服務器,該實例將提供有關IO操作的結果或狀態的信息 ChannelFuture channelFuture = bootstrap.connect(nettyHost, nettyPort);//.sync()去掉,不然就走不到下一行 ListennerClientReconnHeart 加不進去 channelFuture.addListener(applicationContext.getBean(NettyClientReconnHeart.class)); @Component public class NettyClientReconnHeart implements ChannelFutureListener { private final Logger logger = LoggerFactory.getLogger(LoggerConfig.NETTY_LOGGER); @Autowired private NettyClient nettyClient; @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (!channelFuture.isSuccess()) { EventLoop loop = channelFuture.channel().eventLoop(); logger.warn("客戶端已啟動,與服務端建立連接失敗,10s之后嘗試重連!"); loop.schedule(() -> nettyClient.doConnect(), 10, TimeUnit.SECONDS); } else { logger.info("服務器連接成功"); } } }