fix: 数据库缓存写入改为 Fire-and-Forget

问题:
- 多个股票并发写入数据库缓存
- ISqlSugarClient 是 Singleton,共享连接
- Storageable.ExecuteCommandAsync 并发时连接冲突

修复:
1. 先写入内存缓存(确保返回给调用者)
2. 数据库缓存写入改为 Task.Run(Fire-and-Forget)
3. 写入失败只记录日志,不影响主流程

优先级:内存缓存 > 数据库缓存
- 内存缓存:必须成功,直接影响用户体验
- 数据库缓存:可选,失败后下次重新获取
This commit is contained in:
OpenClaw Agent 2026-03-24 10:33:37 +00:00
parent ad7761810d
commit e78d560f60

View File

@ -187,10 +187,7 @@ public class MarketDataService : IMarketDataService
throw new InvalidOperationException($"获取到的价格无效: {symbol} = {response.Price}"); throw new InvalidOperationException($"获取到的价格无效: {symbol} = {response.Price}");
} }
// 写入数据库缓存 // 先写入内存缓存(确保返回给调用者)
await SavePriceCacheAsync(symbol, assetType, response, source);
// 同时写入内存缓存5分钟有效
var cacheKey = $"{symbol.ToUpper()}_{assetType.ToUpper()}"; var cacheKey = $"{symbol.ToUpper()}_{assetType.ToUpper()}";
var expireAt = DateTime.Now.AddMinutes(5); var expireAt = DateTime.Now.AddMinutes(5);
_memoryCache[cacheKey] = (new MarketPriceCache _memoryCache[cacheKey] = (new MarketPriceCache
@ -203,6 +200,19 @@ public class MarketDataService : IMarketDataService
ExpiredAt = expireAt ExpiredAt = expireAt
}, expireAt); }, expireAt);
// 写入数据库缓存Fire-and-Forget失败不影响主流程
_ = Task.Run(async () =>
{
try
{
await SavePriceCacheAsync(symbol, assetType, response, source);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "[数据库缓存写入失败] Symbol={Symbol},忽略(内存缓存已生效)", symbol);
}
});
return response; return response;
} }