Netty超时机制学习
-
技术点描述
- ReadTimeoutHandler读取数据超时处理
- WriteTimeoutHandler写数据超时处理
-
IdleStateHandler状态空闲处理
通过以上三种方式,可以轻松实现SOCKET长连接的心跳包机制。
另要注意的是这里所说的超时是指逻辑上的超时,而非TCP连接超时。
-
实现方案
ReadTimeoutHandler,WriteTimeoutHandler, IdleStateHandler这三种方式都是通过在数据处理管道ChannelPipelineFactory的实现类里配置相关代码来实现。
一般使用根据需求使用一种方式即可。
它主要使用Timer定时器用自定义的时间,去定时检测相应的状态,检测到后会根据选择的处理方式,是报错或回调指定的接口实现类处理。
-
参考源码包
-
主要包
-
IdleStateHandler 空闲状态的处理代码
源码:
/**
* Creates a new instance.
*
* @param timer
* the Timer that is used to trigger the scheduled event.
* The recommended Timer implementation is HashedWheelTimer.
* @param readerIdleTimeSeconds
* an IdleStateEvent whose state is IdleState.READER_IDLE
* will be triggered when no read was performed for the specified
* period of time. Specify 0 to disable.
* @param writerIdleTimeSeconds
* an IdleStateEvent whose state is IdleState.WRITER_IDLE
* will be triggered when no write was performed for the specified
* period of time. Specify {@code 0} to disable.
* @param allIdleTimeSeconds
* an IdleStateEvent whose state is IdleState.ALL_IDLE
* will be triggered when neither read nor write was performed
* for the specified period of time. Specify 0 to disable.
*/
public IdleStateHandler(
Timer timer,
int readerIdleTimeSeconds,
int writerIdleTimeSeconds,
int allIdleTimeSeconds) {
this(timer, readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds, TimeUnit.SECONDS);
}
-
ReadTimeoutHandler 读取数据超时的处理代码
源码:
/**
* Creates a new instance.
*
* @param timer
* the Timer that is used to trigger the scheduled event.
* The recommended Timer implementation is HashedWheelTimer.
* @param timeoutSeconds
* read timeout in seconds
*/
public ReadTimeoutHandler(Timer timer, int timeoutSeconds) {
this(timer, timeoutSeconds, TimeUnit.SECONDS);
}
-
WriteTimeoutHandler 写数据超时的处理代码
源码:
/**
* Creates a new instance.
*
* @param timer
* the Timer that is used to trigger the scheduled event.
* The recommended Timer implementation is HashedWheelTimer.
* @param timeoutSeconds
* write timeout in seconds
*/
public WriteTimeoutHandler(Timer timer, int timeoutSeconds) {
this(timer, timeoutSeconds, TimeUnit.SECONDS);
}
-
辅助包
-
IdleStateEvent 空闲事件的接口类
源码:
/**
* A ChannelEvent that is triggered when a Channel has been idle
* for a while.
* @apiviz.landmark
* @apiviz.has org.jboss.netty.handler.timeout.IdleState oneway - -
*/
public interface IdleStateEvent extends ChannelEvent {
/**
* Returns the detailed idle state.
*/
IdleState getState();
/**
* Returns the last time when I/O occurred in milliseconds.
*/
long getLastActivityTimeMillis();
}
- DefaultIdleStateEvent空闲事件的实现类
-
IdleStateAwareChannelHandler 处理空闲事件的接口.
源码:
/**
* An extended SimpleChannelHandler that adds the handler method for
* an IdleStateEvent.
* @apiviz.uses org.jboss.netty.handler.timeout.IdleStateEvent
*/
public class IdleStateAwareChannelHandler extends SimpleChannelHandler {
/**
* Creates a new instance.
*/
public IdleStateAwareChannelHandler() {
super();
}
@Override
public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
if (e instanceof IdleStateEvent) {
channelIdle(ctx, (IdleStateEvent) e);
} else {
super.handleUpstream(ctx, e);
}
}
/**
* Invoked when a Channel has been idle for a while.
*/
public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
ctx.sendUpstream(e);
}
}
- IdleStateAwareChannelUpstreamHandler处理空闲事件的接口.
-
IdleState 定义了三种空闲状态的枚举类
源码:
/**
* An Enum that represents the idle state of a Channel.
*/
public enum IdleState {
/**
* No data was received for a while.
*/
READER_IDLE,
/**
* No data was sent for a while.
*/
WRITER_IDLE,
/**
* No data was either received or sent for a while.
*/
ALL_IDLE;
}
- ReadTimeoutException 读取超时异常类
- WriteTimeoutException 写数据超时异常类
- TimeoutException 读取数据和写数据异常类的父类
-
Demo实现
以下是关于三种方式的关键代码实现讲解。
-
IdleStateHandler
//第一步,在服务启动类中设置数据处理管道.
...
bootstrap.setPipelineFactory(new TCPServerPipelineFactory());
...
//第二步,在数据处理管道实现类里配置空闲状态处理代码.
public class TCPServerPipelineFactory implements ChannelPipelineFactory {
@Override
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = Channels.pipeline();
//设置空闲状态处理操作
pipeline.addLast("idlehandler", new IdleStateHandler(new HashedWheelTimer(), 10, 5 , 0));
pipeline.addLast("hearbeat", new Heartbeat());
pipeline.addLast("handler", new TCPServerHandler());
return pipeline;
}
//第三步,实现方式1:自定义IdleStateAwareChannelHandler的实现类,
//当Channel处理空闲状态时,会触发此方法.
public class Heartbeat extends IdleStateAwareChannelHandler {
@Override
public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
super.channelIdle(ctx, e);
if (e.getState() == IdleState.READER_IDLE){
byte[] test = " ac0bce0490007050006".getBytes();
ChannelBuffer channelBuffer = ChannelBuffers.buffer(test.length);
channelBuffer.writeBytes(upData);
//发送超时数据到终端.
e.getChannel().write(channelBuffer);
}
}
//第三步, 实现方式2:在扩展SimpleChannelHandler的handler类里,如下操作:
//记得注释掉第二步中的代码pipeline.addLast("hearbeat", new Heartbeat());
@Override
public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
if (e instanceof IdleStateEvent) {
IdleStateEvent ise = (IdleStateEvent)e;
if (ise.getState() == IdleState.READER_IDLE){
byte[] test = "超时 ...".getBytes();
ChannelBuffer channelBuffer = ChannelBuffers.buffer(test.length);
channelBuffer.writeBytes(test);
//发送超时数据到终端.
ctx.getChannel().write(channelBuffer);
}
}
super.handleUpstream(ctx, e);
}
-
ReadTimeoutHandler
//第一步,在服务启动类中设置数据处理管道.
...
bootstrap.setPipelineFactory(new TCPServerPipelineFactory());
...
//第二步,在数据处理管道实现类里配置空闲状态处理代码.
public class TCPServerPipelineFactory implements ChannelPipelineFactory {
@Override
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = Channels.pipeline();
//设置读取数据超时处理
pipeline.addLast("readTimeOut",new ReadTimeoutHandler(new HashedWheelTimer(),10));
pipeline.addLast("handler", new TCPServerHandler());
return pipeline;
}
//第三步, 在扩展SimpleChannelHandler的handler类里,如下操作:
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
//对读取超时异常进行判断
if (e.getCause() instanceof ReadTimeoutException) {
byte[] test = "超时 ...".getBytes();
ChannelBuffer channelBuffer = ChannelBuffers.buffer(test.length);
channelBuffer.writeBytes(test);
ctx.getChannel().write(channelBuffer);
} else {
logger.log(Level.WARN, "Unexpected exception from downstream.",e.getCause());
}
}
-
WriteTimeoutHandler
略,原理同ReadTimeoutHandler。
相关推荐
配置maven添加io.netty 在com.zhao的包下的文件,可以自行修改使用
在本文中,我们将深入探讨 Netty 的断线重连机制和心跳机制,这两个特性对于维持稳定可靠的网络通信至关重要。 首先,让我们了解**断线重连机制**。在分布式系统中,网络连接可能会因为各种原因中断,如网络抖动、...
在本文中,我们将深入探讨如何利用 Netty 和 WebSocket 实现心跳检测和断线重连机制。 首先,我们需要理解 WebSocket 协议。WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,它为客户端和服务器提供了低...
3. 使用Netty的ChannelHandlerContext发送心跳包,并设置相应的超时检查和处理机制。 4. 如何处理Socket连接,发送和接收自定义协议的数据。 5. 示例代码展示如何在Java中编写和运行Netty应用。 这个demo将是一个很...
在本文中,我们将深入探讨 Netty 实现简单通信和心跳机制的基础知识,这对于初学者来说是一个很好的起点。 一、Netty 框架简介 Netty 是由 JBoss 提供的一个开源框架,基于 Java NIO(非阻塞I/O)构建。Netty 提供...
在“基于netty_4.0.26的心跳检测”这个主题中,我们将深入探讨如何在Netty 4.0.26版本中实现心跳检测机制,以确保网络连接的稳定性和可靠性。 心跳检测是网络通信中的一个重要概念,主要用于检测客户端与服务器之间...
本篇文章将深入探讨如何在 Netty 中实现心跳机制。 ### 1. Netty 心跳概念 心跳机制在网络通信中扮演着重要角色,它通过定期发送小型数据包或无实际内容的数据包(通常称为"心跳包")来验证连接的活跃性。当连接的...
当我们需要在分布式系统中实现可靠的数据传输时,心跳检测机制就显得至关重要。下面我们将深入探讨"spring整合netty心跳检测"这一主题。 首先,我们要理解心跳检测的基本概念。心跳检测是指在通信双方之间周期性地...
- **服务器端**:服务器端创建一个监听特定端口的Netty ServerBootstrap,配置心跳检查的逻辑,如设置心跳间隔时间和超时时间,当接收到心跳请求时,返回心跳响应。 - **客户端**:客户端周期性地向服务器发送心跳...
综上所述,“断网断电心跳检测”是保障WebSocket通信稳定性和可靠性的关键技术,Netty通过提供灵活的心跳检测机制,使得开发者能够轻松应对网络异常,确保服务的连续性和用户体验。对于处理实时性强、对网络依赖度高...
5. **心跳超时管理**: 使用`ScheduledExecutorService`或者Netty的`ScheduledFuture`来定时触发心跳检查。当心跳检测到超时时,可以执行相应的处理,比如关闭连接。 6. **异常处理**: 当心跳检测失败时,需要有相应...
Java Netty实现心跳机制过程解析 在本文中,我们将了解如何使用Java Netty实现心跳机制过程解析。心跳机制是一种检测客户端是否空闲的机制,用于关闭长期空闲的客户端连接,释放系统资源。 首先,让我们了解为什么...
总的来说,理解和掌握 Netty 的心跳检测机制对于开发高可用、稳定的网络服务至关重要。通过自定义 `IdleStateHandler` 参数,我们可以灵活地调整心跳检测的频率,从而有效地监控和管理网络连接的健康状态。
#### 心跳机制 - 服务端采用 `IdleStateHandler`,在一段时间内(默认15s)没有读到客户端消息则说明客户端已离线,服务器会触发读超时事件断开连接 - 客户端采用定时(默认10s)任务方式向服务端发送一个ping消息...
特别地,手册还介绍了Netty实现聊天功能和WebSocket聊天功能的方法,以及Netty超时机制和心跳程序的实现。这些功能的实现案例,为用户提供了实用的网络通信应用的构建框架。 用户手册中还提到了Netty的另一个重要...
本文将深入探讨如何使用SpringBoot整合Netty4实现即时通讯,并结合Zookeeper进行服务发现与管理,同时包含心跳检测和下线重连机制。 **一、SpringBoot与Netty集成** SpringBoot以其简化Spring应用初始搭建以及开发...
最后,用户指南中还会介绍Netty的其他高级特性,如实现WebSocket聊天功能,以及Netty超时机制和心跳程序的实现。这些高级特性对于构建复杂的网络应用程序至关重要。 总之,Netty用户指南通过全面的介绍和实例演示,...
在这个“Netty HelloWorld + HeartBeat Demo”中,我们将深入理解Netty的基本用法以及如何实现心跳机制。 首先,让我们从Netty HelloWorld Demo开始。这个Demo通常用于展示如何使用Netty创建一个简单的TCP服务器和...
对于性能优化,可以调整Netty的线程模型、缓冲区大小、心跳机制等参数。 总的来说,SpringBoot整合Netty的实践涉及到SpringBoot的应用构建、Netty的服务器和客户端创建、响应式编程模型、以及两者的交互和配置优化...
【Netty 超时机制及心跳程序实现】(1.5.1-1.5.3)讲解了如何处理连接超时和保持连接活跃的心跳机制,这对于长连接服务至关重要。 最后,【Architectural Overview】部分总结了Netty的整体架构,帮助读者从宏观角度...