我有大约 50 个网站,在 5 个 Web 服务器之间进行负载平衡。它们都使用企业库缓存,并访问相同的缓存数据库。缓存数据库中的项目每隔几个小时刷新一次,使用 ICacheItemRefreshAction 实现。
我想通过将刷新代码放在关键部分中来保证只有一个网站刷新缓存。
但是,这些不能确保跨多个 Web 服务器的关键部分。
目前,我正在缓存数据库中创建一个新密钥以充当互斥锁。这通常会起作用,但我可以看到 2 个进程进入临界区的可能性很小。
public class TakeLongTimeToRefresh : ICacheItemRefreshAction
{
#region ICacheItemRefreshAction Members
public void Refresh(string removedKey, object expiredValue, CacheItemRemovedReason removalReason)
{
string lockKey = "lockKey";
ICacheManager cm = CacheFactory.GetCacheManager();
if (!cm.Contains(lockKey))
{
Debug.WriteLine("Entering critical section");
// Add a lock-key which will never expire for synchronisation.
// I can see a small window of opportunity for another process to enter
// the critical section here...
cm.Add(lockKey, lockKey,
CacheItemPriority.NotRemovable, null,
new NeverExpired());
object newValue = SomeLengthyWebserviceCall();
cm.Remove(removedKey);
Utilities.AddToCache(removedKey, newValue);
cm.Remove("lockkey");
}
}
}
有没有办法保证关键部分以确保我不会两次调用网络服务?
编辑我应该补充一点,我不能使用共享文件,因为部署策略会阻止它。
StackOverflow 参考资料: