實現數據庫級緩存的正確方法是什麼? (這不是緩存提供商,它是關於緩存和存儲庫之間的關係!)如何正確實現數據庫級緩存
解決方案#1:注入外部簡單緩存
public class MyRepository : IMyRepository
{
private readonly IDataCache _dataCache;
public MyRepository(IDataCache dataCache)
{
_dataCache = dataCache;
}
public string Get(int id)
{
var result = _dataCache.Get(id) as string;
if (result == null)
{
//Go fetch data from data source
_dataCache.Add(id, result);
}
return result;
}
}
解決方案#2:其它CachedRepository類實現相同的接口 (這將需要一些時髦的DI配置正確解決,但它是可能的)
public class MyRepository : IMyRepository
{
private readonly IDataCache _dataCache;
public MyRepository(IDataCache dataCache)
{
_dataCache = dataCache;
}
public string Get(int id)
{
//Go fetch data from data source
return result;
}
}
public class CachedMyRepository : IMyRepository
{
private readonly IMyRepository _myRepository;
private readonly IDataCache _dataCache;
public CachedMyRepository(IMyRepository myRepository, IDataCache dataCache)
{
_dataCache = dataCache;
_myRepository = myRepository;
}
public string Get(int id)
{
var result = _dataCache.Get(id) as string;
if (result == null)
{
result = _myRepository.Get(id);
_dataCache.Add(id, result);
}
return result;
}
}
(每種解決方案都基於這個簡單的存儲庫和高速緩存接口爲了討論)
public interface IMyRepository
{
string Get(int id);
}
public interface IDataCache
{
object Get(object key);
void Add(object key, object item);
}
你緩存一些永遠不會改變其狀態的對象嗎?你什麼時候使緩存無效?從IDataCache接口看來,我從來沒有喜歡過我。 –
Mc Kevin。你錯過了這一點。這不是關於緩存實現,這是關於存儲庫和緩存之間的關係。請閱讀該問題。 –
解決方案2對我來說更好,我認爲您在解決方案2的MyRepository中不需要IDataCache。 –