Setting Expiry in Redis

0 0
Read Time:2 Minute, 23 Second

This is a short article that features a video on Setting Expiry in Redis. So, we will learn how you can set an expiry time to your Redis keys.

What is Redis?

Redis is an open-source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. It is highly reliable, scalable, and has high availability.

Redis can be used to cache content . For eg. — database queries that are supposed to be used by users, for eg. Flight Search Results (of course with an expiry time), static content like HTML, JS, CSS. Redis is also highly used as a Session Store for users authorizations. Unique user sessions are stored in Redis. Rather than making roundtrips to Databases on the disk, reading and writing user sessions in Redis is faster.

Some useful commands

Here are a few useful commands that you will be using very commonly,

1. Get All Keys

keys *

2. Get a particular key’s value

get key_name

3. Set a key with a value

set key_name value

4. Delete a key

del key_name

5. Set key with expiry in seconds. (Expire after 60secs)

set key_name value EX 60

You can also use ex in place of EX.

6. Set key with expiry in milliseconds. (Expire after 6secs = 6000ms)

set key_name value PX 6000

You can also use px in place of PX.

7. Flush the Database. Kill all keys.

flushdb

8. Get Database size. Total no of active keys

dbsize

9. Check expiry time left for a key. In seconds.

ttl key_name

Setting expiry in Redis

You can use the EX and PX modifiers in your Redis commands. Watch the video below where I cover it in detail.

https://youtube.com/watch?v=D8DUmuEGRYg%3Ffeature%3Doembed

In case you are using a Redis client in a Node Express server, then you can set expiry to your keys in pretty much the same way.

So, for the example shown below, I am using node-redis module, which is a high performance Node.js Redis client.

Once you have your Node Redis client connected to your Redis instance,

//connect to Redis
const redisClient = redis.createClient({
    port: REDIS_PORT,
    host: REDIS_HOST,
});

You can set keys in Redis with expiry as show below, I am setting an expiry time of 10mins to my key users.

redisClient.set('users', JSON.stringify(users), 'EX', 10*60, (err) => { 
    //cache for 10mins
    if(err) {
      return res.status(500).send('Server error');
    }
    
    //other operations will go here
    //probably respond back to the request
});

Anyways watch the video which will give you an idea of the topic that I am discussing in this article.

Have a Good Day! Cheers!

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %