【问题标题】:Clear StackExchange.Redis Cache with configurable expiry清除具有可配置过期时间的 StackExchange.Redis 缓存
【发布时间】:2017-04-13 19:00:24
【问题描述】:

我想知道是否有办法在指定的到期日期后从我的 c# 服务中清除/刷新整个缓存。如何在 c# 中实现这一点?

C#

// library
using StackExchange.Redis;

public class RedisCacheService
{
    // Fields
    ConnectionMultiplexer _Redis = null;
    IDatabase _RedisDB = null;

    // ctor
    public RedisCacheService(String redisConnectionString) // , DateTime ExpiryDate ? - Extracted from config
    {
        try 
        {
            if (String.IsNullOrEmpty(redisConnectionString))
            {
                throw new Exception("The 'redisConnectionString' parameter is unassigned");
            }

            this._Redis = ConnectionMultiplexer.Connect(redisConString);

            if (_Redis == null)
            {
                throw new Exception("_Redis object not initialized");
            }   

            this._RedisDB = _Redis.GetDatabase();           

            // I need to set some sort of expiry config here in the constructor.

            // The redisConnectionString is passed through when an instance of this class is created in the host startup and
            // the redisConnectionString is extracted from the config.
        }
        catch (Exception e)
        {
            throw new Exception(e);
        }
    }
}

我看到了一个类似的解决方案,当我实际使用对象填充缓存时,我可以传递一个过期时间,但我更想要一个全局缓存清除解决方案。

任何帮助或建议将不胜感激。

【问题讨论】:

    标签: c# stackexchange.redis


    【解决方案1】:

    您可以向 redis 添加一个假密钥,例如 _waitforit,并设置 TTL。 然后你等待它过期。 同时,您订阅key space events 以获取过期密钥。在您的 _waitforit 密钥过期的那一刻,您刷新数据库。

    这些事件的唯一缺点是您必须在 Redis 服务器上显式启用它。可以通过配置或命令行来完成。我想你需要CONFIG SET notify-keyspace-events Exe

    在网站注释上:

    如果您不想自己编写所有代码,您可以使用CacheManager 为您完成大部分工作。

    它内置了过期配置,您可以收听所有这些事件。

    您也可以订阅通过键空间事件触发的普通 C# 事件 onRemoveByHandle(如果一切配置正确)。

    【讨论】:

    • 事件不知道“关键空间事件”。这个很棒的东西,谢谢!
    • np ;) 唯一的缺点是您必须在 redis 服务器上显式启用它。可以通过配置或命令行来完成。我想你需要CONFIG SET notify-keyspace-events Exe
    猜你喜欢
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    相关资源
    最近更新 更多