实现数据库级缓存的正确方法是什么? (这不是缓存提供商,它是关于缓存和存储库之间的关系!)如何正确实现数据库级缓存
解决方案#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。 –