請記住,示例我在這裏展示只是爲了儘可能明確,沒有任何實際實施或生產代碼說明問題。飼養緩存與後端
而且,我們假設如果有什麼被存儲或從後端返回,它會被緩存。我從代碼中省略的例子和發生的地方。
對於這個問題的範圍,我們還必須假設,MyType集合總是很小,相當靜態,當應用程序啓動時,它將從後端獲取一切,並重用緩存副本,直到應用程序關閉。這就是爲什麼GetCached(id)
和GetBackend(id)
實際上來說是ListCached
和ListBackend
的包裝。
假設我們有以下一種簡單的存儲庫:
public class MyRepository : IRepository<MyType>
{
public IEnumerable<MyType> GetAll()
{
// Will return cached items if present
return ListCached ?? ListBackend;
}
public MyType Get(int id)
{
return GetCached(id) ?? GetBackend(id);
}
private MyType GetBackend(int id)
{
return ListBackend.FirstOrDefault(type => type.Id == id);
}
private MyType GetCached(int id)
{
return ListCached.FirstOrDefault(type => type.Id == id);
}
protected IEnumerable<MyType> ListBackend
{
get { return Backend.GetAll<MyType>(); }
set { Backend.StoreAll<MyType>(value); }
}
public IEnumerable<MyType> ListCached
{
get { return Cache.GetAll<MyType>(); }
set { Cache.StoreAll<MyType>(value); }
}
public void Store(MyType value)
{
Backend.Store(value);
}
}
而這裏的挑戰:
class Program
{
static void Main(string[] args)
{
#region Handling Missing Objects in Cache
// We have a repository
var rep = new MyRepository();
// Into which we put stuff (3 for the demo)
rep.Store(new MyType { Id = 1 });
rep.Store(new MyType { Id = 2 });
rep.Store(new MyType { Id = 3 });
// And the repository, after this, returns 3 items
// The items are returned from cache
var count = rep.GetAll().Count(); // Returns 3
// However, somewhere else in the application, it happens so,
// for any reason, bug, programmer error, photon from sun hitting the cpu
// or tinfoil-hat left home in rush,
// that one item gets removed from the cache
Cache.Remove(new MyType { Id = 2 });
// After which, only 2 items are returned from the repository
// since the cache exists, it won't even try to hit the database
count = rep.GetAll().Count();
// Now count = 2, while WE know the backend has now 3 items
// how would the program detect it and get a fresh copy from backend?
#endregion
}
}
,你會在這種情況下怎麼辦?是否有模式可以幫助檢測情況並從後端獲取新鮮收集。最佳實踐是什麼?
每次你需要得到緩存列表,你去數據庫檢查它是否同步,你不覺得它是以某種方式破壞緩存概念。 – TalentTuner 2013-03-11 08:17:38