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
?
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With