How to iterate through MemoryCache in asp.net core?

前端 未结 2 1201
梦谈多话
梦谈多话 2021-01-18 11:24

There\'s no available method in IMemoryCache that allows to iterate through each cached item. My project is small, I don\'t want to use other options like Redis.

<         


        
2条回答
  •  走了就别回头了
    2021-01-18 12:09

    You should cache two type of items.

    1. You cache your properties as they are, abc.xyz-{0}.
    2. Second cache a list of property under the main key name, abc.xyz

    Sample Code:

    cache.Set("abc.xyz-name", name, TimeSpan.FromMinutes(30));
    cache.Set("abc.xyz-lastname", lastname, TimeSpan.FromMinutes(30));
    cache.Set("abc.xyz-birthday", birthday, TimeSpan.FromMinutes(30));
    cache.Set("abc.xyz", new List { "abc.xyz-name", "abc.xyz-lastname", "abc.xyz-birthday" }, TimeSpan.FromMinutes(30));
    

    and when deleting:

    var keys = cache.Get>("abc.xyz");
    foreach(var key in keys)
        cache.Remove(key);
    cache.remove("abc.xyz");
    

    Most of the services use IDistributedCache (in your case MemoryDistributedCache when registered - which again injects IMemoryCache which is MemoryCache class).

    In a distributed cache you can't iterate over all keys as there are potentially millions of keys and this would significantly reduce the performance of the cached service if you could/would iterate over it.

    So the above solution is also friendly and ready for the case when you replace your memory cache with a distributed cache, such as Redis.

提交回复
热议问题