十年河东,十年河西,莫欺少年穷

学无止境,精益求精

ASP.NET Core 缓存Caching,.NET Core 中为我们提供了Caching 的组件。

目前Caching 组件提供了三种存储方式。

Memory

Redis

SqlServer

学习在ASP.NET Core 中使用Caching。

Memory Caching

1.新建一个 ASP.NET Core 项目,选择Web 应用程序,将身份验证 改为 不进行身份验证。

2.添加引用

Install-Package Microsoft.Extensions.Caching.Memory

3.使用

在Startup.cs 中 ConfigureServices

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMemoryCache();
            // Add framework services.
            services.AddMvc();            
        }

然后在控制器中依赖注入、

        private IMemoryCache _cache;

        public LongLongController(IMemoryCache memoryCache)
        {
            _cache = memoryCache;
        }

1、方法:TryGetValue 及 方法缓存的存取

        public IActionResult Index()
        {
            string cacheKey_2 = "CacheKey";
            List<string> cacheEntry;
            //如果缓存没有过期,则Out测试就是缓存存储的值,注意存放值的类型应该和Out参数一致。
            var bol = _cache.TryGetValue<List<string>>(cacheKey_2, out cacheEntry);
            //判断缓存是否存在
            if (!bol)
            {
                List<string> lst = new List<string>() { "陈大六", "陈卧龙", "陈新宇", "刘丽", "花国锋" };
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                 .SetSlidingExpiration(TimeSpan.FromMinutes(10));
                _cache.Set(cacheKey_2, lst, cacheEntryOptions);
            }
            ViewBag.cacheEntry = _cache.Get(cacheKey_2);
            return View();
        }

在TryGetValue 中,Out 参数的类型应与缓存中存储的值的类型一致。否则TryGetValue 中的Out参数永远为NULL。

2、设置缓存的过期时间,可采用绝对过期时间或相对过期时间两种模式;

相对过期时间设置方式:

var cacheEntryOptions = new MemoryCacheEntryOptions()
                 .SetSlidingExpiration(TimeSpan.FromSeconds(10));

代码如下:

        /// <summary>
        /// 相对过期时间十秒 如果:十秒内不间断有人访问,那么在访问期间缓存不会消失。除非前后访问时间大于十秒,缓存会消失
        /// </summary>
        /// <returns></returns>
        public IActionResult Slid()
        {
            string cacheKey_2 = "SlidCache";
            List<string> cacheEntry;
            var bol = _cache.TryGetValue<List<string>>(cacheKey_2, out cacheEntry);
            //判断缓存是否存在
            if (!bol)
            {
                List<string> lst = new List<string>() { "陈大六", "陈卧龙", "陈新宇", "刘丽", "花国锋" };
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                 .SetSlidingExpiration(TimeSpan.FromSeconds(10));
                _cache.Set(cacheKey_2, lst, cacheEntryOptions);
            }
            ViewBag.cacheEntry = _cache.Get(cacheKey_2);
            return View();
        }
View Code

相关文章:

  • 2022-12-23
  • 2018-08-14
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2018-03-09
  • 2022-12-23
猜你喜欢
  • 2021-08-23
  • 2021-09-22
  • 2021-09-28
  • 2022-12-23
  • 2020-07-22
  • 2022-12-23
相关资源
相似解决方案