2012-01-25 73 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