我有一个在我的 Web 应用程序的服务层业务对象中缓存的类。当代码在负载平衡的服务器上运行时,当客户端访问一台机器并更新其详细信息,然后关闭浏览器,重新打开它并碰巧在负载平衡解决方案的另一台机器上访问网站时,他们的最新的更改不可见。
这个基本类由我的其他业务对象(如 People)继承。有没有办法可以刷新负载平衡环境中其他服务器上的缓存对象,以便客户端始终看到最新的?
public abstract class CacheStore<T> where T:IComparable, new()
{
private class CacheItem
{
public T Item
{
get;
set;
}
public DateTime Expires
{
get;
set;
}
}
private List<CacheItem> theCache = new List<CacheItem>();
public abstract TimeSpan Lifetime
{
get;
}
public int CountAll
{
get
{
return theCache.Count();
}
}
public int CountExpired
{
get
{
return theCache.Count(i => i.Expires < DateTime.Now);
}
}
public void Add(T item)
{
CacheItem i = (from c in theCache where (c.Item.CompareTo(item) == 0) select c).FirstOrDefault();
if (i != null)
{
if (i.Expires < DateTime.Now)
{
theCache.Remove(i);
i = null;
}
}
if (i == null)
{
theCache.Add(new CacheItem()
{
Expires = DateTime.Now + Lifetime,
Item = item
});
}
}
public IEnumerable<T> Filter(Func<T, bool> predicate)
{
return (from c in theCache where c.Expires > DateTime.Now select c.Item).Where(predicate);
}
public void MarkAsExpired(Func<T, bool> predicate)
{
var markAsExpired = from c in theCache
where this.Filter(predicate).Contains(c.Item)
select c;
foreach (CacheItem ci in markAsExpired)
{
ci.Expires = DateTime.Now.Subtract(TimeSpan.FromSeconds(1));
}
}
}
}