概述
Netty提供了一个读写空闲心跳检测机制的Handler,用于检测读空闲、写空闲、读写空闲。
如果服务端在一定时间内没有执行读请求,就会触发读空闲事件,一定时间内没有执行写请求,就会触发写空闲事件,如果在一定时间内既没有执行读请求,也没有执行写请求,就会触发读写空闲事件。
案例
服务端:
public class NettyHeartBeatServer {
private int port;
public NettyHeartBeatServer(int port){
this.port = port;
}
public void start() throws InterruptedException {
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//添加一个心跳检测机制的Handler,Netty自带的。
//四个参数:
//readerIdleTime 读空闲时间,如果这个时间内没有执行读请求,就会触发读空闲事件
//writerIdleTime 写空闲时间,如果这个时间内没有执行写请求,就会触发写空闲事件。
//allIdleTime 读写空闲时间,如果在这个时间内没有执行读请,也没有执行写请求,就会触发读写空闲事件
//unit 时间单位
//这里设置的是 3秒读空闲、5秒写空闲、8秒读写空闲
pipeline.addLast(new IdleStateHandler(3,5,8, TimeUnit.SECONDS));
//触发空闲事件要由下一个InboundHandler的userEventTriggered方法解决,这里就直接写一个匿名类算了,不新建了。
pipeline.addLast(new ChannelInboundHandlerAdapter(){
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
//强转
IdleStateEvent stateEvent = (IdleStateEvent) evt;
//IdleState是一个枚举类,包含了3中空闲状态
switch (stateEvent.state()){
case READER_IDLE:{
System.out.println("客户端:" + ctx.channel().remoteAddress()+ "触发了读空闲事件");
break;
}
case WRITER_IDLE:{
System.out.println("客户端:" + ctx.channel().remoteAddress()+ "触发了写空闲事件");
}
case ALL_IDLE:{
System.out.println("客户端:" + ctx.channel().remoteAddress()+ "触发了读写空闲事件");
}
}
super.userEventTriggered(ctx, evt);
}
});
}
});
ChannelFuture channelFuture = serverBootstrap.bind(port);
channelFuture.channel().closeFuture().sync();
}
public static void main(String[] args) throws InterruptedException {
NettyHeartBeatServer nettyHeartBeatServer = new NettyHeartBeatServer(8989);
nettyHeartBeatServer.start();
}
}
客户端:
//客户端 ,仅仅做连接,不发任何数据
public class NettyHeartBeatClient {
private int serverPort;
public NettyHeartBeatClient(int serverPort){
this.serverPort = serverPort;
}
public void start() throws InterruptedException {
NioEventLoopGroup worker = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(worker)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
}
});
ChannelFuture connect = bootstrap.connect("127.0.0.1", serverPort);
connect.channel().closeFuture().sync();
}
public static void main(String[] args) throws InterruptedException {
NettyHeartBeatClient nettyHeartBeatClient = new NettyHeartBeatClient(8989);
nettyHeartBeatClient.start();
}
}
执行结果:

可以利用这些来维护空闲连接超时,比如60秒客户端没有数据发来,就把连接断开之类的。
博客介绍了Netty的读写空闲心跳检测机制,该机制有检测读空闲、写空闲、读写空闲的Handler。服务端在一定时间无读、写或读写请求,会分别触发对应空闲事件,可利用此机制维护空闲连接超时,如断开长时间无数据的连接。

4658

被折叠的 条评论
为什么被折叠?



