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

  • 相关阅读:
    携程机票实时数据处理实践及应用
    关系型数据库表设计
    tornado
    Poisson distribution 泊松分布 指数分布
    Interpret bytes as packed binary data
    python爬虫爬取内容中,-xa0,-u3000的含义
    Okapi BM25 (BM stands for Best Matching)
    一主
    分片 副本
    暂时无法提交申请 帐号类型修改
  • 原文地址:https://www.cnblogs.com/lcq529/p/8547956.html
Copyright © 2011-2022 走看看