ASP.Net AppFabric Cache缺少Flush / Clear和Count / GetCount方法?

时间:2011-01-14 13:32:28

标签: asp.net appfabric

我正在尝试使用EntLib将解决方案转换为使用AppFabric缓存。借助一些扩展方法,这是一个相当痛苦的过程。

我使用的扩展方法:

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有两个很难转换的功能。即“Count”(计算缓存中的键数)和“Flush”(从缓存中删除所有数据)。如果我可以在缓存中迭代密钥,那么两者都可以解决。

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

有没有办法获取缓存中的密钥列表?
我可以使用默认的区域名称吗?
如果我没有使用区域名称,如何刷新缓存?

2 个答案:

答案 0 :(得分:10)

关于我的推测,请参阅my previous answer,了解在未指定区域时缓存如何在内部工作,以及如何获取不在命名区域。

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

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

正如我在那里所说,我认为命名区域可能是的方式 - 在我看来,使用它们可以解决比它创造的问题更多的问题。

答案 1 :(得分: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);
        }