;
options.SlidingExpiration = TimeSpan.FromMinutes(1);
cache.Set<string>("timestamp", DateTime.Now.ToString(), options);
return View();
}
上面代码在Index() action中创建了MemoryCacheEntryOptions对象,并同时设置了一个绝对期限为1分钟与滑动期限为1分钟的策略。MemoryCacheEntryOptions对象作为Set()方法的第三个参数传递。
8. 定义移除缓存之后的回调函数
有时候你可能需要在缓存移除后获得通知。缓存被移除有以下2种原因,一是调用了Remove()方法,二是到期后自动移除。你可以通过设定回调函数获得移除缓存之后的通知:
public IActionResult Index()
{
//cache.Set<string>("timestamp", DateTime.Now.ToString());
MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
options.AbsoluteExpiration = DateTime.Now.AddMinutes(1);
options.SlidingExpiration = TimeSpan.FromMinutes(1);
options.RegisterPostEvictionCallback(MyCallback, this);
cache.Set<string>("timestamp", DateTime.Now.ToString(), options);
return View();
}
上面代码示例了通过RegisterPostEvictionCallback方法设定回调函数,在本例中回调函数名为MyCallback,第二个参数是你希望传递给回调函数的状态参数,本例我们将HomeController实例作为状态参数传递给回调函数。
回调函数方法如下:
private static void MyCallback(object key, object value, EvictionReason reason, object state)
{
var message = $"Cache entry was removed : {reason}";
((HomeController)state).cache.Set("callbackMessage", message);
}
看看上面代码,MyCallback() 是一个在HomeController中的私有静态函数,有四个参数。前两个参数是被移除的缓存数据所对应的键/值,第三个参数表示移除的原因。EvictionReason是一个枚举类型,可能原因有过期、移除和替换。
在函数体中,我们仅定义了一个string类型的message表示移除原因。如果我们想要把这个message作为另一个缓存项,就需要访问HomeController的缓存对象,此时就要使用第四个参数state。使用state对象获得HomeController中的缓存,同时使用Set()方法设置了一个名为“callbackMessage”的缓存项。
callbackMessage可以在Show() action中获得:
public IActionResult Show()
{
string timestamp = cache.Get<string>("timestamp");
ViewData["callbackMessage"] = cache.Get<string>("callbackMessage");
return View("Show", timestamp);
}
在Show页面呈现:
<h1>TimeStamp : @Model</h1>
<h3>@ViewData["callbackMessage"]</h3>
<h2>@Html.ActionLink("Go back", "Index", "Home")</h2>
测试回调方法,运行程序并访问/Home/Index页面,然后再访问/Home/Show页面,不断刷新Show页面直到缓存过期,页面会显示过期原因。
9. 缓存的优先级
和过期策略一样,缓存优先级同样使用MemoryCacheEntryOptions:
MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
options.Priority = CacheItemPriority.Normal;
cache.Set<string>("timestamp", DateTime.Now.ToString(), options);
CacheItemPriority枚举值有普通,高和永久保留。
10. 设置缓存之间的依赖关系
可以为缓存数据设置依赖关系,实现删除一个缓存项后,其依赖的缓存项同时被移除的功能。请按如下代码更新Index() action:
public IActionResult Index()
{
var cts = new CancellationTokenSource();
cache.Set("cts", cts);
MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
options.AddExpirationToken(new CancellationChangeToken(cts.Token));
options.RegisterPostEvictionCallback(MyCallback, this);
cache.Set<string>("timestamp",DateTime.Now.ToString(), options);
cache.Set<string>("key1", "Hello World!",new CancellationChangeToken(cts.Token));
cache.Set<string>("key2", "Hello Universe!",new CancellationChangeToken(cts.Token));
return View();
}
注:通过NuGet安装“Microsoft.Extensions.Primitives”程序包,同时添加对System. |