package com.ruoyi.imserver.netty; import com.ruoyi.common.im.constant.IMRedisKey; import com.ruoyi.common.im.mq.RedisMQTemplate; import io.netty.channel.EventLoopGroup; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.context.SmartLifecycle; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import java.util.List; @Slf4j @Component @AllArgsConstructor public class IMServerGroup implements CommandLineRunner { public static volatile long serverId = 0; private final RedisMQTemplate redisMQTemplate; private final List imServers; /*** * 判断服务器是否就绪 * **/ public boolean isReady() { for (IMServer imServer : imServers) { if (!imServer.isReady()) { return false; } } return true; } @Override public void run(String... args) { try { System.out.println("========== IMServerGroup 开始初始化 =========="); // 1. 先验证Redis连接 if (!testRedisConnection()) { // 不要直接退出,记录错误,让应用继续启动(如果需要) System.err.println("严重:Redis连接失败,但应用将继续启动(部分功能可能不可用)"); // 根据业务决定:如果Redis是必须的,可以抛出异常: // throw new RuntimeException("Redis连接失败,应用启动中止"); } String key = IMRedisKey.IM_MAX_SERVER_ID; serverId = redisMQTemplate.opsForValue().increment(key, 1); for (IMServer imServer : imServers) { imServer.start(); } System.out.println("========== IMServerGroup 初始化完成 =========="); }catch (Exception e) { // 捕获所有异常,打印详细信息,但可以选择不向上抛出,防止应用退出 System.err.println("IMServerGroup 初始化过程中发生严重错误:"); e.printStackTrace(); // 打印完整的堆栈跟踪,这能帮你定位到具体行号 // 重要决策:是否重新抛出异常? // 如果希望应用继续运行(比如Redis失败但想先看其他功能),就注释掉下一行 // 如果希望应用停止,就保留下一行 // throw new RuntimeException("IMServerGroup启动失败", e); } } private boolean testRedisConnection() { try { // 使用你之前编写的连接测试代码 // 例如:String pong = redisTemplate.getConnectionFactory().getConnection().ping(); String pong = redisMQTemplate.getConnectionFactory().getConnection().ping(); System.out.println("Redis连接测试成功 "+pong); return true; } catch (Exception e) { System.err.println("Redis连接测试失败: " + e.getClass().getName() + " - " + e.getMessage()); return false; } } @PreDestroy public void destroy() { // 停止服务 log.info("消费线程停止12..."); for (IMServer imServer : imServers) { imServer.stop(); } } }