ASP.NET Core 中的缓存 / MemoryCache

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

学无止境,精益求精

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.使用

扫描二维码关注公众号,回复: 11392809 查看本文章

在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();
        }

未完待续...

猜你喜欢

转载自www.cnblogs.com/chenwolong/p/13210093.html