From 95bad4cdfa3a6dba66659efeae19cb4cd014f937 Mon Sep 17 00:00:00 2001 From: yanghongwei Date: Wed, 26 Mar 2025 11:23:39 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B9=E6=B3=95=E5=A2=9E=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Common/Redis/RedisService.cs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) 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; + } } }