Java 后端 / 系统课时
实现长连接服务
实现长连接服务
本节介绍如何基于 Netty 构建具备心跳检测和状态管理能力的长连接服务,解决连接存活判断、异常断开处理和资源释放问题,最终实现一个可维护的通信服务。
学习目标
- 理解长连接服务中的连接生命周期和状态维护方式
- 掌握 Netty IdleStateHandler 与空闲事件处理机制
- 能够处理连接失效、状态清理和资源释放问题
长连接的核心问题
短连接通常在一次请求完成后关闭 TCP 连接,而长连接会持续保持通信通道,让客户端和服务端可以随时发送消息,常用于即时通信、网关连接和实时推送。
长连接服务需要解决三个核心问题:如何判断连接仍然有效、如何避免无效连接长期占用资源、如何在断开后清理业务状态。仅保持 Socket 不关闭无法解决这些问题,需要结合心跳检测和连接管理。
使用 Netty 实现心跳检测
Netty 提供 IdleStateHandler 检测读写空闲状态。当连接达到指定空闲时间后,Handler 会触发 IdleStateEvent,业务代码可以根据事件发送心跳或关闭连接。
下面示例创建一个服务端 Pipeline,并通过自定义 Handler 处理读空闲事件。
java
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import java.util.concurrent.TimeUnit;
public class HeartbeatServer {
public static void main(String[] args) throws Exception {
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup worker = new NioEventLoopGroup();
try {
new ServerBootstrap()
.group(boss, worker)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
// 60 秒没有读取到客户端数据时触发空闲事件
ch.pipeline().addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt instanceof IdleStateEvent event && event.state() == IdleState.READER_IDLE) {
ctx.close();
}
}
});
}
})
.bind(<PORT>)
.sync()
.channel()
.closeFuture()
.sync();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}预期输出
text
Netty server started on port <PORT>
Client idle event detected after <TIME> seconds
Channel closed after idle timeout实际日志会根据端口、客户端行为和空闲时间配置变化,<PORT> 与 <TIME> 表示运行时动态值。
管理连接状态
生产环境通常需要维护用户和 Channel 的映射关系,例如用户登录后保存连接,用于服务端主动推送消息。连接建立时注册状态,断开时删除状态,避免业务层继续引用失效连接。
java
import io.netty.channel.Channel;
import java.util.concurrent.ConcurrentHashMap;
public class ConnectionManager {
private final ConcurrentHashMap<String, Channel> channels = new ConcurrentHashMap<>();
public void add(String userId, Channel channel) {
channels.put(userId, channel);
}
public void remove(String userId) {
channels.remove(userId);
}
public Channel get(String userId) {
return channels.get(userId);
}
}预期结果
text
user-1001 -> active channel
user-1001 removed after disconnect连接管理需要考虑并发访问、重复登录和服务重启后的状态恢复。连接规模较大时,应使用并发安全的数据结构,并避免在 Channel 失效后继续保存无效引用。
处理长连接异常断开
长连接并不代表永久连接。网络抖动、客户端崩溃、代理超时都会导致连接失效,因此服务端需要统一处理关闭事件。
常见处理策略包括:
- 收到断开事件后立即释放 Channel 关联资源
- 心跳检测失败后主动关闭连接
- 将业务状态与网络状态分离,避免连接异常影响业务数据
可靠长连接的关键是将心跳检测和状态管理结合起来:心跳负责判断连接是否存活,状态管理负责维护业务关系,异常处理负责释放资源。
按自己的节奏,确认真正理解。