NETCORE - 缓存(MemoryCache)
NETCORE - 缓存(MemoryCache)
1. netcore中缓存相关的类库都在Microsoft.Extensions.Caching,使用MemoryCache首先安装包
Install-Package Microsoft.Extensions.Caching.Memory
下边的栗子介绍netcore中缓存的常用配置,直接看代码
class Program { static void Main(string[] args) { //缓存的配置 MemoryCacheOptions cacheOps = new MemoryCacheOptions() { //缓存最大为100份 //##注意netcore中的缓存是没有单位的,缓存项和缓存的相对关系 SizeLimit = 100, //缓存满了时,压缩20%(即删除20份优先级低的缓存项) CompactionPercentage = 0.2, //两秒钟查找一次过期项 ExpirationScanFrequency = TimeSpan.FromSeconds(3) }; MemoryCache myCache = new MemoryCache(cacheOps); //单个缓存项的配置 MemoryCacheEntryOptions cacheEntityOps = new MemoryCacheEntryOptions() { //绝对过期时间1 //AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(2)), //绝对过期时间2 //AbsoluteExpirationRelativeToNow=TimeSpan.FromSeconds(3), //相对过期时间 SlidingExpiration = TimeSpan.FromSeconds(3), //优先级,当缓存压缩时会优先清除优先级低的缓存项 Priority = CacheItemPriority.Low,//Low,Normal,High,NeverRemove //缓存大小占1份 Size = 1 }; //注册缓存项被清除时的回调,可以注册多个回调 cacheEntityOps.RegisterPostEvictionCallback((key, value, reason, state) => { Console.WriteLine($"回调函数输出【键:{key},值:{value},被清除的原因:{reason}】"); }); myCache.Set("mykey", "myvalue", cacheEntityOps); Console.WriteLine($"mykey的值:{myCache.Get("mykey") ?? "mykey缓存被清除了"}"); Console.WriteLine("------------------暂停3秒"); Thread.Sleep(3000); Console.WriteLine($"mykey的值:{myCache.Get("mykey") ?? "mykey缓存被清除了"}"); Console.ReadKey(); } } }
end
参考:http://news.558idc.com/451171.html