zoukankan      html  css  js  c++  java
  • 持久化方式

    1.HttpContext.Items

    HttpContext抽象提供了一个简单的IDictionary<Object,Object>类型的字典集合,叫做Items。在每个请求中,这个集合从HttpRequest开始起就可以使用,直到请求结束后被丢弃。要存取集合,你可以直接给键赋值,或根据给定键查询值。

    举个例子,一个简单的中间件Middleware可以在Items集合中添加一些内容

      app.Use(async (context, next) =>
      {
             context.Items["key"] = "gouwa";
             await next.Invoke();
      });

      我们可以在这次请求中在这次中间件之后使用这个值。

     public IActionResult About()
    {
    
                ViewData["Message"] = HttpContext.Items["key"];
    
                return View();
     }

    2.HttpContext.Session

         ASP.NET.Core中的Session使用方法与.NET中有所不同,core中Session是一个单独组件,必须添加并配置。

        在项目中引用 Microsoft.AspNetCore.Session的程序包

    install-package  Microsoft.AspNetCore.Session

        然后在Startup类进行Session配置

        在ConfigureServices中添加Session服务

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSession();
    }

       然后再在Configure中添加Session中间件

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
         app.UseSession();
         app.UseMvc(routes =>
         {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
         });
    }

        注意:Session中间件必须添加在UseMvc()之前

       在ISession接口中,只有存储byte[]类型和读取byte[]类型方法

    public interface ISession
    {
      bool IsAvailable { get; }
      string Id { get; }
      IEnumerable<string> Keys { get; }
      Task LoadAsync();
      Task CommitAsync();
      bool TryGetValue(string key, out byte[] value);
      void Set(string key, byte[] value);
      void Remove(string key);
      void Clear();
      IEnumerable<string> Keys { get; }
    }

      当然由扩展方法可以在使用诸如String和Int32的简单类型时使用更加容易

    context.Session.SetInt32("key1", 123);
    int? val = context.Session.GetInt32("key1");
    context.Session.SetString("key2", "value");
    string stringVal = context.Session.GetString("key2");
    byte[] result = context.Session.Get("key3");

     如果要存储更复杂的对象,需要将对象序列化成一个byte[]字节流以便存储。

    3.Memory Caching

          使用Memory Caching必须也添加对应的组件

    Install-package Microsoft.Extensions.Caching.Memory

         在Startup类中ConfigureServices中添加服务

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

     然后我们就可以在程序中使用MemoryCache缓存了.

     public class HomeController : Controller
        {
            IMemoryCache _memoryCache;
            public HomeController(IMemoryCache memoryCache)
            {//使用注入
                _memoryCache = memoryCache;
            }
            public IActionResult Index()
            {
                //添加缓存
                _memoryCache.Set<String>("key", "val");
                //获取缓存
                _memoryCache.Get<String>("key");
    
                //设置相2分钟对过期时间
                _memoryCache.Set("key1", "val1", new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(2)));
                //设置绝对过期时间两分钟
                _memoryCache.Set("key2", "val2", new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(2)));
                //设置缓存优先级(程序压力大时,会根据优先级自动回收)
                _memoryCache.Set("key3", "val3", new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove));
                //缓存回调 10秒过期会回调
                _memoryCache.Set("key4", "val4", new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(10)).RegisterPostEvictionCallback((key, value, reason, subatate) => {
                    Console.WriteLine($"键{key}值{value}改变,因为{reason}");
                }));
                return View();
            }
    }
  • 相关阅读:
    97. Interleaving String (String; DP)
    140. Word Break II (String; DP,DFS)
    139. Word Break (String; DP)
    120. Triangle(Array; DP)
    132. Palindrome Partitioning II (String; DP)
    91. Decode Ways (Array; DP)
    45. Jump Game II (Array; Two-Pointers,Greedy)
    LeetCode Excel Sheet Column Number
    LeetCode Factorial Trailing Zeroes
    LeetCode SQL: Second Highest Salary
  • 原文地址:https://www.cnblogs.com/yan7/p/7839805.html
Copyright © 2011-2022 走看看