Nodejs IOREDIS: how to set expire time for a key?

Vikas Bansal picture Vikas Bansal · Dec 20, 2016 · Viewed 16.1k times · Source

I am connecting to a Redis sentinel using the code given below

var Redis = require('ioredis');
var redis = new Redis({
    sentinels: [{ host: '99.9.999.99', port: 88888 }],
    name: 'mymaster'
});

I am setting the value of a key by using following code:

function (key, data) {

        var dataInStringFormat = JSON.stringify(data); /// conbverting obj to string

        /// making promise for returning
        var promise = new Promise(function (resolve, reject) {
            /// set data in redis
            redis.set(key, dataInStringFormat)
                .then(function (data) {
                    resolve(data);
                }, function (err) {
                    reject(err);
                });
        });

        return promise;

    }

Can you please help me by providing a solution to set an expire time for the key value e.g. 12 hours

Answer

Tuan Anh Tran picture Tuan Anh Tran · Dec 20, 2016

It's documented

redis.set('key', 100, 'ex', 10)

Where EX and 10 stands for 10 seconds. If you want to use milliseconds, replace EX with PX