前言
ClientHousekeepingService 继承了 ChannelEventListener 监听器接口,负责对netty长连接产生的网络连接事件进行监听,比如:网络连接、网络关闭、网络异常、网络空闲事件,然后调度生产者管理组件、消费组管理组件、过滤服务器组件维护,断开它们内存中维护的网络长连接。
同时ClientHousekeepingService 内部还维护了一个定时调度线程,没隔10秒钟,扫描一次生产者管理组件、消费者管理组件、过滤服务器组件失活的长连接,进行清理。
源码版本:4.9.3
源码架构图
源码分析
源码 + 注释 如下:
// 客户端网络连接监听服务
public class ClientHousekeepingService implements ChannelEventListener {
private static final InternalLogger log = InternalLoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME);
private final BrokerController brokerController;
// 客户端网络连接调度线程池
private ScheduledExecutorService scheduledExecutorService = Executors
.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("ClientHousekeepingScheduledThread"));
public ClientHousekeepingService(final BrokerController brokerController) {
this.brokerController = brokerController;
}
public void start() {
// 添加调度任务,10秒扫描一次
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
// 扫描异常的客户端连接
ClientHousekeepingService.this.scanExceptionChannel();
} catch (Throwable e) {
log.error("Error occurred when scan not active client channels.", e);
}
}
}, 1000 * 10, 1000 * 10, TimeUnit.MILLISECONDS);
}
private void scanExceptionChannel() {
// 扫描生产者管理组件中的不活跃连接
this.brokerController.getProducerManager().scanNotActiveChannel();
// 扫描消费者管理组件中的不活跃连接
this.brokerController.getConsumerManager().scanNotActiveChannel();
// 扫描过滤器管理组件中的不活跃连接
this.brokerController.getFilterServerManager().scanNotActiveChannel();
}
public void shutdown() {
this.scheduledExecutorService.shutdown();
}
// 处理客户端连接事件,默认不做任何处理
@Override
public void onChannelConnect(String remoteAddr, Channel channel) {
}
// 处理客户端断开事件,关闭生产者管理组件、消费者管理组件、过滤器管理组件中的对应的channel
@Override
public void onChannelClose(String remoteAddr, Channel channel) {
this.brokerController.getProducerManager().doChannelCloseEvent(remoteAddr, channel);
this.brokerController.getConsumerManager().doChannelCloseEvent(remoteAddr, channel);
this.brokerController.getFilterServerManager().doChannelCloseEvent(remoteAddr, channel);
}
// 处理客户端异常事件,关闭生产者管理组件、消费者管理组件、过滤器管理组件中的对应的channel
@Override
public void onChannelException(String remoteAddr, Channel channel) {
this.brokerController.getProducerManager().doChannelCloseEvent(remoteAddr, channel);
this.brokerController.getConsumerManager().doChannelCloseEvent(remoteAddr, channel);
this.brokerController.getFilterServerManager().doChannelCloseEvent(remoteAddr, channel);
}
// 处理客户端空闲事件,关闭生产者管理组件、消费者管理组件、过滤器管理组件中的对应的channel
@Override
public void onChannelIdle(String remoteAddr, Channel channel) {
this.brokerController.getProducerManager().doChannelCloseEvent(remoteAddr, channel);
this.brokerController.getConsumerManager().doChannelCloseEvent(remoteAddr, channel);
this.brokerController.getFilterServerManager().doChannelCloseEvent(remoteAddr, channel);
}
}