zoukankan      html  css  js  c++  java
  • Asp.Net MVC 缓存设计

    Asp.Net MVC 缓存:

    1. 可以直接在Controller,Action上面定义输出缓存OutputCache,如下,第一次请求这个Index的时候,里面的代码会执行,并且结果会被缓存起来,然后在30秒钟内,第二个或者后续的请求,就不需要再次执行,而是直接将结果返回给用户即可

            [OutputCache(Duration = 30,VaryByParam="none")]
            public ActionResult Index(string name)
            {
                return View();
            }

    OutputCache Attribute既可以作用于Action上,也可以作用于Controller.  

    VaryByParam为none,表示不管参数如何变化,30s内都缓存,如果VaryByParam设置为name, 那下次访问如果name变化,则缓存失效,生成新的缓存页。

    如果您不想要为不同的已缓存内容指定参数,可以将其设置为none。如果想要指定所有的已缓存内容参数,可以设置为*

    其中除了VaryByParam,还可以做如下的配置,(所有的配置:以分号分隔的字符串列表)

    VaryByContentEncoding 获取或设置基于内容变化的编码。
    公共属性 VaryByCustom 获取或设置基于自定义项变化的值。
    公共属性 VaryByHeader 获取或设置基于标头变化的值。
    公共属性 VaryByParam 获取或设置基于参数变化的值。

    2. 支持通过CacheProfile的方式,灵活定义缓存的设置(新功能)

     <system.web> 
        <caching> 
          <outputCacheSettings> 
            <outputCacheProfiles> 
              <add  name="faceProfile" duration ="180"  varyByParam="none" enabled="true"/> 
            </outputCacheProfiles> 
          </outputCacheSettings> 
        </caching> 
    <system.web>
      [OutputCache(CacheProfile = "faceProfile")] 
        public ActionResult Index() 
        { 
            return View(); 
        } 

    3. .Net提供了一个缓存对象Cache,我们可以使用 HttpRuntime.Cache来使用。(web程序可以使用 HttpContext.Cache )

      //
        // 摘要:
        //     提供了一组的当前应用程序的 ASP.NET 运行时服务。
        public sealed class HttpRuntime
        {
    
            //
            // 摘要:
            //     获取 System.Web.Caching.Cache 当前应用程序。
            //
            // 返回结果:
            //     当前的 System.Web.Caching.Cache。
            //
            // 异常:
            //   T:System.Web.HttpException:
            //     未安装 ASP.NET。
            public static Cache Cache { get; }
           
        }

    我们查看HttpRuntime的接口发现,这个属性是静态的,在.net中静态的属性,我们可以得出这个属性为线程安全的,这很好的解决多线程环境中并发的问题。

    具体的操作:

    添加缓存

            public static void SetCache(string key, object obj)
            {
                Cache cache = HttpRuntime.Cache;
                cache.Insert(key, obj);
            }
    
            public static void SetCache(string key, object obj, TimeSpan Timeout)
            {
                Cache cache = HttpRuntime.Cache;
                cache.Insert(key, obj, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
            }
    
            public static void SetCache(string key, object obj, DateTime absoluteExpiration, TimeSpan slidingExpiration)
            {
                Cache cache = HttpRuntime.Cache;
    cache.Insert(key, obj, null, absoluteExpiration, slidingExpiration); }

    absoluteExpiration:用于设置绝对过期时间,它表示只要时间一到就过期,所以类型为System.DateTime,当给这个参数设置了一个时间时,slidingExpiration参数的值就只能为Cache.NoSlidingExpiration,否则出错;
    slidingExpiration:用于设置可调过期时间,它表示当离最后访问超过某个时间段后就过期,所以类型为System.TimeSpan,当给这个参数设置了一个时间段时,absoluteExpiration的值就只能为Cache.NoAbsoluteExpiration,否则出错;

    获取缓存信息:

            public T Get<T>(string key)
            {
                return (T)HttpRuntime.Cache[key];
            }
    
            public static object Get(string key)
            {
                return HttpRuntime.Cache[key];
            }

    移除缓存

            public static void Remove(string key)
            {
                HttpRuntime.Cache.Remove(key);
            }
            public void Clear()
            {
                IDictionaryEnumerator enumerator = HttpRuntime.Cache.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    HttpRuntime.Cache.Remove(enumerator.Key.ToString());
                }
            }

    缓存依赖项:文件依赖,其他缓存依赖,数据库依赖,当依赖项发生改变时,缓存会失效,并可以引发一定事件。

                CacheDependency fileDepends = new CacheDependency(Server.MapPath("config.json"));
                HttpRuntime.Cache.Insert(key, obj, fileDepends);

     MemoryCache 

       类似于 ASP.NET Cache 类。 MemoryCache 类有许多用于访问缓存的属性和方法。

       Cache 和 MemoryCache 类之间的主要区别是:

    1. MemoryCache 已被更改,以便 .NET Framework 应用程序(非 ASP.NET 应用程序)可以使用该类。 例如,MemoryCache 类对 System.Web 程序集没有依赖关系。

    2. 可以创建 MemoryCache 类的多个实例,以用于相同的应用程序和相同的 AppDomain 实例

    关于MemoryCache的用法,推荐看下abp框架中对MemoryCache的使用

    github: https://github.com/aspnetboilerplate/aspnetboilerplate

    同时,也可以看博客园里有园友对abp框架对缓存源码的解析。

    根据ABP的代码,我整理了一个简单的memroycache使用方法

     public class AbpMemoryCache
        {
            private MemoryCache _memoryCache;
    
            public TimeSpan DefaultSlidingExpireTime { get; set; }
    
    
            public AbpMemoryCache()
            {
                _memoryCache = new MemoryCache(new OptionsWrapper<MemoryCacheOptions>(new MemoryCacheOptions()));
                DefaultSlidingExpireTime = TimeSpan.FromHours(1);
            }
    
            public object GetOrDefault(string key)
            {
                return _memoryCache.Get(key);
            }
    
            public void Set(string key, object value)
            {
                _memoryCache.Set(key, value, DefaultSlidingExpireTime);
            }
    
    
            public void Remove(string key)
            {
                _memoryCache.Remove(key);
            }
    
            public void Clear()
            {
                _memoryCache.Dispose();
                _memoryCache = new MemoryCache(new OptionsWrapper<MemoryCacheOptions>(new MemoryCacheOptions()));
            }
    
            public void Dispose()
            {
                _memoryCache.Dispose();
            }
        }
  • 相关阅读:
    不可小视视图对效率的影响力
    Maximum Margin Planning
    PhysicsBased Boiling Simulation

    Learning Behavior Styles with Inverse Reinforcement Learning
    Simulating Biped Behaviors from Human Motion Data
    Nearoptimal Character Animation with Continuous Control
    Apprenticeship Learning via Inverse Reinforcement Learning
    回报函数学习的学徒学习综述
    Enabling Realtime Physics Simulation in Future Interactive Entertainment
  • 原文地址:https://www.cnblogs.com/hankuikui/p/7072698.html
Copyright © 2011-2022 走看看