C# 中的通用缓存

Bad*_*Dub 5 c# generics caching

是否有更有效的方法来检查缓存数据是否存在、是否确实获取以及是否不调用 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);
}
Run Code Online (Sandbox Code Playgroud)

这样的事情可能吗:

List<Map> maps = this.CacheHelper.GetCachedItems<Map>(key, lengthoftime);
Run Code Online (Sandbox Code Playgroud)

然后 GetCachedItems 将检查缓存的项目并进行相应的检索。这似乎是可行的,但是当缓存的项目不存在并且我必须从 api/数据库检索项目时,我不知道是否可以通用。

唯一的解决方案是对传入的类型使用 switch 语句?

switch(<T>type)
{
  case<Map>:
      return _mapRepository.FindBy(x => x.Active);
  case<Playlist>:
      return await _apiService.GetPlaylists();
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助。

Dav*_*idG 4

我的解决方案是传入一个函数,该函数将您需要的数据缓存为 lambda 表达式。这样,缓存方法就可以检查缓存并仅在需要时调用委托。例如:

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;
}
Run Code Online (Sandbox Code Playgroud)

现在您可以像这样一般调用 Get 函数:

var maps = Get<List<Map>>(
    "Maps",
    () => _mapRepository.FindBy(x => x.Active).ToList(),
    20);
Run Code Online (Sandbox Code Playgroud)