学海无涯

导航

关于Redis分布式缓存 IDistributedCache 的工具类

通过NuGet 安装 Microsoft.Extensions.Caching.StackExchangeRedis 组件

在 Program.cs 的 builder.Build() 之前注册 IDistributedCache 服务

string redisConnection = builder.Configuration.GetConnectionString("RedisConnection");
//注册分布式Redis
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = redisConnection;
    options.InstanceName = "yzk_";
});

  appsetting.json配置文件

"ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-DABHN6U\\MSSQLSERVER2014;uid=sa;pwd=Lz38275292;database=NewAps;MultipleActiveResultSets=true;",
    "RedisConnection": "127.0.0.1:6379"

  }

  工具类接口

using Microsoft.AspNetCore.Routing.Template;
using Microsoft.Extensions.Caching.Distributed;

namespace TestWebApplication.Utility
{
    public interface IDistributedCacheHelper
    {
        TResult? GetOrCreate<TResult>(string cacheKey, Func<DistributedCacheEntryOptions, TResult?> valueFactory, int expireSeconds = 60);
        Task<TResult?> GetOrCreateAsync<TResult>(string cacheKey, Func<DistributedCacheEntryOptions, Task<TResult?>> valueFactory, int expireSeconds);
        void Remove(string cacheKey);
        Task RemoveAsync(string cacheKey);
    }
}

  工具类实现

using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;

namespace TestWebApplication.Utility
{
    /// <summary>
    /// 分布式Redis的IDistributedCache工具类
    /// </summary>
    public class DistributedCacheHelper : IDistributedCacheHelper
    {
        private readonly IDistributedCache m_Cache;
        public DistributedCacheHelper(IDistributedCache cache)
        {
            m_Cache = cache;
        }
        private static DistributedCacheEntryOptions CreateOptions(int baseExpireSeconds)
        {
            double sec = Random.Shared.Next(baseExpireSeconds, baseExpireSeconds * 2);
            TimeSpan expiration = TimeSpan.FromSeconds(sec);
            var options = new DistributedCacheEntryOptions();
            options.AbsoluteExpirationRelativeToNow = expiration;
            return options;
        }
        public TResult? GetOrCreate<TResult>(string cacheKey, Func<DistributedCacheEntryOptions, TResult?> valueFactory, int expireSeconds = 60)
        {
            throw new NotImplementedException();
        }

        public async Task<TResult?> GetOrCreateAsync<TResult>(string cacheKey, Func<DistributedCacheEntryOptions, Task<TResult?>> valueFactory, int expireSeconds)
        {
            string jsonStr = await m_Cache.GetStringAsync(cacheKey);
            if (string.IsNullOrEmpty(jsonStr))
            {
                var options = CreateOptions(expireSeconds);
                TResult? result = await valueFactory(options);
                string jsonOfResult = JsonSerializer.Serialize(result, typeof(TResult));
                await m_Cache.SetStringAsync(cacheKey, jsonOfResult, options);
                return result;
            }
            else
            {
                await m_Cache.RefreshAsync(cacheKey);
                return JsonSerializer.Deserialize<TResult>(jsonStr);
            }
        }

        public void Remove(string cacheKey)
        {
            m_Cache.Remove(cacheKey);
        }

        public async Task RemoveAsync(string cacheKey)
        {
            await m_Cache.RemoveAsync(cacheKey);
        }
    }
}

  客户端调用

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using TestWebApplication.Utility;

namespace TestWebApplication.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class Test1Controller : ControllerBase
    {//分布式Redis
        private readonly ILogger<Test1Controller> _logger;
        private readonly IDistributedCacheHelper _distributedCache;
        public Test1Controller(ILogger<Test1Controller> logger, IDistributedCacheHelper distributedCache)
        {
            _logger = logger;
            _distributedCache = distributedCache;
        }
        [HttpGet]
        public async Task<string> Now()
        {
            string KEY = "Now";
            string? s = String.Empty;
            s = await _distributedCache.GetOrCreateAsync(KEY, async (e) =>
            {
                return DateTime.Now.ToString();
            }, 60);
            return s;
        }

    }
}

  

 

posted on 2022-09-16 10:36  宁静致远.  阅读(177)  评论(0编辑  收藏  举报