首页 > 解决方案 > 如何获取包含某些关键字的所有缓存数据

问题描述

我正在使用 c# (Microsoft.Extensions.Caching.Memory) 中的缓存,因为我将多个数据存储到缓存中,如下所示。

IMemoryCache cache;

cache.Set("xxxx_1", "xxxx");
cache.Set("xxxx_2", "xxxx");
cache.Set("xxxx_3", "xxxx");

也可以一一获取数据。

Getcachedata = (string)cache.Get("xxxx_1")

但我想获取包含像 xxxx 这样的 Key 的数据完整数据。我浏览了很多文章,但没有得到帮助。

标签: c#.netasp.net-corecaching

解决方案


尝试编写CacheExtensions类来自定义GetCacheData如下方法:

public static class CacheExtensions
{
    public static Dictionary<TKey,TValue> GetCacheData<TKey, TValue>(this IMemoryCache cache, TKey key)
    {
        var data = new Dictionary<TKey, TValue>();
        var value = (TValue)(cache.Get(key) ?? default(TValue));
        data.Add(key, value);
        return data;
    }
}

然后得到如图所示的数据结果: 在此处输入图像描述


推荐阅读