我可以通过创建
IMemoryCache
类的实例来获取缓存的对象,如下所示:
_memoryCache.Get<Users>(id);
如何获取使用此类的用户列表?
如果列表没有缓存,如何缓存?
您可以使用 TryGetValue 方法,该方法返回缓存的对象作为输出参数。请参阅下面的示例:-
List<User> users;
string key = "usersCacheKey";
//TryGetValue will get the item from cache and assign it to users variable.
//It will return false if item is not found.
if(!_memoryCache.TryGetValue<List<User>>(key, out users){
//item not found in cache. set the cache item here
users = new List<User>();
_memoryCache.Set<List<User>>(key, users);
}
请参考以下链接,了解有关如何在 ASP.NET Core 5.0 中使用内存缓存的更多信息:- 在 ASP.NET Core 中缓存内存中