首页 > 编程语言 >ASP .NET Core 缓存

ASP .NET Core 缓存

时间:2022-11-24 00:11:20浏览次数:41  
标签:Core ASP Redis System 缓存 key distributedCache NET options

缓存可以通过减少生成内容所需的工作,显著提高应用的性能和可伸缩性。 缓存最适用于不常更改且生成成本很高的数据。 缓存生成的数据副本可以比从源中更快地返回。 应该以从不依赖于缓存数据的方式编写和测试应用。ASP.NET Core 支持多个不同的缓存。

本文主要介绍三种缓存方式

缓存类别 Nuget
Memory内存 Microsoft.Extensions.Caching.Memory
SqlServer Microsoft.Extensions.Caching.SqlServer
Redis Microsoft.Extensions.Caching.StackExchangeRedis

添加缓存服务

Memory

        //分布式
        services.AddDistributedMemoryCache();
        //非分布式
        //services.AddMemoryCache();

Redis

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = "192.168.1.105:6379,password=1qaz@WSX3edc$RFV,ssl=False,abortConnect=False";
                options.InstanceName = "App-Instance-Keys";
            });

            services.AddStackExchangeRedisCache(options =>
            {
                options.ConfigurationOptions = new StackExchange.Redis.ConfigurationOptions()
                {
                    Password = "1qaz@WSX3edc$RFV",
                    ConnectTimeout = 5000,//设置建立连接到Redis服务器的超时时间为5000毫秒
                    SyncTimeout = 5000,//设置对Redis服务器进行同步操作的超时时间为5000毫秒
                    ResponseTimeout = 5000,//设置对Redis服务器进行操作的响应超时时间为5000毫秒
                    Ssl = false,//设置启用SSL安全加密传输Redis数据
                    //SslHost=""
                    //SslProtocols = System.Security.Authentication.SslProtocols.Tls//还可以通过SslProtocols属性指定SSL具体用到的是什么协议,不过这个属性不是必须的
                };

                options.ConfigurationOptions.EndPoints.Add("192.168.1.105:6379");
                options.InstanceName = "App-Instance-Keys";
            });

SqlServer

        services.AddDistributedSqlServerCache(options =>
        {
            options.SchemaName = "dbo";
            options.ConnectionString = Configuration["SqlServerConnection"];
            //会创建一个外部表
            options.TableName = "AppCache";
            //默认缓存时间
            options.DefaultSlidingExpiration = TimeSpan.FromMinutes(20);
            //过时自动删除
            options.ExpiredItemsDeletionInterval = TimeSpan.FromMinutes(30);
        });

使用缓存

DistributedCacheEntryOptions是设置缓存时间的配置类

        //设置十分钟后过期
        new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(10));

        //设置以当前时间为例,十分钟后过期
        new DistributedCacheEntryOptions().SetAbsoluteExpiration(DateTimeOffset.Now.AddMinutes(10));

        new DistributedCacheEntryOptions {
            //设置未来某一个时间过期
            AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(10),
            //设置以当前时间为例,过过长时间过期,案例为10分钟
            //AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
        };

设置缓存

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Threading.Tasks;

namespace MicrosoftCache.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class RedisController : ControllerBase
    {
        private readonly IDistributedCache _distributedCache;

        public RedisController(IDistributedCache distributedCache)
        {
            _distributedCache = distributedCache;
        }

        [HttpGet]
        public async Task Get()
        {
            //设置十分钟后过期
           var dco=  new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(10));

            string key = "demokey";

            //添加/修改缓存时间
            _distributedCache.SetString(key, "123456", dco);

            //异步缓存
            await _distributedCache.SetStringAsync("demokeyAsync", "123456", dco);

            //获取缓存数据
            var getvlaue = _distributedCache.GetString(key);


            //刷新
            _distributedCache.Refresh(key);

            //删除
            _distributedCache.Remove(key);


            object value = new { id=1,user = "zs" };

            var stringObject = System.Text.Json.JsonSerializer.Serialize(value, new System.Text.Json.JsonSerializerOptions
            {
                //.Net6+
                ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles
            });

            var bytesObject = System.Text.Encoding.UTF8.GetBytes(stringObject);//将Json字符串通过UTF-8编码,序列化为字节数组

            //设置byte 缓存
            _distributedCache.Set(key, bytesObject, dco);
            //刷新Redis
            _distributedCache.Refresh(key);



            //获取byte 缓存数据
            var bytesGetObject = _distributedCache.Get(key);
            var stringGetObject = System.Text.Encoding.UTF8.GetString(bytesGetObject);//通过UTF-8编码,将字节数组反序列化为Json字符串
            var bytevlaue = System.Text.Json.JsonSerializer.Deserialize<object>(stringGetObject);
        }
    }
}

缓存帮助类

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

namespace MicrosoftCache
{
    /// <summary>
    /// Cache缓存操作类
    /// </summary>
    public class CacheHelper
    {
        protected IDistributedCache cache;

        /// <summary>
        /// 通过IDistributedCache来构造RedisCache缓存操作类
        /// </summary>
        /// <param name="cache">IDistributedCache对象</param>
        public CacheHelper(IDistributedCache cache)
        {
            this.cache = cache;
        }

        /// <summary>
        /// 添加或更改Redis的键值,并设置缓存的过期策略
        /// </summary>
        /// <param name="key">缓存键</param>
        /// <param name="value">缓存值</param>
        /// <param name="distributedCacheEntryOptions">设置Redis缓存的过期策略</param>
        public void Set(string key, object value, DistributedCacheEntryOptions distributedCacheEntryOptions)
        {
            var stringObject = JsonSerializer.Serialize(value, new JsonSerializerOptions
            {
                ReferenceHandler = ReferenceHandler.IgnoreCycles
            });

            var bytesObject = Encoding.UTF8.GetBytes(stringObject);//将Json字符串通过UTF-8编码,序列化为字节数组

            cache.Set(key, bytesObject, distributedCacheEntryOptions);
            Refresh(key);//刷新Redis
        }

        /// <summary>
        /// 查询键值是否在Redis中存在
        /// </summary>
        /// <param name="key">缓存键</param>
        /// <returns>true:存在,false:不存在</returns>
        public bool Exist(string key) => cache.Get(key) != null;


        /// <summary>
        /// Redis中获取键值
        /// </summary>
        /// <typeparam name="T">缓存的类型</typeparam>
        /// <param name="key">缓存键</param>
        /// <param name="isExisted">是否获取到键值,true:获取到了,false:键值不存在</param>
        /// <returns>缓存的对象</returns>
        public T Get<T>(string key, out bool isExisted)
        {
            var bytesObject = cache.Get(key);//从Redis中获取键值key的字节数组,如果没获取到,那么会返回null

            if (bytesObject == null)
            {
                isExisted = false;
                return default(T);
            }

            var stringObject = Encoding.UTF8.GetString(bytesObject);//通过UTF-8编码,将字节数组反序列化为Json字符串

            isExisted = true;
            return JsonSerializer.Deserialize<T>(stringObject);
        }

        /// <summary>
        /// Redis中删除键值
        /// </summary>
        /// <param name="key">缓存键</param>
        public void Remove(string key)=> cache.Remove(key);
        

        /// <summary>
        /// 从Redis中刷新键值
        /// </summary>
        /// <param name="key">缓存键</param>
        public void Refresh(string key)=>  cache.Refresh(key);
        
    }
}

标签:Core,ASP,Redis,System,缓存,key,distributedCache,NET,options
From: https://www.cnblogs.com/RainFate/p/16920591.html

相关文章