1. AbsoluteExpirationRelativeToNow 和 AbsoluteExpiration
共同点:与某个时刻间隔一段时间失效。
差异:记时点不同,AbsoluteExpirationRelativeToNow 是以现在时间为参照,间隔一个段时间后失效。
AbsoluteExpiration 是以时间为参照对象(时刻),到达时间后就失效。
2. SlidingExpiration
距离上次访问固定间隔内访问可无限延续value的生命周期。
代码片段:
//
// 摘要:
// Provides the cache options for an entry in Microsoft.Extensions.Caching.Distributed.IDistributedCache.
public class DistributedCacheEntryOptions
{
public DistributedCacheEntryOptions();
//
// 摘要:
// Gets or sets an absolute expiration date for the cache entry.
public DateTimeOffset? AbsoluteExpiration { get; set; }
//
// 摘要:
// Gets or sets an absolute expiration time, relative to now.
public TimeSpan? AbsoluteExpirationRelativeToNow { get; set; }
//
// 摘要:
// Gets or sets how long a cache entry can be inactive (e.g. not accessed) before
// it will be removed. This will not extend the entry lifetime beyond the absolute
// expiration (if set).
public TimeSpan? SlidingExpiration { get; set; }
}
using Microsoft.Extensions.Caching.Distributed;
using System.Text;
namespace SqlServerCache
{
// 基于SQL Server 的缓存实现
public class SqlServerCacheDemo
{
public static void Run()
{
#region
Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(builder => builder
.ConfigureServices(svcs => svcs.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = "server=.;database=demodb;uid=sa;pwd=1;Trusted_Connection=True;Encrypt=false;";
options.SchemaName = "dbo";
options.TableName = "AspnetCache";
}))
.Configure(app => app.Run(ProocessAsync))
).Build().Run();
#endregion
}
static async Task ProocessAsync(HttpContext httpContext)
{
httpContext.Response.ContentType = "text/html;charset=utf-8";
var cache = httpContext.RequestServices.GetRequiredService<IDistributedCache>();
var currentTime = await cache.GetStringAsync("CurrentTime");
// cache.Remove("CurrentTime"); 抹除时间
currentTime = await cache.GetStringAsync("CurrentTime");
if (currentTime == null)
{
currentTime = DateTime.Now.ToString();
await cache.SetAsync("CurrentTime", Encoding.UTF8.GetBytes(currentTime), new DistributedCacheEntryOptions()
{
// 间隔时间失效
// AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(50)
// 距离上次访问间隔时间 过期失效
// SlidingExpiration = TimeSpan.FromSeconds(10)
// 绝对过期时间
AbsoluteExpiration = DateTimeOffset.Now.Add(TimeSpan.FromSeconds(10))
});
}
await httpContext.Response.WriteAsync($"{currentTime}({DateTime.Now})");
}
}
}