redis 在ASP.NET核心7中设置默认滑动过期

xqk2d5yq  于 2023-02-28  发布在  Redis
关注(0)|答案(1)|浏览(191)

我在ASP.NET Core 7中安装了Microsoft.Extensions.Caching.Redis,并且我正在尝试在program.cs中设置默认的滑动过期:

即使在configurationOptions中,我也没有看到任何选项。

ryevplcw

ryevplcw1#

默认情况下,Redis缓存不支持设置全局过期时间。
检查RedisCacheOptions的源代码:

/// <summary>
    /// Configuration options for <see cref="RedisCache"/>.
    /// </summary>
    public class RedisCacheOptions : IOptions<RedisCacheOptions>
    {
        /// <summary>
        /// The configuration used to connect to Redis.
        /// </summary>
        public string Configuration { get; set; }

        /// <summary>
        /// The configuration used to connect to Redis.
        /// This is preferred over Configuration.
        /// </summary>
        public ConfigurationOptions ConfigurationOptions { get; set; }

        /// <summary>
        /// Gets or sets a delegate to create the ConnectionMultiplexer instance.
        /// </summary>
        public Func<Task<IConnectionMultiplexer>> ConnectionMultiplexerFactory { get; set; }

        /// <summary>
        /// The Redis instance name.
        /// </summary>
        public string InstanceName { get; set; }

        /// <summary>
        /// The Redis profiling session
        /// </summary>
        public Func<ProfilingSession> ProfilingSession { get; set; }

        RedisCacheOptions IOptions<RedisCacheOptions>.Value
        {
            get { return this; }
        }
    }

它不提供以下属性:

public TimeSpan DefaultSlidingExpiration { get; set; }

public TimeSpan? ExpiredItemsDeletionInterval { get; set; }

供用户设置默认到期时间。
一个简单的方法是使用默认过期时间自定义设置缓存方法。

public static  class Test
    {
        public static Task SetdefaultStringAsync(this IDistributedCache cache, string key, string value,  CancellationToken token = default(CancellationToken))
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            //set default Sliding Expiration
            var options = new DistributedCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromSeconds(5));
            
            return cache.SetAsync(key, Encoding.UTF8.GetBytes(value), options, token);
        }
    }

现在,当你使用这个自定义的方法,它会设置默认滑动过期5秒.

相关问题