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
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.
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.
There is no default TTL. By default, keys are set to live forever.
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.
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
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.
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