Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StackExchange.Redis key expiration by UTC date

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?

like image 541
freethinker Avatar asked May 14 '15 10:05

freethinker


People also ask

Do Redis keys expire?

Normally Redis keys are created without an associated time to live. The key will simply live forever, unless it is removed by the user in an explicit way, for instance using the DEL command.

Is Redis TTL in seconds?

Time to live (TTL) is an integer value that specifies the number of seconds until the key expires. Redis can specify seconds or milliseconds for this value.

How do I change the expiration date on Redis cache?

To create a Redis with an expiration time, use the SET command and the EX option to set the expiration time. The EX option takes a number in seconds and sets the number of seconds the key is valid until expiration. You can also use PX to specify the expiration time in Milliseconds.


1 Answers

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);
} 
like image 72
Kyle Huang Avatar answered Oct 07 '22 06:10

Kyle Huang