首页>代码>基于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("系统成功关闭!");
    }
}
最近下载更多
wanglinddad  LV54 4月12日
shuangfu  LV24 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日
Uting  LV3 2023年2月21日
675104182  LV14 2023年1月31日
wayshort  LV2 2022年10月29日
最近浏览更多
wanglinddad  LV54 4月12日
silences_ftjh  LV10 3月22日
Xiaobaiya11  LV2 3月4日
3334004690  LV3 2月20日
打烊1234  LV2 1月30日
axdfer 1月2日
暂无贡献等级
ddy-ddy  LV4 2023年12月27日
erqiu2013  LV18 2023年12月27日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友