2011-01-14 46 views
7

我想将使用EntLib的解决方案转换为使用AppFabric缓存。通过一些扩展方法的帮助,这是一个相当无痛的过程。ASP.Net AppFabric Cache缺少Flush/Clear和Count/GetCount方法?

扩展方法我用:

public static bool Contains(this DataCache dataCache, string key) 
{ 
    return dataCache.Get(key) != null; 
} 

public static object GetData(this DataCache dataCache, string key) 
{ 
    return dataCache.Get(key); 
}

但也有EntLib的两个特点,我觉得很难转换。即“计数”(计算缓存中的密钥数量)和“刷新”(从缓存中移除所有数据)。如果我可以迭代缓存中的密钥,两者都可以解决。

有一种叫做ClearRegion(string region)的方法,但是这需要我在所有使用的Get/Put/Add方法上指定一个区域名称,这需要一些手动容易出错的工作。

有没有什么办法可以获得缓存中的密钥列表?
是否有我可以使用的默认区域名称?
我没有使用区域名称时如何刷新缓存?

+0

该代码允许我用上面的.Contains()方法替换“.Count == 0”。 – 2011-01-14 14:45:31

回答

10

my previous answer炒作作为高速缓存的内部工作原理,当你不指定区域,以及如何获得不在指定区域对象的个数。

我们可以使用相同的技术建立一个Flush方法:

public void Flush (this DataCache cache) 
{ 
    foreach (string regionName in cache.GetSystemRegions()) 
    {  
     cache.ClearRegion(regionName) 
    } 
} 

正如我说有,我想叫区域可能要走的路 - 在我看来,使用他们解决更多的问题比创造。

+0

谢谢。它似乎自动创建了一整套区域。 Default_Region_0000到Default_Region_1023。清除全部显示它们为空(Get-CacheStatistics)。 – 2011-01-14 14:24:49

0

如果任何人将来会遇到问题(像我一样) - 这里是清除缓存的完整代码。

private static DataCacheFactory _factory; 
     private const String serverName = "<machineName>"; 
     private const String cacheName = "<cacheName>"; 

     static void Main(string[] args) 
     { 
      Dictionary<String, Int32> cacheHostsAndPorts = new Dictionary<String, Int32> { { serverName, 22233 } }; 
      Initialize(cacheHostsAndPorts); 
      DataCache cache = _factory.GetCache(cacheName); 
      FlushCache(cache); 
      Console.WriteLine("Done"); 
      Console.ReadLine(); 
     } 

     private static void FlushCache(DataCache cache) 
     { 
      foreach (string regionName in cache.GetSystemRegions()) 
      { 
       cache.ClearRegion(regionName); 
      } 
     } 

     public static void Initialize(Dictionary<String, Int32> cacheHostsAndPorts) 
     { 
      var factoryConfig = new DataCacheFactoryConfiguration 
      { 
       Servers = cacheHostsAndPorts.Select(cacheEndpoint => new DataCacheServerEndpoint(cacheEndpoint.Key, cacheEndpoint.Value)) 
      }; 

      _factory = new DataCacheFactory(factoryConfig); 
     }