Skip to content

Instantly share code, notes, and snippets.

@crrobinson14
Last active January 7, 2020 17:21
Show Gist options
  • Save crrobinson14/7c9e6a93f21012026c8eb07ea89b0e51 to your computer and use it in GitHub Desktop.
Save crrobinson14/7c9e6a93f21012026c8eb07ea89b0e51 to your computer and use it in GitHub Desktop.
const Redis = require('redis');
const Config = require('./config.js');
const Log = require('./log.js');
let redisClient = Redis.createClient(Config.redis.uri);
// Locking utility function. This is based on https://github.com/errorception/redis-lock but we only needed a simple use-case of it,
// and redis-lock continually retries - we wanted to fail immediately if a lock was in use.
class Lock {
static acquire(feedId) {
return new Promise(function(resolve, reject) {
let value = '' + new Date(Date.now() + Config.redis.lockDuration),
key = 'hoover:lock:feed:' + feedId;
Log.info('LOCK: Will lock with key ' + key);
redisClient.set(key, value, 'PX', Config.redis.lockDuration, 'NX', function(err, result) {
if (err || result === null) {
reject('LOCK: ' + key + ' already locked');
}
resolve(result);
});
});
}
static release(feedId) {
return new Promise(function(resolve, reject) {
let key = 'hoover:lock:feed:' + feedId;
Log.info('LOCK: Releasing key ' + key);
redisClient.del(key, function(err, result) {
if (err) {
reject(err);
}
resolve(result);
});
});
}
}
module.exports = Lock;
// Lock it
const someId = '1234'; // What we want to lock
try {
await Lock.acquire(someId);
} catch (e) {
Log.info(`${someId} already being processed, skipping...`);
return 0;
}
// ... Do the work...
// Release and done.
await Lock.release(someId);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment