zoukankan      html  css  js  c++  java
  • .net Core学习笔记之MemoryCache

      .NET Core支持多种不同的缓存,其中包括MemoryCache,它表示存储在Web服务器内存中的缓存; 

       内存中的缓存存储任何对象; 分布式缓存界面仅限于byte[]

    1:在.net core中使用MemoryCache首先要下载MemoryCache包

         在程序包管理器控制台输入命令:Install-Package Microsoft.Extensions.Caching.Memory 

         之后可以看到已经下载好了NuGet包“Microsoft.Extensions.Caching.Memory

        使用IMemoryCache:内存中缓存是使用依赖注入从应用程序引用的服务,在Startup.cs中

     public void ConfigureServices(IServiceCollection services)
            {
                //使用依赖注入从应用程序引用服务
                services.AddMemoryCache();
                services.AddMvc();
            }

    IMemoryCache在构造函数中请求实例:

     //IMemoryCache在构造函数中请求实例
            private IMemoryCache _cache;
           // private object CacheKeys;
           
            public HomeController(IMemoryCache memoryCache)
            {
                _cache = memoryCache;
            }
    
            public IActionResult Index()
            {
                DateTime cacheEntry;
                string CacheKeys = "key";
                // 使用TryGetValue来检测时间是否在缓存中
                if (!_cache.TryGetValue(CacheKeys, out cacheEntry))
                {
                    //时间未被缓存,添加一个新条目
                    cacheEntry = DateTime.Now;
    
                    // 使用Set将其添加到缓存中
                    var cacheEntryOptions = new MemoryCacheEntryOptions()
                        // 在此期间保持高速缓存,如果被访问,则重新设置时间
                        .SetSlidingExpiration(TimeSpan.FromSeconds(3));
    
                    _cache.Set(cacheEntry, cacheEntry, cacheEntryOptions);
                }
    
                return View("Index", cacheEntry);
            }

    显示当前时间:缓存的DateTime值保留在高速缓存中,同时在超时期限内有请求(并且不因内存压力而驱逐)

    @model DateTime?
    
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css">
    <link rel="stylesheet" href="~/lib/font-awesome/css/font-awesome.css">
    
    <div>
        <h2>Actions</h2>
        <ul>
            <li><a asp-controller="Home" asp-action="CacheTryGetValueSet">TryGetValue and Set</a></li>
        </ul>
    </div>
    
    <h3>Current Time: @DateTime.Now.TimeOfDay.ToString()</h3>
    <h3>Cached Time: @(Model == null ? "No cached entry found" : Model.Value.TimeOfDay.ToString())</h3>

    缓存的DateTime值保留在高速缓存中,同时在超时期限内有请求(并且不因内存压力而驱逐)。下图显示了从缓存中检索的当前时间和较早的时间:

  • 相关阅读:
    15款精美的 WordPress 电子商务网站模板
    15套免费的扁平化界面设计素材【免费下载】
    35幅使用小图片组成的创意插图作品 【上篇】
    sqlserver2014两台不同服务器上数据库同步
    C++ Reflection Library
    美国的包容主要体现在接受移民,那么,中国的包容主要体现在哪里呢?答案就是资本
    mysql主从复制
    Kubernetes+Istio
    Net异步编程
    研发的困境----DEVOPS
  • 原文地址:https://www.cnblogs.com/lcq529/p/8547956.html
Copyright © 2011-2022 走看看