首页>代码>基于netty开发的在线聊天程序netty-chat>/netty-demo-m/src/main/java/com/example/netty/AppContext.java
package com.example.netty;


import com.example.netty.udpserver.UdpNettyServer;
import com.example.netty.websocketserver.WebSocketNettyServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;

@Component
@Scope("singleton")
public class AppContext {

    private final Logger logger = LoggerFactory.getLogger(AppContext.class);

    @Autowired
    private WebSocketNettyServer websocketNettyServer;
    @Autowired
    private UdpNettyServer udpNettyServer;


    private List<Thread> nettyThreads = new ArrayList<>();

    /**
     * 描述:Tomcat加载完ApplicationContext-main和netty文件后:
     *      1. 启动Netty WebSocket服务器;
     *      2. 加载用户数据;
     *      3. 加载用户交流群数据。
     */
    @PostConstruct
    public void init() {
        Thread websocketNettyThread = new Thread(websocketNettyServer);
        logger.info("开启独立线程,启动Netty WebSocket服务器...");
        websocketNettyThread.start();
        nettyThreads.add(websocketNettyThread);

        Thread uodNettyThread = new Thread(udpNettyServer);
        logger.info("开启独立线程,启动Netty UDP服务器...");
        uodNettyThread.start();
        nettyThreads.add(uodNettyThread);

    }

    /**
     * 描述:Tomcat服务器关闭前需要手动关闭Netty Websocket相关资源,否则会造成内存泄漏。
     *      1. 释放Netty Websocket相关连接;
     *      2. 关闭Netty Websocket服务器线程。(强行关闭,是否有必要?)
     */
    @SuppressWarnings("deprecation")
    @PreDestroy
    public void close() {
        logger.info("正在释放Netty Websocket相关连接...");
        websocketNettyServer.close();
        logger.info("正在关闭Netty UDP Websocket服务器线程...");
        for (Thread nettyThread :this.nettyThreads){
            nettyThread.stop();
        }
        logger.info("系统成功关闭!");
    }
}
最近下载更多
人间蒸发  LV23 3月12日
charleswang  LV7 2024年6月11日
ntboss2002  LV3 2024年5月8日
wanglinddad  LV55 2024年4月12日
shuangfu  LV25 2023年10月19日
qq1061521319  LV4 2023年9月1日
cto1206  LV3 2023年8月29日
youzitao  LV11 2023年4月17日
荣》Cowboy  LV12 2023年4月12日
dixiu000  LV4 2023年2月28日
最近浏览更多
kkkllll  LV2 1月9日
微信网友_7298640909209600  LV2 2024年12月22日
chuxue11  LV2 2024年11月18日
yunsgui  LV1 2024年6月26日
TY0165  LV20 2024年6月17日
charleswang  LV7 2024年6月11日
xiaozhi丶  LV15 2024年6月3日
develop  LV10 2024年6月2日
ntboss2002  LV3 2024年5月3日
wanglinddad  LV55 2024年4月12日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友