Ioredis: mset with expire/TTL

Created on 16 May 2020  路  2Comments  路  Source: luin/ioredis

Hi,

I'm aware that I can set a key with expiration by:
redis.set('key', 100, 'ex', 10)

I would like to leverage the operation mget with an expiration time.
Is there a way to do it?
Is there something similar to:

redis.mset(keys, 'ex', 10) ?

Most helpful comment

To whoever needs to set multiple keys with expiration date and avoid multiple trips to redis here is an example:

  const keys = ['a', 'b', 'c', 'd'];
  const oneDayInSeconds = 24 * 3600;
  const setCommands = keys.map((k) => {
    return ['set', `prefix_${k}`, 1, 'ex', oneDayInSeconds];
  });

  await this.cache
    .multi(setCommands)
    .exec(function() {
      // callback
    });

Ps.: You might need to tweak if you want to set a different value than 1 to the keys.

All 2 comments

No, as the operation mset does not Accept any expiration Parameter you have to do in two steps.

To whoever needs to set multiple keys with expiration date and avoid multiple trips to redis here is an example:

  const keys = ['a', 'b', 'c', 'd'];
  const oneDayInSeconds = 24 * 3600;
  const setCommands = keys.map((k) => {
    return ['set', `prefix_${k}`, 1, 'ex', oneDayInSeconds];
  });

  await this.cache
    .multi(setCommands)
    .exec(function() {
      // callback
    });

Ps.: You might need to tweak if you want to set a different value than 1 to the keys.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AdriVanHoudt picture AdriVanHoudt  路  4Comments

dfee picture dfee  路  4Comments

luckyscript picture luckyscript  路  5Comments

eduleboss picture eduleboss  路  3Comments

kimmobrunfeldt picture kimmobrunfeldt  路  5Comments