从 Redis 检索多个密钥时出现死锁
本文关键字:死锁 密钥 Redis 检索 | 更新日期: 2023-09-27 17:56:14
我正在尝试将此查询的结果并行获取到 redis(使用 stackexchange C# 客户端),但不知何故我在死锁中运行,不确定在哪里
检索数据的方法:
public LiveData Get(string sessionId)
{
return GetAsync(sessionId).Result;
}
private async Task<LiveData> GetAsync(string sessionId)
{
var basketTask = GetBasketAsync(sessionId);
var historyTask = GetHistoryAsync(sessionId);
var capturedDataTask = GetCapturedDataAsync(sessionId);
var basket = await basketTask;
var history = await historyTask;
var capturedData = await capturedDataTask;
return new LiveData
{
Basket = basket.IsNullOrEmpty
? new List<Product>()
: JsonConvert.DeserializeObject<List<Product>>(basket),
History = history.Select(cachedProduct
=> JsonConvert.DeserializeObject<Product>(cachedProduct.Value.ToString())).ToList(),
CapturedData = capturedData.ToDictionary<HashEntry, string, object>(
hash => hash.Name, hash => JsonConvert.DeserializeObject(hash.Value))
};
}
从 redis 获取缓存数据的方法是:
private async Task<RedisValue> GetBasketAsync(string key)
{
key = $"{key}{BasketSuffix}";
var redisDb = RedisConnection.Connection.GetDatabase();
redisDb.KeyExpireAsync(key, _expire);
return await redisDb.StringGetAsync(key);
}
private async Task<HashEntry[]> GetHistoryAsync(string key)
{
key = $"{key}{HistorySuffix}";
var redisDb = RedisConnection.Connection.GetDatabase();
redisDb.KeyExpireAsync(key, _expire);
return await redisDb.HashGetAllAsync(key);
}
private async Task<HashEntry[]> GetCapturedDataAsync(string key)
{
key = $"{key}{CapturedDataSuffix}";
var redisDb = RedisConnection.Connection.GetDatabase();
redisDb.KeyExpireAsync(key, _expire);
return await redisDb.HashGetAllAsync(key);
}
我认为像这样调用 KeyExpireAsync 很好,只是因为触发和忘记很好,但不确定这是否相关(我什至尝试删除它,但它仍然被阻止)
死锁的来源是以下代码片段:
public LiveData Get(string sessionId)
{
return GetAsync(sessionId).Result;
}
相反,请以正确的方式"一路异步"调用它:
public async Task<LiveData> Get(string sessionId)
{
return await GetAsync(sessionId);
}
调用.Result
可能会导致死锁,使用 .Wait()
API 也是如此。此外,从外观上看 - .KeyExpireAsync
需要等待。
async Task<RedisValue> GetBasketAsync(string key)
{
key = $"{key}{BasketSuffix}";
var redisDb = RedisConnection.Connection.GetDatabase();
await redisDb.KeyExpireAsync(key, _expire);
return await redisDb.StringGetAsync(key);
}
我理解您在.KeyExpireAsync
调用中不使用 await
关键字的思考过程,但如果我正在编写此代码,我肯定会像我演示的那样await
它。是一劳永逸的代码气味,很容易避免。