refactor: 移除 Redis/Rabbit 依赖,Agent Mongo 切至 ai_crm_angent_dev

This commit is contained in:
2026-10-22 00:02:46 +08:00
parent 8307ff95e4
commit 7685f280c6
25 changed files with 80 additions and 486 deletions
@@ -1,59 +0,0 @@
package top.xyquan.ecomdmbbackend.common.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis配置类
*/
@Configuration
public class RedisConfig {
/**
* 配置RedisTemplate
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.registerModule(new JavaTimeModule());
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
new Jackson2JsonRedisSerializer<>(objectMapper, Object.class);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
/** Stream 队列使用纯字符串序列化 */
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
}
@@ -5,7 +5,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 租户模型 API Key 加解密与 Redis 缓存。
* 租户模型 API Key 加解密配置。
*/
@Data
@Component
@@ -14,7 +14,4 @@ public class AgentLlmProperties {
/** AES 密钥材料;空则回退 jwt.secret */
private String secret = "";
/** Redis 运行时缓存 TTL 秒 */
private long runtimeCacheTtlSeconds = 600;
}
@@ -6,12 +6,10 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.agent.llm.config.AgentLlmProperties;
import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmModelMapper;
import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmProviderMapper;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.AgentLlmModelItemDTO;
@@ -33,7 +31,6 @@ import top.xyquan.ecomdmbbackend.modules.agent.llm.support.AgentLlmCrypto;
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.OpenAiCompatibleModelsProbe;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.Duration;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
@@ -46,7 +43,7 @@ import java.util.Set;
import java.util.stream.Collectors;
/**
* 公司多提供商模型 API:MySQL 存密文;Redis 按 company+provider+model 缓存明文。
* 公司多提供商模型 API:MySQL 存密文;运行时由 Agent 直拉内部 API(暂无 Redis 缓存)。
*/
@Slf4j
@Service
@@ -58,9 +55,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
private final AgentCompanyLlmProviderMapper providerMapper;
private final AgentCompanyLlmModelMapper modelMapper;
private final AgentLlmCrypto crypto;
private final AgentLlmProperties llmProperties;
private final CurrentUserContext currentUserContext;
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
private final OpenAiCompatibleModelsProbe modelsProbe;
@@ -102,7 +97,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
po.setCreateBy(userId);
po.setUpdateBy(userId);
providerMapper.insert(po);
evictRuntimeCache(companyId);
return toProviderVo(po, List.of());
}
@@ -129,8 +123,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
}
existing.setUpdateBy(userId);
providerMapper.updateById(existing);
evictRuntimeCache(companyId);
warmCacheForProvider(existing);
return toProviderVo(existing, listModelsByProvider(companyId, providerId));
}
@@ -146,7 +138,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
if (hadDefault) {
ensureCompanyHasDefault(companyId, currentUserContext.getCurrentUserId());
}
evictRuntimeCache(companyId);
}
@Override
@@ -214,8 +205,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
}
List<AgentCompanyLlmModelPO> saved = listModelsByProvider(companyId, providerId);
evictRuntimeCache(companyId);
warmCacheForProvider(provider);
return toProviderVo(provider, saved);
}
@@ -243,8 +232,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
}
modelMapper.updateById(row);
ensureCompanyHasDefault(companyId, userId);
evictRuntimeCache(companyId);
warmCacheForProvider(provider);
return toProviderVo(provider, listModelsByProvider(companyId, providerId));
}
@@ -312,13 +299,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
throw new BusinessException("提供商不存在");
}
AgentLlmRuntimeVO cached = readRuntimeCache(companyId, provider.getId(), selected.getModel());
if (cached != null) {
return cached;
}
AgentLlmRuntimeVO runtime = buildRuntimeForModel(provider, selected);
cacheRuntime(companyId, runtime);
return runtime;
return buildRuntimeForModel(provider, selected);
}
private AgentCompanyLlmModelPO resolveModelRow(
@@ -441,20 +422,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
return vo;
}
private void warmCacheForProvider(AgentCompanyLlmProviderPO provider) {
try {
for (AgentCompanyLlmModelPO m : listModelsByProvider(provider.getCompanyId(), provider.getId())) {
if (!Boolean.TRUE.equals(m.getEnabled())) {
continue;
}
cacheRuntime(provider.getCompanyId(), buildRuntimeForModel(provider, m));
}
} catch (Exception e) {
log.warn("预热 LLM 运行时缓存失败 companyId={} providerId={}",
provider.getCompanyId(), provider.getId(), e);
}
}
private static String normalizeApiStyle(String raw) {
if (!StringUtils.hasText(raw)) {
return "auto";
@@ -567,81 +534,4 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
return vo;
}
private static String redisKey(Long companyId, Long providerId, String model) {
return "agent:llm:rt:" + companyId + ":" + providerId + ":" + model;
}
private void cacheRuntime(Long companyId, AgentLlmRuntimeVO runtime) {
try {
Map<String, Object> payload = new HashMap<>();
payload.put("provider_id", runtime.getProviderId());
payload.put("base_url", runtime.getBaseUrl());
payload.put("api_key", runtime.getApiKey());
payload.put("model", runtime.getModel());
payload.put("context_window", runtime.getContextWindow());
payload.put("api_style", runtime.getApiStyle() == null ? "auto" : runtime.getApiStyle());
payload.put("extra_headers",
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
stringRedisTemplate.opsForValue().set(
redisKey(companyId, runtime.getProviderId(), runtime.getModel()),
objectMapper.writeValueAsString(payload),
Duration.ofSeconds(Math.max(60, llmProperties.getRuntimeCacheTtlSeconds())));
} catch (Exception e) {
log.warn("写入 LLM Redis 缓存失败 companyId={}", companyId, e);
}
}
private AgentLlmRuntimeVO readRuntimeCache(Long companyId, Long providerId, String model) {
try {
String raw = stringRedisTemplate.opsForValue().get(redisKey(companyId, providerId, model));
if (!StringUtils.hasText(raw)) {
return null;
}
Map<String, Object> map = objectMapper.readValue(raw, new TypeReference<>() {
});
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
Object pid = map.get("provider_id");
if (pid instanceof Number n) {
vo.setProviderId(n.longValue());
} else {
vo.setProviderId(providerId);
}
vo.setBaseUrl(String.valueOf(map.get("base_url")));
vo.setApiKey(String.valueOf(map.get("api_key")));
vo.setModel(String.valueOf(map.get("model")));
Object cw = map.get("context_window");
if (cw instanceof Number n) {
vo.setContextWindow(n.intValue());
} else if (cw != null && StringUtils.hasText(String.valueOf(cw))
&& !"null".equalsIgnoreCase(String.valueOf(cw))) {
try {
vo.setContextWindow(Integer.parseInt(String.valueOf(cw)));
} catch (NumberFormatException ignored) {
vo.setContextWindow(null);
}
} else {
vo.setContextWindow(null);
}
Object style = map.get("api_style");
vo.setApiStyle(style == null ? "auto" : normalizeApiStyle(String.valueOf(style)));
Object headers = map.get("extra_headers");
if (headers instanceof Map<?, ?> m) {
Map<String, String> h = new HashMap<>();
m.forEach((k, v) -> h.put(String.valueOf(k), String.valueOf(v)));
vo.setExtraHeaders(h);
} else {
vo.setExtraHeaders(Map.of());
}
return vo;
} catch (Exception e) {
return null;
}
}
private void evictRuntimeCache(Long companyId) {
Set<String> keys = stringRedisTemplate.keys("agent:llm:rt:" + companyId + "*");
if (keys != null && !keys.isEmpty()) {
stringRedisTemplate.delete(keys);
}
}
}
@@ -8,19 +8,6 @@ spring:
url: jdbc:mysql://192.168.3.100:3306/ai_crm_dev?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
username: ai_crm_dev
password: ai_crm_dev
data:
redis:
host: 192.168.3.100
port: 6379
password: redis_qinghua
database: 2
mongodb:
uri: mongodb://ecom_dmb_dev:ecom_dmb_dev@192.168.3.100:27017/ecom_dmb_dev
rabbitmq:
host: 192.168.3.100
username: ecom_dmb_dev
password: ecom_dmb_dev
virtual-host: /ecom_dmb_dev
jwt:
secret: your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
@@ -10,19 +10,6 @@ spring:
password: ecom_dmb_staging
hikari:
maximum-pool-size: 20
data:
redis:
host: 192.168.3.100
port: 6379
password: redis_qinghua
database: 0
mongodb:
uri: mongodb://qinghua:mongo_qinghua@192.168.3.100:27017/ecom_dmb_staging
rabbitmq:
host: 192.168.3.100
username: qinghua
password: rabbitmq_qinghua
jwt:
secret: staging-jwt-secret-key-must-be-at-least-64-bytes-long-for-hs512-algorithm
@@ -11,18 +11,6 @@ spring:
hikari:
maximum-pool-size: 20
minimum-idle: 10
data:
redis:
host: 192.168.3.100
port: 6379
password: redis_qinghua
database: 0
mongodb:
uri: mongodb://qinghua:mongo_qinghua@192.168.3.100:27017/ecom_dmb
rabbitmq:
host: 192.168.3.100
username: qinghua
password: rabbitmq_qinghua
jwt:
secret: prod-jwt-secret-key-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
@@ -8,19 +8,6 @@ spring:
url: jdbc:mysql://192.168.3.100:3306/ecom_dmb_test?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
username: ecom_dmb_test
password: ecom_dmb_test
data:
redis:
host: 192.168.3.100
port: 6379
password: redis_qinghua
database: 3
mongodb:
uri: mongodb://ecom_dmb_test:ecom_dmb_test@192.168.3.100:27017/ecom_dmb_test
rabbitmq:
host: 192.168.3.100
username: ecom_dmb_test
password: ecom_dmb_test
virtual-host: /ecom_dmb_test
jwt:
secret: your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
@@ -32,32 +32,6 @@ spring:
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 30000
data:
redis:
timeout: 10000ms # Lettuce 命令执行超时,需 >= leftPop 的 5 秒等待时间
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: -1ms
mongodb:
# host/uri 见各环境;这里只放公共行为
auto-index-creation: false
rabbitmq:
# host/账号见各环境
port: 5672
virtual-host: /
publisher-confirm-type: correlated
publisher-returns: true
template:
mandatory: true
listener:
simple:
acknowledge-mode: auto
# 与全量/增量 listener concurrency 同量级,避免长任务预取过多
prefetch: 4
default-requeue-rejected: false
# Spring AI MCP Server(Agent 能力面;鉴权见 ecom.agent.mcp)
ai:
mcp:
@@ -93,7 +67,6 @@ ecom:
llm:
# API Key 加解密材料;空则派生自 jwt.secret
secret: ${AGENT_LLM_SECRET:}
runtime-cache-ttl-seconds: 600
# JWT 令牌有效期(密钥见各环境配置)
jwt: