zoukankan      html  css  js  c++  java
  • Netty ChannelFuture 监听三种方法

    以下是伪代码

    方法一

    前后代码省略
    //绑定服务器,该实例将提供有关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("服务器连接成功");
            }
        }
    }
  • 相关阅读:
    产品蔟的创建--抽象工厂模式
    产品蔟的创建--抽象工厂模式
    ASP.NET MVC5+EF6+EasyUI 后台管理系统--工作流演示截图
    ASP.NET MVC5+EF6+EasyUI 后台管理系统--工作流演示截图
    ASP.NET MVC5+EF6+EasyUI 后台管理系统--工作流演示截图
    ASP.NET MVC5+EF6+EasyUI 后台管理系统--工作流演示截图
    一个网站SQL注入的案例
    一个网站SQL注入的案例
    干什么挣钱快,2个冷门项目让你迅速发家致富
    获取 pool的并发数和Pool下成员的并发数
  • 原文地址:https://www.cnblogs.com/vipsoft/p/14924157.html
Copyright © 2011-2022 走看看