You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
3.3 KiB

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