Does Azure Redis cache allow me to set a function to reliably trigger whenever a certain key in my cache expires?
Asked
Active
Viewed 2,392 times
1 Answers
5
You can combine a client using Redis Pub/Sub and Redis Keyspace Notifications to have a client receive a message when events happen to specific keys, or when specific events happen to any key. You can then use pattern-matching subscriptions to receive messages for more than a single key. You can also subscribe to multiple channels from a single client; all messages include which channel it is publishing to so your client can decide what to do.
To receive a message when any key beginning with foo
expires, do the following:
- Set
notify-keyspace-events
config value toKx
using the Azure Portal. Steps to set value for Azure are here. More details on the config value schema are defined here. - Using the client of your choice, PSUBSCRIBE (pattern subscribe) to the channel for your key:
PSUBSCRIBE '__keyspace@*__:foo*'
- Using another client connection, set a value for your key with a TTL:
SET foo42 bar EX 5
- After 5 seconds, you should see a message on your subscribing client:
"pmessage","__keyspace@*__:foo*","__keyspace@0__:foo42","expired"
To receive a message when any key expires, do the following:
- Set
notify-keyspace-events
config value toEx
- PSUBSCRIBE to the keyevent channel for keys being expired:
PSUBSCRIBE '__keyevent@*__:expired'
- In another client, set a key with a TTL:
SET foo bar EX 5
- After 5 seconds, see a message on your subscribing client:
"pmessage","__keyevent@*__:expired","__keyevent@0__:expired","foo"
For clients to quickly develop and debug, I would recommend using redis-cli or the Redis console in the Azure Portal.
Hope this helps. Good luck!

Adam
- 2,532
- 1
- 24
- 34
-
Thanks a lot for your answer, is it possible to get the content of the Key ? like "bar" in your example, I can't find a way to access the content – Aznhar Nov 19 '21 at 15:17
-
1I don't think so since Redis server would have already been removed the keys by the time it sends the notification. – Adam Nov 23 '21 at 00:22