问题
How to correctly clear IMemoryCache from ASP.NET Core?
I believe this class is missing Clear method, but anyway how to deal with it? In my project I'm caching DocumentRepository's methods for 24 hours where I'm getting lots of rows from database. But sometimes I can change the database, so I want to clear the IMemoryCache as it has got rubbish data.
回答1:
The cache class and interface don't have any methods for clearing neither ones to iterate over the keys, since it's not meant to be a list and in ASP.NET Core applications one usually use IDistributedCache
interface as dependency, since it easier allows you to later change from a local memory cache to a distributed cache (such as memd or Redis).
Instead, if you want to invalidate a specific row, you should remove the cached entry via cache.Remove(myKey)
.
Of course, this requires you to know the key you want to invalidate. Typically you do that via events. Every time you update an entry in the database, you would fire up an event. This event will be caught by a background service and cause a cache invalidation.
Locally this can be done with any pub/sub library. In distributed scenarios you may want to use pub/sub features of the distributed cache (i.e. Redis).
In cases of lookup tables (where many values are affected), you can have a service refresh the cache (i.e. every 5 to 10 minutes via a background task using a scheduling library such as hangfire or quart.net).
Home work Questions
But one question you should ask yourself: Is it really a good idea to cache documents for 24 hours if they change frequently?
Does the loading of a single document takes so much time, that caching it 24 hours will be worth? Or are shorter times good enough (15, 30, 60 minutes)?
回答2:
To clear you MemoryCache, just remove your memory cache by key, like this:
memoryCache.Remove("your_key");
来源:https://stackoverflow.com/questions/56315930/how-to-clear-memorycache-in-asp-net-core