diff --git a/Common/Redis/RedisService.cs b/Common/Redis/RedisService.cs index 9fcde9a..dc7c8f4 100644 --- a/Common/Redis/RedisService.cs +++ b/Common/Redis/RedisService.cs @@ -54,5 +54,28 @@ namespace LY.App.Common.Redis { return await _db.KeyExistsAsync(key); } + /// + /// 获取数据,如果不存在则从数据源获取并存入 Redis + /// + /// 数据类型 + /// Redis Key + /// 数据源方法 + /// 可选的过期时间 + /// 获取到的值 + public async Task GetOrSetAsync(string key, Func> factory, TimeSpan? expiry = null) + { + var value = await GetAsync(key); + if (value is not null) + { + return value; + } + + value = await factory(); + if (value is not null) + { + await SetAsync(key, value, expiry); + } + return value; + } } }