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
+4 -3
View File
@@ -18,7 +18,7 @@ deploy/ # 部署 TUI,流程见 deploy/MANUAL-DEPLOY.md
## 后端(apps/server)
- 构建 `./mvnw clean package -DskipTests`,运行 `./mvnw spring-boot:run`(默认 dev profile)
- 运行依赖环境变量:`DB_URL` / `DB_USERNAME` / `DB_PASSWORD` / `REDIS_HOST` / `REDIS_PASSWORD` / `JWT_SECRET`,见 README.md 与 `application-{profile}.yml`;MongoDB / RabbitMQ 连接见各 profile(与 MySQL 同机,账号 `qinghua`)
- 运行依赖:MySQL + `JWT_SECRET`(见 `application-{profile}.yml`);**已去掉 Redis / RabbitMQ / Server 侧 Mongo**
- 测试 `./mvnw test`,单个 `./mvnw test -Dtest=RoleAspectTest`
- 架构设计文档在 `docs/`(权限控制、开放接口、Agent/MCP 等),改动相关模块前先读
- `.vscode/settings.json` 已关闭 Eclipse null analysis(MyBatis-Plus 方法引用误报),不要补 `@SuppressWarnings("null")`
@@ -46,8 +46,9 @@ deploy/ # 部署 TUI,流程见 deploy/MANUAL-DEPLOY.md
- `cd apps/agent && python -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt`
- 配置 `.env`(参考 `.env.example`):`JWT_SECRET` 须与 Java `jwt.secret` 一致
- 运行:`uvicorn api.main:app --reload --port 8200`
- 租户自管 OpenAI Compatible 凭证(Mongo 加密 + Redis 缓存);聊天/会话在 Agent Mongo 库
- MCP 电商工具(BI / catalog / pdd)已拆除;当前 MCP 面主要为 `mcp_ping`,待 CRM 工具再挂
- 租户自管 OpenAI Compatible 凭证(Key 在 Server MySQL);聊天/会话/记忆在 Agent Mongo(dev:`ai_crm_angent_dev`)
- LLM 运行时直拉 Server 内部 API(暂无 Redis 缓存)
- MCP 电商工具已拆除;当前主要为 `mcp_ping`,待 CRM 工具再挂
## 授权(apps/license-server)
+2 -4
View File
@@ -2,10 +2,8 @@
# 可另建 gitignore 的 .env 覆盖本文件中的密钥
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev
MONGO_DB=ecom_dmb_agent_dev
# 与 Server application-dev 同 Redis DB=2
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/2
MONGO_URI=mongodb://ai_crm_angent_dev:ai_crm_angent_dev@192.168.3.100:27017/?authSource=ai_crm_angent_dev
MONGO_DB=ai_crm_angent_dev
SERVER_BASE_URL=http://localhost:8080
LLM_FALLBACK_ENABLED=true
LLM_FALLBACK_BASE_URL=https://api.deepseek.com/v1
+2 -4
View File
@@ -9,12 +9,10 @@
# 本地也可再建 gitignore 的 .env,会覆盖同名变量(便于放真实 Key)。
# 部署时 compose 注入 AGENT_ENV=test|pre|prod,并挂载对应 .env.{env}。
#
# Redis:与同环境 Server 共用同一 Redis DB,读缓存键 agent:llm:rt:*
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev
MONGO_DB=ecom_dmb_agent_dev
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/2
MONGO_URI=mongodb://ai_crm_angent_dev:ai_crm_angent_dev@192.168.3.100:27017/?authSource=ai_crm_angent_dev
MONGO_DB=ai_crm_angent_dev
SERVER_BASE_URL=http://localhost:8080
LLM_FALLBACK_ENABLED=true
LLM_FALLBACK_BASE_URL=https://api.deepseek.com/v1
-2
View File
@@ -1,10 +1,8 @@
# 预发环境(AGENT_ENV=pre,端口 8202)
# 与 Server application-pre 对齐:Redis DB=0、后端 8102
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://qinghua:mongo_qinghua@192.168.3.100:27017/?authSource=ecom_dmb_agent_pre
MONGO_DB=ecom_dmb_agent_pre
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/0
SERVER_BASE_URL=http://192.168.3.101:8102
LLM_FALLBACK_ENABLED=false
LLM_FALLBACK_BASE_URL=
-2
View File
@@ -1,10 +1,8 @@
# 生产环境(AGENT_ENV=prod,端口 8203)
# 与 Server application-prod 对齐:Redis DB=0、后端 8103
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://qinghua:mongo_qinghua@192.168.3.100:27017/?authSource=ecom_dmb_agent
MONGO_DB=ecom_dmb_agent
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/0
SERVER_BASE_URL=http://192.168.3.101:8103
LLM_FALLBACK_ENABLED=false
LLM_FALLBACK_BASE_URL=
-2
View File
@@ -1,10 +1,8 @@
# 测试环境(AGENT_ENV=test,端口 8201)
# 与 Server application-test 对齐:Redis DB=3、后端 8101
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://ecom_dmb_agent_test:ecom_dmb_agent_test@192.168.3.100:27017/?authSource=ecom_dmb_agent_test
MONGO_DB=ecom_dmb_agent_test
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/3
SERVER_BASE_URL=http://192.168.3.101:8101
LLM_FALLBACK_ENABLED=false
LLM_FALLBACK_BASE_URL=
+2 -3
View File
@@ -37,9 +37,8 @@ API 前缀:`/api/agent/...`(会话/聊天/记忆;与前端代理 `/api/age
|------|------|
| `AGENT_ENV` | 选择 `.env.{env}` |
| `JWT_SECRET` | 与 Java `jwt.secret` 一致 |
| `MONGO_URI` / `MONGO_DB` | Agent 独立库(sessions / messages / memory) |
| `REDIS_URL` | **与同环境 Server 同 DB**,读 LLM 运行时缓存 `agent:llm:rt:*` |
| `SERVER_BASE_URL` | Java 根地址,内部拉 `/api/internal/agent/llm-runtime` |
| `MONGO_URI` / `MONGO_DB` | Agent 独立库(sessions / messages / memory);dev 默认 `ai_crm_angent_dev` |
| `SERVER_BASE_URL` | Java 根地址,内部拉 `/api/internal/agent/llm-runtime`(暂无 Redis 缓存) |
| `MCP_BASE_URL` / `MCP_BEARER_TOKEN` | 调 Server `/mcp`;Bearer 须与 Java `AGENT_MCP_TOKEN` / `ecom.agent.mcp.bearer-token` 一致,空则不加载 MCP 工具 |
| `LLM_FALLBACK_*` | 仅本地:公司未配置时的 OpenAI Compatible fallback |
| `CHAT_HISTORY_FETCH_LIMIT` | 从 Mongo 最多拉多少条再按 token 裁剪(默认 200) |
+8 -8
View File
@@ -13,17 +13,16 @@ from domain.models import Actor
from infrastructure.auth.jwt import parse_actor
from infrastructure.llm.factory import OpenAICompatibleStreamer
from infrastructure.llm.gateway import ServerLlmRuntimeGateway
from infrastructure.persistence.memory.cache import (
NoopLlmProtocolCapabilityCache,
NoopLlmRuntimeCache,
)
from infrastructure.persistence.mongo.client import get_db
from infrastructure.persistence.mongo.repositories import (
MongoMemoryRepository,
MongoMessageRepository,
MongoSessionRepository,
)
from infrastructure.persistence.redis.cache import (
RedisLlmProtocolCapabilityCache,
RedisLlmRuntimeCache,
get_redis,
)
async def current_actor(
@@ -41,8 +40,9 @@ async def current_actor(
async def llm_runtime_service(
settings: Settings = Depends(get_settings),
) -> LlmRuntimeService:
cache = RedisLlmRuntimeCache(get_redis(settings))
return LlmRuntimeService(settings, cache, ServerLlmRuntimeGateway(settings))
return LlmRuntimeService(
settings, NoopLlmRuntimeCache(), ServerLlmRuntimeGateway(settings)
)
async def session_service(
@@ -77,7 +77,7 @@ async def chat_service(
llm_runtime=llm_svc,
memory=mem_svc,
streamer=OpenAICompatibleStreamer(
RedisLlmProtocolCapabilityCache(get_redis(settings)),
NoopLlmProtocolCapabilityCache(),
capability_ttl_seconds=settings.llm_capability_ttl_seconds,
),
)
-2
View File
@@ -12,7 +12,6 @@ from api.response import fail
from api.routers import chat, memories, sessions
from config.settings import get_settings
from infrastructure.persistence.mongo.client import close_mongo, ensure_indexes, get_db
from infrastructure.persistence.redis.cache import close_redis
@asynccontextmanager
@@ -22,7 +21,6 @@ async def lifespan(_app: FastAPI):
await ensure_indexes(db)
yield
await close_mongo()
await close_redis()
def create_app() -> FastAPI:
@@ -1,4 +1,4 @@
"""租户 LLM 运行时解析:Redis → Server 内部 API → 本地 fallback。"""
"""租户 LLM 运行时解析:缓存(可 Noop)→ Server 内部 API → 本地 fallback。"""
from __future__ import annotations
+4 -6
View File
@@ -38,7 +38,7 @@ class Settings(BaseSettings):
extra="ignore",
)
app_name: str = "ecom-dmb-agent"
app_name: str = "ai-crm-agent"
# 当前环境名(只读展示;实际由 AGENT_ENV 决定加载哪个文件)
agent_env: str = _AGENT_ENV
host: str = "0.0.0.0"
@@ -49,11 +49,9 @@ class Settings(BaseSettings):
jwt_secret: str = "your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security"
jwt_algorithms: str = "HS512"
mongo_uri: str = "mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev"
mongo_db: str = "ecom_dmb_agent_dev"
# 须与同环境 Server Redis 同库,才能命中 agent:llm:rt:* 缓存
redis_url: str = "redis://:redis_qinghua@192.168.3.100:6379/2"
mongo_uri: str = "mongodb://ai_crm_angent_dev:ai_crm_angent_dev@192.168.3.100:27017/?authSource=ai_crm_angent_dev"
mongo_db: str = "ai_crm_angent_dev"
# 本地缓存 TTL(当前为 Noop,直连 Server;预留)
llm_cache_ttl_seconds: int = 600
# Java Server 根地址(内部拉 LLM 运行时)
@@ -0,0 +1,44 @@
"""内存空实现:暂不接 Redis,LLM 运行时每次走 Server 内部 API。"""
from __future__ import annotations
from domain.models import LlmProtocolCapability, LlmRuntimeConfig
from domain.ports import LlmProtocolCapabilityCache, LlmRuntimeCache
class NoopLlmRuntimeCache(LlmRuntimeCache):
async def get(
self,
company_id: int,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig | None:
return None
async def set(
self,
company_id: int,
config: LlmRuntimeConfig,
ttl_seconds: int,
) -> None:
return None
async def delete(self, company_id: int) -> None:
return None
class NoopLlmProtocolCapabilityCache(LlmProtocolCapabilityCache):
async def get(
self, *, provider_id: int | None, base_url: str
) -> LlmProtocolCapability | None:
return None
async def set(
self,
*,
provider_id: int | None,
base_url: str,
capability: LlmProtocolCapability,
ttl_seconds: int,
) -> None:
return None
@@ -1,153 +0,0 @@
"""Redis 缓存租户 LLM 运行时配置(按公司+提供商+模型)。"""
from __future__ import annotations
import json
import redis.asyncio as redis
from config.settings import Settings
from domain.models import LlmProtocolCapability, LlmRuntimeConfig
from domain.ports import LlmProtocolCapabilityCache, LlmRuntimeCache
from infrastructure.llm.api_style import normalize_api_style
class RedisLlmRuntimeCache(LlmRuntimeCache):
def __init__(self, client: redis.Redis) -> None:
self._r = client
@staticmethod
def _key(company_id: int, provider_id: int | None, model: str | None) -> str:
if provider_id is not None and model:
return f"agent:llm:rt:{company_id}:{provider_id}:{model}"
if model:
return f"agent:llm:rt:{company_id}:{model}"
return f"agent:llm:rt:{company_id}"
async def get(
self,
company_id: int,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig | None:
raw = await self._r.get(self._key(company_id, provider_id, model))
if not raw and provider_id is not None and model:
# 兼容旧键 companyId:model
raw = await self._r.get(self._key(company_id, None, model))
if not raw:
return None
data = json.loads(raw)
cfg = LlmRuntimeConfig(
base_url=data["base_url"],
api_key=data["api_key"],
model=data["model"],
provider_id=_optional_int(data.get("provider_id")) or provider_id,
extra_headers=data.get("extra_headers") or {},
context_window=_optional_int(data.get("context_window")),
api_style=normalize_api_style(data.get("api_style")),
)
if model and cfg.model and cfg.model != model:
return None
if provider_id is not None and cfg.provider_id is not None and cfg.provider_id != provider_id:
return None
return cfg
async def set(
self,
company_id: int,
config: LlmRuntimeConfig,
ttl_seconds: int,
) -> None:
payload = {
"provider_id": config.provider_id,
"base_url": config.base_url,
"api_key": config.api_key,
"model": config.model,
"extra_headers": config.extra_headers,
"context_window": config.context_window,
"api_style": normalize_api_style(config.api_style),
}
await self._r.set(
self._key(company_id, config.provider_id, config.model),
json.dumps(payload),
ex=ttl_seconds,
)
async def delete(self, company_id: int) -> None:
keys = await self._r.keys(f"agent:llm:rt:{company_id}*")
if keys:
await self._r.delete(*keys)
_redis: redis.Redis | None = None
def _optional_int(v) -> int | None:
if v is None:
return None
try:
n = int(v)
except (TypeError, ValueError):
return None
return n if n > 0 else None
def get_redis(settings: Settings) -> redis.Redis:
global _redis
if _redis is None:
_redis = redis.from_url(settings.redis_url, decode_responses=True)
return _redis
class RedisLlmProtocolCapabilityCache(LlmProtocolCapabilityCache):
"""按 provider_id(优先)或 base_url 缓存 Responses/store 能力。"""
def __init__(self, client: redis.Redis) -> None:
self._r = client
@staticmethod
def _key(*, provider_id: int | None, base_url: str) -> str:
if provider_id is not None and int(provider_id) > 0:
return f"agent:llm:cap:p:{int(provider_id)}"
url = (base_url or "").rstrip("/").lower()
return f"agent:llm:cap:u:{url}"
async def get(
self, *, provider_id: int | None, base_url: str
) -> LlmProtocolCapability | None:
raw = await self._r.get(self._key(provider_id=provider_id, base_url=base_url))
if not raw:
return None
try:
data = json.loads(raw)
except json.JSONDecodeError:
return None
return LlmProtocolCapability(
responses=data.get("responses"),
store=data.get("store"),
)
async def set(
self,
*,
provider_id: int | None,
base_url: str,
capability: LlmProtocolCapability,
ttl_seconds: int,
) -> None:
payload = {
"responses": capability.responses,
"store": capability.store,
}
await self._r.set(
self._key(provider_id=provider_id, base_url=base_url),
json.dumps(payload),
ex=max(60, ttl_seconds),
)
async def close_redis() -> None:
global _redis
if _redis is not None:
await _redis.aclose()
_redis = None
-1
View File
@@ -5,7 +5,6 @@ pydantic>=2.9.0
pydantic-settings>=2.6.0
PyJWT>=2.9.0
motor>=3.6.0
redis>=5.2.0
httpx>=0.27.0
langchain-core>=0.3.0
langchain-openai>=0.3.26
+10 -22
View File
@@ -1,44 +1,32 @@
# ecom-dmb-backend
# ai-crm server(原 ecom-dmb-backend)
电商 DMB 后端服务
AI CRM 主后端
## 技术栈
- Java 17 + Spring Boot 3.2
- MyBatis-Plus + MySQL
- Redis(导入任务队列 + 缓存)
- MongoDB(BI 聚合统计)
- RabbitMQ(业务消息队列)
- Java 17 + Spring Boot 3.5
- MyBatis-Plus + MySQL + Flyway
- JWT 认证(HS512)
- Lombok + MapStruct
- Spring AI MCP Server
- Lombok
## 环境要求
- JDK 17+
- MySQL 8.0+
- Redis 6.0+
- MongoDB 6.0+
- RabbitMQ 3.12+
- Maven 3.9+
## 快速启动
### 1. 配置环境变量(生产环境必须)
### 1. 配置(见 `application-{profile}.yml`)
```bash
export DB_URL="jdbc:mysql://<host>:3306/ecom_dmb_dev?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true"
export DB_USERNAME="ecom_dmb_dev"
export DB_PASSWORD="<your-db-password>"
export REDIS_HOST="<your-redis-host>"
export REDIS_PORT="6379"
export REDIS_PASSWORD="<your-redis-password>"
export JWT_SECRET="<your-64-byte-secret-key>"
```
开发默认连 `ai_crm_dev`;生产请用环境变量覆盖数据源与 `JWT_SECRET`。
空库启动时 Flyway 自动建表,再由 `SysInitRunner` 灌种子(默认超管 `admin` / `admin123`)。
### 2. 启动
```bash
cd ecom-dmb-backend
./mvnw spring-boot:run
```
-20
View File
@@ -143,26 +143,6 @@
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<!-- Spring Data Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Redis连接池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- Spring Data MongoDB(BI 聚合统计) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- RabbitMQ(消息队列) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!-- Jackson序列化支持 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
@@ -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: