龙空技术网

Netty 心跳检测

一个程序员小哥哥 511

前言:

眼前你们对“netty状态机”大约比较关注,朋友们都想要分析一些“netty状态机”的相关文章。那么小编同时在网摘上收集了一些关于“netty状态机””的相关文章,希望你们能喜欢,你们一起来学习一下吧!

心跳检测

Netty 的心跳检测机制例如

服务器超过 n 秒没有读取数据时发出读空闲服务器超过 n 秒没有写数据发出写空闲使用方式

引入 Netty 提供的 handler io.netty.handler.timeout.IdleStateHandler#IdleStateHandler(long, long, long, java.util.concurrent.TimeUnit)

{@link IdleStateHandler} Netty 提供的处理空闲状态的处理器readerIdleTime 读空闲 {多长时间没有读就会发送一个心跳检测包,检查是否链接}writerIdleTime 写空闲 {多长时间没有写就会发送一个心跳检测包,检查是否链接}allIdleTime 读写空闲 {多长时间既没有读也没有写就会发送一个心跳检测包,检查是否链接}idle handler trigger 以后就会把结果传递给下一个 handler 处理

pipeline.addLast("IdleHandler", new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));pipeline.addLast("UserIdleHandler", new HeartbeatServerHandler());
HeartbeatServerHandler 的实现
/** * 这个处理器会处理 {@link IdleStateHandler} 这个心跳检测传递来的数据 * * @author L */public class HeartbeatServerHandler extends ChannelInboundHandlerAdapter {    Logger log = LoggerUtils.getLogger(HeartbeatServerHandler.class);    /**     * 事件触发     *     * @param ctx 上下文信息     * @param evt 触发的事件     */    @Override    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {        if (evt instanceof IdleStateEvent) {            // 向下转型            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;            switch (idleStateEvent.state()) {                case ALL_IDLE:                    log.info("读写空闲");                    break;                case READER_IDLE:                    log.info("读空闲");                    break;                case WRITER_IDLE:                    log.info("写空闲");                    break;            }        }    }}

这就是一个简单的 Netty 心跳检测小 demo 实列

完整代码服务端

package com.netty.heartbeat;import com.utils.LoggerUtils;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;import io.netty.handler.logging.LogLevel;import io.netty.handler.logging.LoggingHandler;import io.netty.handler.timeout.IdleStateHandler;import org.slf4j.Logger;import java.util.concurrent.TimeUnit;/** * @author L */public class HeartbeatServer {    Logger log = LoggerUtils.getLogger(HeartbeatServer.class);    public void init() throws InterruptedException {        EventLoopGroup boosGroup = new NioEventLoopGroup();        EventLoopGroup workGroup = new NioEventLoopGroup();        try {            ServerBootstrap bootstrap = new ServerBootstrap();            bootstrap.channel(NioServerSocketChannel.class)                    .group(boosGroup, workGroup)                    // 添加一个处理器 (日志处理器)                    .handler(new LoggingHandler(LogLevel.INFO))                    // work 工作的处理器                    .childHandler(new ChannelInitializer<SocketChannel>() {                        @Override                        protected void initChannel(SocketChannel ch) {                            ChannelPipeline pipeline = ch.pipeline();                            // {@link IdleStateHandler} netty 提供的处理空闲状态的处理器                            // readerIdleTime 读空闲 {多长时间没有读就会发送一个心跳检测包,检查是否链接}                            // writerIdleTime 写空闲 {多长时间没有写就会发送一个心跳检测包,检查是否链接}                            // allIdleTime 读写空闲 {多长时间既没有读也没有写就会发送一个心跳检测包,检查是否链接}                            // idle handler trigger 以后就会把结果传递给下一个 handler 处理                            pipeline.addLast("", new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));                            pipeline.addLast("UserIdleHandler", new HeartbeatServerHandler());                        }                    });            ChannelFuture channelFuture = bootstrap.bind(6666).sync();            // 添加监听器            channelFuture.addListener(future -> {                if (future.isDone()) log.info("服务器绑定端口成功");            });            channelFuture.channel().closeFuture().sync();        } finally {            boosGroup.shutdownGracefully();            workGroup.shutdownGracefully();        }    }}

标签: #netty状态机