• ObjectCache 的使用 CQ


    Cache的获取及定义

    Cache的获取代码:

    var cache = CacheManager.Instance.GetCache<KeyType, ValueType>();

    因此对Cache的定义,实际上就是对KeyType和ValueType的定义,例如:

    class Key :IEquatable<Key>
    
    {
    
    public string Id{get;set;}
    
    public bool Equals(Key other)
    
    {
    
       if(other == null)
    
          return false;
    
       return Id == other.Id;
    
    }
    
    
    
    class BusinessObj
    
    {
    
           /* property definitions*/
    
    }
    
    

    有了以上两个类型,我们就可以用来创建/获取cache了。

    var cache = CacheManager.Instance.GetCache<Key, BusinessObj>();

    Cache的作用范围

    由于Cache的定义实际上是通过强类型来定义的,如上面的代码GetCache<Key, BusinessObj>()。因此Cache的作用范围等同于上面定义的类型Key和BusinessObj的作用范围。

    Cache生命周期的管理

    Cache生命周期的管理问题实际上就是控制cache的内容在何时失效。

    有以下两种方式来控制cache内容何时失效,cache的内容一旦失效,它就会被从内存中移除

    1. 可以通过继承BaseToken来管理

    2. 直接调用ICache上的Reset()方法来清空Cache中的所有内容

    3. 直接调用ICache上的Remove()方法来指定移除某一个CacheItem

    Cache的分组

    对Cache分组的目的是,我们可以对同一组别的Cache进行清空处理。Cache的分组信息通过特性定义在Cache的Key上面。请参见以下代码:

    [CacheKeyCategory(2)]
            class CackeKey2 : IEquatable<CackeKey2>
            {
                public long Id { get; set; }
                #region IEquatable<CacheKey> Members
    
                public bool Equals(CackeKey2 other)
                {
                    return Id == other.Id;
                }
    
                #endregion
            }

    我们可以通过如下单元测试来看清楚其作用

    [TestMethod]
            public void CacheCategory_Category_Test()
            {
                var cache = CacheManager.Instance.GetCache<CackeKey2, string>();
                cache.GetWithCreate(new CackeKey2 { Id = 1 }, () => "Hello", new BaseToken());
    
                Assert.AreEqual(1, cache.Count());
    
                CacheManager.Instance.ResetCaches(4);
    
                Assert.AreEqual(1, cache.Count());
    
                CacheManager.Instance.ResetCaches(2);
    
                Assert.AreEqual(0, cache.Count());
            }
    当CacheManager.Instance.ResetCaches(4)被调用时,Cache<CacheKey2,string>中的内容并没有被清空。当

    CacheManager.Instance.ResetCaches(2)被调用时,Cache<CacheKey2,string>中的内容才被清空。

    如果Cache的key没有添加分组信息,那么只有当CacheManager.Instance.ResetCaches(0);被调用时,Cache中的内容才会被清空,且实际上,这是所有的缓存都会被清空。

  • 相关阅读:
    基于centos的freeradius高可用lvs(UDP)
    sql server 2012的AlwaysOn高可用
    python基础题型一
    用户访一个APP或者网页流程示意图
    DNS解析流程
    crontab的定时任务实例
    Xcode设置
    Nvidia Nsight + .NET
    C++ Pointer-to-Member Selector
    C++11
  • 原文地址:https://www.cnblogs.com/czy/p/2318150.html
Copyright © 2020-2023  润新知