add
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
"""平台配置服务:system_configs 表 + Redis 缓存 60s(后台修改即时生效)"""
|
||||
from typing import Any
|
||||
|
||||
import redis.asyncio as aioredis
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.common import SystemConfig
|
||||
|
||||
CACHE_KEY = "config:system"
|
||||
CACHE_TTL = 60
|
||||
|
||||
|
||||
async def get_all_configs(db: AsyncSession, redis: aioredis.Redis) -> dict[str, str]:
|
||||
"""全量读取配置(Redis Hash 缓存 60s)"""
|
||||
cached = await redis.hgetall(CACHE_KEY) # type: ignore[misc]
|
||||
if cached:
|
||||
return dict(cached)
|
||||
rows = (await db.execute(select(SystemConfig))).scalars().all()
|
||||
configs = {row.config_key: row.config_value for row in rows}
|
||||
if configs:
|
||||
await redis.hset(CACHE_KEY, mapping=configs) # type: ignore[misc]
|
||||
await redis.expire(CACHE_KEY, CACHE_TTL)
|
||||
return configs
|
||||
|
||||
|
||||
async def get_config(db: AsyncSession, redis: aioredis.Redis, key: str, default: Any = None) -> str | Any:
|
||||
"""读取单个配置项"""
|
||||
configs = await get_all_configs(db, redis)
|
||||
return configs.get(key, default)
|
||||
|
||||
|
||||
async def get_config_int(db: AsyncSession, redis: aioredis.Redis, key: str, default: int) -> int:
|
||||
value = await get_config(db, redis, key, None)
|
||||
try:
|
||||
return int(value) if value is not None else default
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
async def set_config(db: AsyncSession, redis: aioredis.Redis, key: str, value: str, admin_id: int | None = None) -> None:
|
||||
"""写入配置并失效缓存(后台调用)"""
|
||||
row = await db.get(SystemConfig, key)
|
||||
if row is None:
|
||||
db.add(SystemConfig(config_key=key, config_value=value, updated_by=admin_id))
|
||||
else:
|
||||
row.config_value = value
|
||||
row.updated_by = admin_id
|
||||
await db.commit()
|
||||
await redis.delete(CACHE_KEY)
|
||||
Reference in New Issue
Block a user