Netty心跳检测机制

netty中提供了 tcp-keepalive 的设置:

ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)//这个地方

设置:ChannelOption.SO_KEEPALIVE, true 表示打开 TCP 的 keepAlive 设置。

一个 Netty 服务端可能会面临上万个连接,如何去维护这些连接是应用应该去处理的事情。在 Netty 中提供了 IdleStateHandler 类专门用于处理心跳。

IdleStateHandler 的构造函数如下:

public IdleStateHandler(long readerIdleTime,
 long writerIdleTime, long allIdleTime,TimeUnit unit){
}

long readerIdleTime, long writerIdleTime, long allIdleTime

  • readerIdleTime 表示多长时间没有读,就会发送心跳检测包,检测是否还是连接状态

  • writerIdleTime 表示多长时间没有写,就会发送心跳检测包,检测是否还是连接状态

  • allIdleTime 表示多长时间没有读写,就会发送心跳检测包,检测是否还是连接状态

  • unit 代表时间单位

示例代码:

Server

package org.joisen.netty.heartbeat;

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 java.util.concurrent.TimeUnit;


public class MyServer {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO)) //在bossGroup增加一个日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //加入一个netty提供的IdleStateHandler
                            
                            pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
                            //加入一个对空闲检测进一步处理的handler(自定义)
                            pipeline.addLast(new MyServerHandler());

                        }
                    });
            //启动服务器
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
            channelFuture.channel().closeFuture().sync();

        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }



}

Handler

package org.joisen.netty.heartbeat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;


public class MyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * @param ctx 上下文
     * @param evt 事件
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if(evt instanceof IdleStateEvent){
            //将 evt 向下转型 IdleStateEvent
            IdleStateEvent event = (IdleStateEvent) evt;
            String eventType = null;
            switch (event.state()){
                case READER_IDLE:
                    eventType = "读空闲";
                    break;
                case WRITER_IDLE:
                    eventType = "写空闲";
                    break;
                case ALL_IDLE:
                    eventType = "读写空闲";
                    break;
            }
            System.out.println(ctx.channel().remoteAddress() + "--超时时间--"+eventType);
            System.out.println("服务器做相应处理");
        }

    }
}

Client 用的是之前写的,反正端口一样,可以用于测试

package org.joisen.netty.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;


public class GroupChatClient {

    private final String host;
    private final int port;

    public  GroupChatClient(String host,int port){
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception{
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //得到pipeline
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("decoder",new StringDecoder());
                            pipeline.addLast("encoder",new StringEncoder());
                          
                        }
                    });

            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            //提示
            Channel channel = channelFuture.channel();
            System.out.println("------------"+channel.localAddress()+"----------");
            //客户端需要输入信息,创建一个扫描器
            Scanner scanner = new Scanner(System.in);
            while(scanner.hasNextLine()){
                String msg = scanner.nextLine();
                //通过channel发送到服务器
                channel.writeAndFlush(msg+"\r\n");
            }
        }finally {
            eventExecutors.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        new GroupChatClient("127.0.0.1",7000).run();

    }



}

运行MyServer.class;
运行Client.class

运行结果:

二月 03, 2021 8:41:47 下午 io.netty.handler.logging.LoggingHandler channelRegistered
信息: [id: 0xcd351bad] REGISTERED
二月 03, 2021 8:41:47 下午 io.netty.handler.logging.LoggingHandler bind
信息: [id: 0xcd351bad] BIND: 0.0.0.0/0.0.0.0:7000
二月 03, 2021 8:41:47 下午 io.netty.handler.logging.LoggingHandler channelActive
信息: [id: 0xcd351bad, L:/0:0:0:0:0:0:0:0:7000] ACTIVE
二月 03, 2021 8:41:50 下午 io.netty.handler.logging.LoggingHandler channelRead
信息: [id: 0xcd351bad, L:/0:0:0:0:0:0:0:0:7000] READ: [id: 0xa83f59af, L:/127.0.0.1:7000 - R:/127.0.0.1:57305]
二月 03, 2021 8:41:50 下午 io.netty.handler.logging.LoggingHandler channelReadComplete
信息: [id: 0xcd351bad, L:/0:0:0:0:0:0:0:0:7000] READ COMPLETE
二月 03, 2021 8:42:21 下午 io.netty.handler.logging.LoggingHandler channelRead
信息: [id: 0xcd351bad, L:/0:0:0:0:0:0:0:0:7000] READ: [id: 0x3ded73b3, L:/127.0.0.1:7000 - R:/127.0.0.1:57348]
二月 03, 2021 8:42:21 下午 io.netty.handler.logging.LoggingHandler channelReadComplete
信息: [id: 0xcd351bad, L:/0:0:0:0:0:0:0:0:7000] READ COMPLETE
二月 03, 2021 8:42:52 下午 io.netty.handler.logging.LoggingHandler channelRead
信息: [id: 0xcd351bad, L:/0:0:0:0:0:0:0:0:7000] READ: [id: 0x6f9f5a19, L:/127.0.0.1:7000 - R:/127.0.0.1:57391]
二月 03, 2021 8:42:52 下午 io.netty.handler.logging.LoggingHandler channelReadComplete
信息: [id: 0xcd351bad, L:/0:0:0:0:0:0:0:0:7000] READ COMPLETE
/127.0.0.1:57391--超时时间--读空闲
服务器做相应处理
/127.0.0.1:57391--超时时间--写空闲
服务器做相应处理
/127.0.0.1:57391--超时时间--读空闲
服务器做相应处理
/127.0.0.1:57391--超时时间--读写空闲
服务器做相应处理
/127.0.0.1:57391--超时时间--读空闲
服务器做相应处理
/127.0.0.1:57391--超时时间--写空闲
服务器做相应处理
/127.0.0.1:57391--超时时间--读空闲
服务器做相应处理
/127.0.0.1:57391--超时时间--读写空闲
服务器做相应处理
/127.0.0.1:57391--超时时间--写空闲
服务器做相应处理

以上简单了演示了一下,netty的心跳机制,其实主要就是使用了IdleStateHandler。创作不易 给个三连吧~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值