AIID方法变更

This commit is contained in:
lxu75
2025-05-14 17:57:14 +08:00
parent 876569bbb0
commit 5d6da858d0

View File

@@ -1,18 +1,33 @@
package com.volvo.ai.analytic.center.utils; package com.volvo.ai.analytic.center.utils;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Slf4j @Slf4j
@Component @Component
public class AiAnalysisUtils { public class AiAnalysisUtils {
/** private static Snowflake snowflake;
* 生成ai分析请求id
* @param businessType @PostConstruct
* @return public void init() {
*/ try {
// 使用 IP 生成唯一的 workerId
long workerId = ipToWorkerId(getLocalHostIP());
snowflake = IdUtil.getSnowflake(workerId, 0); // datacenterId = 0
log.info("Initialized Snowflake with workerId: {}", workerId);
} catch (Exception e) {
log.error("Failed to initialize Snowflake", e);
throw new RuntimeException("Snowflake initialization failed");
}
}
public static String getAiAnalysisRequestId(String businessType) { public static String getAiAnalysisRequestId(String businessType) {
if (businessType == null || businessType.trim().isEmpty()) { if (businessType == null || businessType.trim().isEmpty()) {
log.error("businessType is null or empty, using default value 'unknown'"); log.error("businessType is null or empty, using default value 'unknown'");
@@ -20,18 +35,26 @@ public class AiAnalysisUtils {
} }
try { try {
long snowflakeId = IdUtil.getSnowflakeNextId(); // 使用自定义的 Snowflake 实例生成 ID
if (snowflakeId == 0) { long snowflakeId = snowflake.nextId();
log.error("Failed to generate Snowflake ID");
throw new RuntimeException("Failed to generate Snowflake ID");
}
String aiAnalysisRequestId = businessType + "-" + snowflakeId; String aiAnalysisRequestId = businessType + "-" + snowflakeId;
log.info("Generated AI analysis request ID: {}", aiAnalysisRequestId); log.info("Generated AI analysis request ID: {}", aiAnalysisRequestId);
return aiAnalysisRequestId; return aiAnalysisRequestId;
} catch (Exception e) { } catch (Exception e) {
log.error("Error generating AI analysis request ID", e); log.error("Error generating AI analysis request ID", e);
//生成唯一字符串 return businessType + "-" + IdUtil.fastSimpleUUID();
return businessType + "-"+IdUtil.fastSimpleUUID();
} }
} }
// 获取本机 IP
private static String getLocalHostIP() throws UnknownHostException {
return InetAddress.getLocalHost().getHostAddress();
}
// 将 IP 转换为合法的 workerId (0 ~ 31)
private static long ipToWorkerId(String ip) {
String[] parts = ip.replaceAll("[^\\d.]", "").split("\\.");
int lastOctet = Integer.parseInt(parts[parts.length - 1]);
return lastOctet % 32; // 限制范围 [0, 31]
}
} }