缓存容量
//设置cache的最大限制是:100
MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions()
{
SizeLimit = 100,
});
总缓存设置大小 没有单位,只是个数
他的每一个缓存还可以设置大小。
缓存过期回调
设置每一个缓存项目的回调函数。
过期分为 被动过期,和主动过期 ,滑动过期。。
MemoryCacheEntryOptions cacheOptin = new MemoryCacheEntryOptions() { //被动过期 这种情况只有当再去查询这个缓存的时候,才会出发他的回调函数。不是实时的 AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10) }; cacheOptin.Size = 1; cacheOptin.RegisterPostEvictionCallback((k, v, r, s) => { Console.WriteLine(k + ":guoqi "); }); memoryCache.Set<string>("nihao", "value", cacheOptin);
//主动过期,程序控制过期 //主动过期 tokenSource.Cancel();也会出发回调函数 CancellationTokenSource tokenSource = new CancellationTokenSource(); cacheOptin.AddExpirationToken(new CancellationChangeToken(tokenSource.Token)); memoryCache.Set<string>("nihao1", "value1", cacheOptin); Console.WriteLine(memoryCache.Get<string>("nihao")); Console.WriteLine(memoryCache.Get<string>("nihao1")); tokenSource.Cancel(); //tokenSource.CancelAfter(1000 * 2);
原子性操作
memoryCache.GetOrCreate<string>("1", t => "1");
缓存优先级
cacheOptin.Priority = CacheItemPriority.High;
cacheOptin.SetPriority(CacheItemPriority.High);
设置单个缓存的优先级
缓存压缩
//压缩20%。剩余80% 。移除的时候,根据过期时间 优先级等操作
memoryCache.Compact(0.2);