对等连接异常:探究原因和可能的解决思路
在使用 netty 实现对等连接时,偶尔会遇到 “对等连接异常”。此异常通常源自客户端或服务端意外中断连接。虽然客户端已实施断开重连机制,但并未识别重连记录。为了进一步理解问题根源,我们分析了以下代码片段:
客户端重连代码
@component public class bdspnettysocketclient { private logger log = loggerfactory.getlogger(bdspnettysocketclient.class); private nioeventloopgroup eventexecutors; public static final concurrenthashmap<string, channel> mchannel = new concurrenthashmap<>(); @postconstruct public void start() { try { this.init(); } catch (exception e) { log.error("启动 netty 客户端出现异常", e); } } @predestroy public void destroy() { this.eventexecutors.shutdowngracefully(); } private void init() { if (mchannel.get("channel") != null) { mchannel.clear(); } this.eventexecutors = new nioeventloopgroup(1); bootstrap bootstrap = new bootstrap(); bootstrap.group(eventexecutors); bootstrap.channel(niosocketchannel.class); bootstrap.option(channeloption.so_keepalive, true); bootstrap.handler(new bdspnettysocketclientinitializer()); channelfuture channelfuture = bootstrap.connect("", ); channelfuture.addlistener(new connectionlistener()); } public void send(string msg) { try { mchannel.get("channel").writeandflush(unpooled.copiedbuffer(msg, charsetutil.utf_8)); } catch (exception e) { log.error(this.getclass().getname().concat(".send has error"), e); } } public void send(object msg) { try { mchannel.get("channel").writeandflush(msg); } catch (exception e) { log.error(this.getclass().getname().concat(".send has error"), e); } } }
断开重连代码
@Component public class ConnectionListener implements ChannelFutureListener { private BdspNettySocketClient bdspNettySocketClient = new BdspNettySocketClient(); @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (!channelFuture.isSuccess()) { final EventLoop loop = channelFuture.channel().eventLoop(); loop.schedule(new Runnable() { @Override public void run() { System.err.println("服务端链接不上,开始重连操作..."); bdspNettySocketClient.start(); } }, 2L, TimeUnit.SECONDS); } else { System.err.println("服务端链接成功..."); } } }
分析代码后,我们推断问题的可能原因是:
- 上游客户端中断连接
客户端重连机制只针对本地客户端断开连接的情况,并不能处理上游客户端中断连接。
- 日志写法问题
客户端重连日志只打印在控制台,而没有记录在日志文件中。导致未能检测到重连记录。
可能的解决思路:
- 在客户端重连代码中加入对上游客户端断开连接的处理。
- 修改客户端重连日志写法,将日志记录到文件中,便于查看重连记录。