方法增加
This commit is contained in:
parent
61439bf419
commit
95bad4cdfa
|
|
@ -54,5 +54,28 @@ namespace LY.App.Common.Redis
|
|||
{
|
||||
return await _db.KeyExistsAsync(key);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取数据,如果不存在则从数据源获取并存入 Redis
|
||||
/// </summary>
|
||||
/// <typeparam name="T">数据类型</typeparam>
|
||||
/// <param name="key">Redis Key</param>
|
||||
/// <param name="factory">数据源方法</param>
|
||||
/// <param name="expiry">可选的过期时间</param>
|
||||
/// <returns>获取到的值</returns>
|
||||
public async Task<T?> GetOrSetAsync<T>(string key, Func<Task<T>> factory, TimeSpan? expiry = null)
|
||||
{
|
||||
var value = await GetAsync<T>(key);
|
||||
if (value is not null)
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
value = await factory();
|
||||
if (value is not null)
|
||||
{
|
||||
await SetAsync(key, value, expiry);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue