使用 AddDistributedRedisCache 时为 IDistributedCache.SetAsync 设置过期时间

use*_*007 4 redis-cache asp.net-core-2.1

我正在使用带有 aws redis 缓存的 .net core api (2.1)。我没有看到将过期设置为IDistributedCache.SetAsync 的方法。这怎么可能?

我的代码段如下:

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddDistributedRedisCache(options =>
    {
        var redisCacheUrl = Configuration["RedisCacheUrl"];
        if (!string.IsNullOrEmpty(redisCacheUrl))
        {
            options.Configuration = redisCacheUrl;
        }
    });
}

Run Code Online (Sandbox Code Playgroud)
//Set & GetCache
public async Task<R> GetInsights<R>(string cacheKey, IDistributedCache _distributedCache)
{
    var encodedResult = await _distributedCache.GetStringAsync(cacheKey);               

    if (!string.IsNullOrWhiteSpace(encodedResult))
    {
    var cacheValue = JsonConvert.DeserializeObject<R>(encodedResult);
    return cacheValue;
    }

    var result = GetResults<R>(); //Call to resource access
    var encodedResult = JsonConvert.SerializeObject(result);
    await _distributedCache.SetAsync(cacheKey, Encoding.UTF8.GetBytes(encodedResult)); //Duration?

    return result;
}

Run Code Online (Sandbox Code Playgroud)

缓存可用多长时间?如何设置过期时间?如果这是不可能的,我该如何删除缓存?

Chr*_*att 7

它在options参数中。您传递 的实例DistributedCacheEntryOptions,该实例具有可用于设置过期时间的各种属性。例如:

await _distributedCache.SetAsync(cacheKey, Encoding.UTF8.GetBytes(encodedResult), new DistributedCacheEntryOptions
{
    AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
});
Run Code Online (Sandbox Code Playgroud)