Home > Software engineering >  Set Expiry time of hsetnx
Set Expiry time of hsetnx

Time:11-30

How to Set expiry time of hsetnx (https://redis.io/commands/hsetnx/) to be 1 hour. Currently i don't see a param where i can set expiry time to it.

const IoRedis = require("ioredis");
const redis = new IoRedis();

var message = {
  "jobdid": "JCLT",
  "email": "[email protected]"
}

checkForDuplicate(message);

async function checkForDuplicate(message){

  const email    = message.email.toLowerCase();
    const jobdid = message.jobdid.toLowerCase();
    const resp   = await redis.hsetnx(`jobs:${email}`, jobdid,  new Date());

    console.log(resp);
}

CodePudding user response:

Not possible. You'll need to call EXPIRE on the key separately.

await redis.expire(`jobs:${email}`, 3600) // expire after 3600 seconds

ADDING ATOMICITY

As requested, here is an example of using ioredis with a transaction. Not that I have not tested this code, just writing it from memory.

await redis.watch(key)
redis.multi()
  .hsetnx(key, field, value);
  .expire(key, ttlInSeconds)
  .exec((err, results) => {
    /* if someone changes the key, this will error, otherwise
       you'll get an array of the results of calling each command */
  });

CodePudding user response:

If you don't need to enumerate the jobs separately, then you don't really need a hash; you can just se a sequence of setnx expire. You don't need a MULTI since setnx will only return 1 exactly once, so a second concurrent caller will never get to the expire.

const IoRedis = require("ioredis");
const redis = new IoRedis();

var message = {
  jobdid: "JCLT",
  email: "[email protected]",
};

checkForDuplicate(message);

async function checkForDuplicate(message) {
  const key = `jobs:${message.email.toLowerCase()}:${message.jobdid.toLowerCase()}`;
  const didSet = await redis.setnx(key,  new Date());
  if (didSet) {
    // We did set this, we're okay to set expiry too
    await redis.expire(key, 3600);
  }
  return didSet;
}
  • Related