package com.zehong.system.netty.listener;

import com.zehong.system.netty.NettyUdpServer;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
/**
 * @author lenovo
 * @date 2025/7/31
 * @description TODO
 */

@Component
@Order(1) // 控制启动顺序，数值越小越先执行
public class NettyServerListener implements ApplicationRunner {
    private static final Logger log = LoggerFactory.getLogger(NettyServerListener.class);

    @Autowired
    private NettyUdpServer nettyServer;

    /**
     * 应用启动后执行，启动Netty服务器
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            log.info("准备启动Netty服务器...");
            // 启动Netty服务
            nettyServer.start();

            // 注册钩子，在JVM关闭时优雅停止Netty服务
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                log.info("JVM即将关闭，准备停止Netty服务器...");
                nettyServer.stop();
            }));
        } catch (Exception e) {
            log.error("启动Netty服务器失败", e);
            // 启动失败时可以选择退出应用或进行其他处理
            // System.exit(1);
        }
    }
}
