Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis list with expiring entries?

Tags:

caching

redis

I'm looking for a way to store a list of items for a user, that will expire within 24 hours. Is there a way to accomplish this using Redis? I was thinking of just using the list and setting an expiration for each individual item, is there a better way?

like image 743
MathBunny Avatar asked Dec 31 '17 18:12

MathBunny


People also ask

How do I expire a list in Redis?

As noted in the accepted answer, expiration in Redis is only performed at key-level - nested elements cannot be expired. To "expire" items, call ZREMRANGEBYSCORE from -inf and the current epoch minus 24 hours.

Does Redis automatically delete expired keys?

After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology. The timeout will only be cleared by commands that delete or overwrite the contents of the key, including DEL , SET , GETSET and all the *STORE commands.

How do I know when my Redis key expires?

Redis TTL command is used to get the remaining time of key expiry in seconds. Returns the remaining time to live of a key that has a timeout. This introspection capability allows a Redis client to check how many seconds a given key will continue to be part of the dataset.

Can you define an expiration time of a field in a hash in Redis?

Hi, it is not possible, either use a different top-level key for that specific field, or store along with the filed another field with an expire time, fetch both, and let the application understand if it is still valid or not based on current time.


2 Answers

As noted in the accepted answer, expiration in Redis is only performed at key-level - nested elements cannot be expired.

To implement a list with expiring elements, you can use the Sorted Set data structure. Every member's score should be the current epoch, so you'll retain the order of insertion. If the values (members) aren't unique, make them so by concatenating the epoch, e.g.:

ZADD user1:items 1514822755 1514822755:value
ZADD user1:items 1514822758 1514822758:value

To "expire" items, call ZREMRANGEBYSCORE from -inf and the current epoch minus 24 hours.

like image 56
Itamar Haber Avatar answered Sep 22 '22 22:09

Itamar Haber


NO, you CANNOT set expiration for each item in a LIST. You can only set an expiration for the entire LIST.

In order to achieve what you want, you need to have a key for each item:

SET user1:item1 value EX 86400
SET uesr1:iter2 value EX 86400
SET user2:item1 value EX 86400

To get all items of a specified user, you can use the SCAN command with a pattern (or use the Keyspace Notification to achieve better performance, but with more complex work):

SCAN 0 MATCH user1:*
like image 24
for_stack Avatar answered Sep 21 '22 22:09

for_stack