Search code examples
c#redisazure-redis-cache

Can we set expiry for all keys in Azure Redis Cache?


To set an expiry for a key as it is being created, we can use StringSetAsync and pass a timestamp value for expiry. However, this is not possible if we want to set multiple key-value-pairs at once -

Task<bool> StringSetAsync(KeyValuePair<RedisKey, RedisValue>[] values, When when = When.Always, CommandFlags flags = CommandFlags.None);

Task<bool> StringSetAsync(RedisKey key, RedisValue value, TimeSpan? expiry = default(TimeSpan?), When when = When.Always, CommandFlags flags = CommandFlags.None);

Is it possible to set the expiry for all keys at the cache level on azure somewhere? I could not find the answer in any documentation. I want to set the kvps all at once to reduce the number of calls to azure redis cache. I also could not find any upper limit to this. How many keys at max can we get and set in one call?


Solution

  • According to the Redis Commands list or Related commands (the right-side of page) list about EXPIRE, there is not a command can expire all keys at a time.

    enter image description here

    So the only way is that you need to loop to run the command EXPIRE <key> <seconds> for the list from command KEYS *. Meanwhile, considering for reducing the number of requests, you can try to refer to the topic Scripting of StackExchange.Redis offical documents to generate a Lua script for all keys expiry and request once to expire all via command EVAL.