fix: 修复批处理中的多次commit问题,bulk_create后清除缓存

This commit is contained in:
Windpicker-owo
2025-11-01 17:31:31 +08:00
parent 029d133e48
commit 2aeb06f708
2 changed files with 55 additions and 25 deletions

View File

@@ -266,7 +266,14 @@ class CRUDBase:
await session.refresh(instance)
# 注意commit在get_db_session的context manager退出时自动执行
# 但为了明确性这里不需要显式commit
return instance
# 注意create不清除缓存因为
# 1. 新记录不会影响已有的单条查询缓存get/get_by
# 2. get_multi的缓存会自然过期TTL机制
# 3. 清除所有缓存代价太大,影响性能
# 如果需要强一致性应该在查询时设置use_cache=False
return instance
async def update(
self,
@@ -459,8 +466,15 @@ class CRUDBase:
for instance in instances:
await session.refresh(instance)
return instances
# 批量创建的缓存策略:
# bulk_create通常用于批量导入场景此时清除缓存是合理的
# 因为可能创建大量记录,缓存的列表查询会明显过期
cache = await get_cache()
await cache.clear()
logger.info(f"批量创建{len(instances)}{self.model_name}记录后已清除缓存")
return instances
async def bulk_update(
self,