2012-01-25 72 views
11

我需要添加缓存功能,并找到一个名为MemoryCache的新闪亮类。但是,我发现MemoryCache有点残缺(我需要区域功能)。除了其他的事情,我需要添加一些像ClearAll(区域)。作者做了很大的努力,以保持这个类没有地区的支持,代码如:支持区域的MemoryCache?

if (regionName != null) 
{ 
throw new NotSupportedException(R.RegionName_not_supported); 
} 

几乎在每种方法中飞行。 我看不到一个简单的方法来覆盖此行为。我能想到的添加区域支持的唯一方法是将一个新类添加为MemoryCache的包装,而不是作为从MemoryCache继承的类。然后在这个新类中创建一个Dictionary,并让每个方法调用“buffer”区域。听起来讨厌和错误,但最终...

你知道更好的方法来添加区域到MemoryCache?

回答

5

您可以为数据的每个分区创建一个以上的一个MemoryCache实例。

http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx

您可以创建使用MemoryCache类的多个实例在同一个应用程序,并在相同的AppDomain实例

+0

这里是实例所有这些新的MemoryCache实例最好的地方?有没有可以管理所有这些实例的MemoryCache提供程序? –

+0

@HenleyChiu我不认为基础库中有任何东西。只需使用标准的分享状态手段,如静态全局可见[ConcurrentDictionary ](http://msdn.microsoft.com/zh-cn/library/dd287191.aspx) –

+2

使用多个“MemoryCache”实例可能会降低某些缓存的有效性情况。请参阅:http://stackoverflow.com/questions/8463962/using-multiple-instances-of-memorycache – Nathan

9

我知道这是一个很长的时间,因为你问这个问题,所以这不是真正的答案,而是未来读者的补充。

我还惊讶地发现MemoryCache的标准实现不支持区域。马上就可以很容易地提供。因此,我决定将MemoryCache包装在我自己的简单类中,以提供我经常需要的功能。

我把我的代码放在这里,以节省时间为其他人有相同的需要!

/// <summary> 
/// ================================================================================================================= 
/// This is a static encapsulation of the Framework provided MemoryCache to make it easier to use. 
/// - Keys can be of any type, not just strings. 
/// - A typed Get method is provided for the common case where type of retrieved item actually is known. 
/// - Exists method is provided. 
/// - Except for the Set method with custom policy, some specific Set methods are also provided for convenience. 
/// - One SetAbsolute method with remove callback is provided as an example. 
/// The Set method can also be used for custom remove/update monitoring. 
/// - Domain (or "region") functionality missing in default MemoryCache is provided. 
/// This is very useful when adding items with identical keys but belonging to different domains. 
/// Example: "Customer" with Id=1, and "Product" with Id=1 
/// ================================================================================================================= 
/// </summary> 
public static class MyCache 
{ 
    private const string KeySeparator = "_"; 
    private const string DefaultDomain = "DefaultDomain"; 


    private static MemoryCache Cache 
    { 
     get { return MemoryCache.Default; } 
    } 

    // ----------------------------------------------------------------------------------------------------------------------------- 
    // The default instance of the MemoryCache is used. 
    // Memory usage can be configured in standard config file. 
    // ----------------------------------------------------------------------------------------------------------------------------- 
    // cacheMemoryLimitMegabytes: The amount of maximum memory size to be used. Specified in megabytes. 
    //        The default is zero, which indicates that the MemoryCache instance manages its own memory 
    //        based on the amount of memory that is installed on the computer. 
    // physicalMemoryPercentage: The percentage of physical memory that the cache can use. It is specified as an integer value from 1 to 100. 
    //        The default is zero, which indicates that the MemoryCache instance manages its own memory 
    //        based on the amount of memory that is installed on the computer. 
    // pollingInterval:    The time interval after which the cache implementation compares the current memory load with the 
    //        absolute and percentage-based memory limits that are set for the cache instance. 
    //        The default is two minutes. 
    // ----------------------------------------------------------------------------------------------------------------------------- 
    // <configuration> 
    // <system.runtime.caching> 
    //  <memoryCache> 
    //  <namedCaches> 
    //   <add name="default" cacheMemoryLimitMegabytes="0" physicalMemoryPercentage="0" pollingInterval="00:02:00" /> 
    //  </namedCaches> 
    //  </memoryCache> 
    // </system.runtime.caching> 
    // </configuration> 
    // ----------------------------------------------------------------------------------------------------------------------------- 



    /// <summary> 
    /// Store an object and let it stay in cache until manually removed. 
    /// </summary> 
    public static void SetPermanent(string key, object data, string domain = null) 
    { 
     CacheItemPolicy policy = new CacheItemPolicy { }; 
     Set(key, data, policy, domain); 
    } 

    /// <summary> 
    /// Store an object and let it stay in cache x minutes from write. 
    /// </summary> 
    public static void SetAbsolute(string key, object data, double minutes, string domain = null) 
    { 
     CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(minutes) }; 
     Set(key, data, policy, domain); 
    } 

    /// <summary> 
    /// Store an object and let it stay in cache x minutes from write. 
    /// callback is a method to be triggered when item is removed 
    /// </summary> 
    public static void SetAbsolute(string key, object data, double minutes, CacheEntryRemovedCallback callback, string domain = null) 
    { 
     CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(minutes), RemovedCallback = callback }; 
     Set(key, data, policy, domain); 
    } 

    /// <summary> 
    /// Store an object and let it stay in cache x minutes from last write or read. 
    /// </summary> 
    public static void SetSliding(object key, object data, double minutes, string domain = null) 
    { 
     CacheItemPolicy policy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(minutes) }; 
     Set(key, data, policy, domain); 
    } 

    /// <summary> 
    /// Store an item and let it stay in cache according to specified policy. 
    /// </summary> 
    /// <param name="key">Key within specified domain</param> 
    /// <param name="data">Object to store</param> 
    /// <param name="policy">CacheItemPolicy</param> 
    /// <param name="domain">NULL will fallback to default domain</param> 
    public static void Set(object key, object data, CacheItemPolicy policy, string domain = null) 
    { 
     Cache.Add(CombinedKey(key, domain), data, policy); 
    } 




    /// <summary> 
    /// Get typed item from cache. 
    /// </summary> 
    /// <param name="key">Key within specified domain</param> 
    /// <param name="domain">NULL will fallback to default domain</param> 
    public static T Get<T>(object key, string domain = null) 
    { 
     return (T)Get(key, domain); 
    } 

    /// <summary> 
    /// Get item from cache. 
    /// </summary> 
    /// <param name="key">Key within specified domain</param> 
    /// <param name="domain">NULL will fallback to default domain</param> 
    public static object Get(object key, string domain = null) 
    { 
     return Cache.Get(CombinedKey(key, domain)); 
    } 

    /// <summary> 
    /// Check if item exists in cache. 
    /// </summary> 
    /// <param name="key">Key within specified domain</param> 
    /// <param name="domain">NULL will fallback to default domain</param> 
    public static bool Exists(object key, string domain = null) 
    { 
     return Cache[CombinedKey(key, domain)] != null; 
    } 

    /// <summary> 
    /// Remove item from cache. 
    /// </summary> 
    /// <param name="key">Key within specified domain</param> 
    /// <param name="domain">NULL will fallback to default domain</param> 
    public static void Remove(object key, string domain = null) 
    { 
     Cache.Remove(CombinedKey(key, domain)); 
    } 



    #region Support Methods 

    /// <summary> 
    /// Parse domain from combinedKey. 
    /// This method is exposed publicly because it can be useful in callback methods. 
    /// The key property of the callback argument will in our case be the combinedKey. 
    /// To be interpreted, it needs to be split into domain and key with these parse methods. 
    /// </summary> 
    public static string ParseDomain(string combinedKey) 
    { 
     return combinedKey.Substring(0, combinedKey.IndexOf(KeySeparator)); 
    } 

    /// <summary> 
    /// Parse key from combinedKey. 
    /// This method is exposed publicly because it can be useful in callback methods. 
    /// The key property of the callback argument will in our case be the combinedKey. 
    /// To be interpreted, it needs to be split into domain and key with these parse methods. 
    /// </summary> 
    public static string ParseKey(string combinedKey) 
    { 
     return combinedKey.Substring(combinedKey.IndexOf(KeySeparator) + KeySeparator.Length); 
    } 

    /// <summary> 
    /// Create a combined key from given values. 
    /// The combined key is used when storing and retrieving from the inner MemoryCache instance. 
    /// Example: Product_76 
    /// </summary> 
    /// <param name="key">Key within specified domain</param> 
    /// <param name="domain">NULL will fallback to default domain</param> 
    private static string CombinedKey(object key, string domain) 
    { 
     return string.Format("{0}{1}{2}", string.IsNullOrEmpty(domain) ? DefaultDomain : domain, KeySeparator, key); 
    } 

    #endregion 

} 
+1

通过MemoryCache枚举效率低下,因为它会锁定整个缓存的时间。此外,您的Clear()是线性搜索,因此线性缓存项的数量会变得更糟。这是一个更好的解决方案:http://stackoverflow.com/a/22388943/220230 – Piedone

+0

感谢您观察此。在给定的简单例子中,我现在删除了Clear方法,以避免将其他人引入歧途。对于那些真正需要通过区域手动删除的方法,我参考了给定的链接。 –

0

另一种方法是围绕MemoryCache实现一个包装器,该包装器通过组合键和区域名来实现区域,例如,

public interface ICache 
{ 
... 
    object Get(string key, string regionName = null); 
... 
} 

public class MyCache : ICache 
{ 
    private readonly MemoryCache cache 

    public MyCache(MemoryCache cache) 
    { 
     this.cache = cache. 
    } 
... 
    public object Get(string key, string regionName = null) 
    { 
     var regionKey = RegionKey(key, regionName); 

     return cache.Get(regionKey); 
    } 

    private string RegionKey(string key, string regionName) 
    { 
     // NB Implements region as a suffix, for prefix, swap order in the format 
     return string.IsNullOrEmpty(regionName) ? key : string.Format("{0}{1}{2}", key, "::", regionName); 
    } 
... 
} 

这并不完美,但它适用于大多数使用情况。

我实现了这一点,它可以作为一个NuGet包:Meerkat.Caching