Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REDIS Durability ? how to auto expire data?

I use REDIS to store data (string) . ex: key "s1" store value "hello world". key "s2" store value "bye bye". I want s1 auto expire (free memory) after 5 minutes but s2 never expire. I use C#, .net 4.0 >> how to code ?. thanks

like image 274
skidrow406 Avatar asked Jun 30 '14 04:06

skidrow406


People also ask

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 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.

What is the default expiry of Redis?

There is no default TTL. By default, keys are set to live forever.

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.


Video Answer


2 Answers

Documentation regarding EXPIRE allows you to set an EXPIRE value per key, in seconds.

EXPIRE s1 300

will expire the key s1 in 5 minutes.

See the documentation here: REDIS EXPIRE

If you are looking for C# code, I think it would depend on what library you are using to access REDIS. There are some other SO questions that may help, but also discuss the problem where expire did not work: Redis Expire does not work

like image 173
wow0609 Avatar answered Oct 14 '22 16:10

wow0609


If you plan to use Redis just as a cache where every key will have an expire set, you may consider using the following configuration instead (assuming a max memory limit of 2 megabytes as an example):

maxmemory 2mb
maxmemory-policy allkeys-lru

In this configuration there is no need for the application to set a time to live for keys using the EXPIRE command (or equivalent) since all the keys will be evicted using an approximated LRU algorithm as long as we hit the 2 megabyte memory limit.

Basically in this configuration Redis acts in a similar way to memcached. We have more extensive documentation about using Redis as an LRU cache.

like image 35
arganzheng Avatar answered Oct 14 '22 18:10

arganzheng