Trying to LOCK key for a scheduler, but ioredis
is allowing me to create multiple keys with same name.
import * as redis from '../redis'
const redCli = redis.get(); // get function that starts ioredis
scheduleJob('my-job', '*/05 * * * * *', async () => {
const key = await redCli.set('my-key', 'key-value', 'EX', 30); // 30 seconds key lifetime
console.log(`KEY: ${key}`); // always log 'OK'
if (!key) {
// log error and return. NEVER gets here.
}
// ALSO TRIED:
if (redCli.exists('my-key')...
if (await redCli.ttl('my-key')...
// continue the flow...
});
I create a key with 30 seconds of lifetime. And my scheduler runs every 5 seconds.
When I try to redCli.set()
a key that already exists, shouldn’t return an ERROR/FALSE? Anything but ‘OK’…
2
Answers
Not sure why my attempts didn't work, but I solved this using
get
Like most mutating commands in Redis, the SET command in Redis is an upsert. That’s just how Redis works.
From the docs for the SET command: