StackExchange.Redis key expiration by UTC date

19,606

How about something like...

public void Set(string key, object value, DateTime expires)
{
    var expiryTimeSpan = expires.Subtract(DateTime.UtcNow);

    _cache.StringSet(key, Serialize(value), expiryTimeSpan);

    //or Set(key, value, expiryTimeSpan);
} 
Share:
19,606

Related videos on Youtube

freethinker
Author by

freethinker

Updated on June 04, 2022

Comments

  • freethinker
    freethinker almost 2 years

    I am working with StackExchange.Redis and building a Redis client interface RedisClientManager. In my interface I have 2 key setters (by timespan expiration and datetime expiration):

    By timespan:

    public void Set(string key, object value, TimeSpan timeout)
    {
        _cache.StringSet(key, Serialize(value), timeout);
    }
    

    By date:

    public void Set(string key, object value, DateTime expires)
    {
        _cache.StringSet(key, Serialize(value));
        _cache.KeyExpire(key, expires);
    }
    

    Usage:

    By timespan:

    RedisClientManager.Set(o.Key, o, new TimeSpan(0, 0, 5, 0));
    

    By date:

    RedisClientManager.Set(o.Key, o, DateTime.UtcNow.AddMinutes(5));
    

    If I add new key by using Timespan (first method), the object is in Redis cache and expires after 5 minutes as well. If I add new key by using Date (second method), the object is not added to Redis.

    This issue happens only on server. On localhost all works fine.

    Maybe Redis uses local server time for keys?

    How can I fix this issue? What the proper way to set absolute expiration to key by using StackExchange.Redis?