为什么我的AppFabric缓存中有多个缓存项使用相同的密钥?

时间:2013-04-25 14:53:54

标签: session caching appfabric distributed-caching appfabric-cache

我的网站代码在两台服务器上,我希望它们之间有共享缓存,所以我使用的是Microsoft AppFabric。我只希望在缓存中有一个项目 - 每个网站访问者不是一个项目,只有一个项目。

我正在尝试实现此目的的代码如下所示,但它不能按我想要的方式工作。我认为问题在于缓存中有许多项目,尽管它们都具有相同的密钥。但它可能是正在发生的其他事情。有关详细信息,请参阅代码注释。

Web.config

<dataCacheClient>
    <hosts>
      <host name="MyHost1" cachePort="22233"/>
      <host name="MyHost2" cachePort="22233"/>
    </hosts>
    <securityProperties mode="None" protectionLevel="None" />
</dataCacheClient>
...
<system.web>
    <sessionState mode="InProc" customProvider="AppFabricCacheSessionStoreProvider">
        <providers>
            <add
                name="AppFabricCacheSessionStoreProvider"
                type="Microsoft.ApplicationServer.Caching.DataCacheSessionStoreProvider"
                cacheName="MyCache"
                sharedId="MySharedApp"/>
        </providers>
    </sessionState>
    ...
</system.web>

Global.asax.cs

private static DataCacheFactory _cacheFactory = new DataCacheFactory();
private static DataCache _cache;

private void RegisterCacheEntry(){
    try
    {
        // Set up cache
        _cache = _cacheFactory.GetCache("MyCache");

        // Prevent duplicate key addition
        if (_cache.GetCacheItem(CacheItemKey) != null || _cache.Get(CacheItemKey) != null) 
            return;

        // Add item to cache
        _cache.Add(CacheItemKey, CacheItem, TimeSpan.FromMinutes(10));

        // When the cache item is removed, the callback:
        // 1) sends me an email 
        // 2) adds the same item with the same key to the cache again.
        // So I SHOULD be getting one email every 10 minutes.
        // However, it starts with one, but the number of emails that I get increases every 10 minutes.
        // i.e., I get one email at time t=0, two emails at t=1, three at t=2, then four, etc.
        _cache.AddItemLevelCallback(CacheItemKey, DataCacheOperations.RemoveItem, CacheItemRemovedCallback);
    }
    catch (Exception e){}
}

如果您想了解有关我正在做什么以及为什么的更多信息,我正在尝试使用如here所述的缓存超时来模拟Windows服务。但我正试图让它在两台服务器上运行。

1 个答案:

答案 0 :(得分:1)

您在web.config中添加了AppFabric会话状态提供程序。所有会话都将保留在群集中:这就是为什么您有多个缓存项目。

此外,您需要在系统中添加额外的错误管理,如here所述:

  

缓存主机只能容纳一定数量的缓存操作   记忆。根据系统负载,可能会有一些缓存   客户端在截断之前可能不会收到通知   缓存主机队列。缓存客户端也可能在数据时错过通知   由于缓存服务器在群集的其余部分发生故障而丢失   还在继续在这些情况下,您的缓存客户端可以发现它   它使用失败错过了一些缓存通知   通知。您的应用程序可以添加回调以接收失败   使用AddFailureNotificationCallback方法进行通知。对于   有关更多信息,请参阅添加失败通知回调

编辑: CacheItemRemovedCallback提供从缓存中删除的密钥。检查它是否始终相同。我还建议不要将分布式缓存限制为单个项目:如果其他人在缓存中添加了某些内容,系统将会失败。