是否有更有效的方法来检查缓存数据是否存在,是否确实获取了它,以及是否没有调用 api/数据库然后缓存它?一遍又一遍地编写这样的代码对我来说似乎效率很低。
List<Map> maps = new List<Map>();
List<Playlist> playlists = new List<Playlist>();
if (SingletonCacheManager.Instance.Get<List<Map>>("Maps") != null)
{
maps = SingletonCacheManager.Instance.Get<ListMap>>("Maps");
}
else
{
maps = _mapRepository.FindBy(x => x.Active).ToList();
SingletonCacheManager.Instance.Add<List<Map>>(maps, "Maps", 20);
}
if (SingletonCacheManager.Instance.Get<List<Playlist>>("Playlists") != null)
{
playlists = SingletonCacheManager.Instance.Get<List<Playlist>>("Playlists");
}
else
{
var p = await _apiService.GetPlaylists();
playlists = p.ToList();
SingletonCacheManager.Instance.Add<List<Playlist>>(playlists, "Playlists", 20);
}
这样的事情是否可能:
List<Map> maps = this.CacheHelper.GetCachedItems<Map>(key, lengthoftime);
然后 GetCachedItems 将检查缓存的项目并相应地检索。这似乎可行,但是当缓存项不存在并且我必须从 api/数据库中检索项目时,我不知道是否可以将其设为通用。
唯一的解决方案是对传入的类型使用 switch 语句?
switch(<T>type)
{
case<Map>:
return _mapRepository.FindBy(x => x.Active);
case<Playlist>:
return await _apiService.GetPlaylists();
}
感谢您的帮助。
最佳答案
我的解决方案是传入一个函数,该函数获取您需要缓存的数据作为 lambda 表达式。这样,缓存方法可以检查缓存并仅在需要时调用委托(delegate)。例如:
public T Get<T>(string key, Func<T> getItemDelegate, int duration) where T : class
{
var cache = GetCache();
var item = SingletonCacheManager.Instance.Get<ListMap>>(key) as T;
if (item != null) return item;
item = getItemDelegate();
SingletonCacheManager.Instance.Add<T>(item, key, duration);
return item;
}
现在您可以像这样一般地调用 Get 函数:
var maps = Get<List<Map>>(
"Maps",
() => _mapRepository.FindBy(x => x.Active).ToList(),
20);
关于c# - C#中的通用缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41982292/