fix: 数据库缓存写入改为 Fire-and-Forget
问题: - 多个股票并发写入数据库缓存 - ISqlSugarClient 是 Singleton,共享连接 - Storageable.ExecuteCommandAsync 并发时连接冲突 修复: 1. 先写入内存缓存(确保返回给调用者) 2. 数据库缓存写入改为 Task.Run(Fire-and-Forget) 3. 写入失败只记录日志,不影响主流程 优先级:内存缓存 > 数据库缓存 - 内存缓存:必须成功,直接影响用户体验 - 数据库缓存:可选,失败后下次重新获取
This commit is contained in:
parent
ad7761810d
commit
e78d560f60
@ -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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user