Skip to content

Instantly share code, notes, and snippets.

@dclucas
Created December 21, 2015 00:30
Show Gist options
  • Save dclucas/c1bdf2ea920da8db88b7 to your computer and use it in GitHub Desktop.
Save dclucas/c1bdf2ea920da8db88b7 to your computer and use it in GitHub Desktop.
Redis-based sequence generation in node.js
'use strict';
/*
initialize npm and make sure you add the required dependencies
$ npm init
$ npm install hapi ioredis redlock --save
}
*/
const Redlock = require('redlock');
const Redis = require('ioredis');
var client1 = new Redis();
var redlock = new Redlock([client1], {
retryCount: 2,
retryDelay: 150
});
function getSequence(key) {
return client1.incr(key)
}
function getExclusiveSequence(key) {
var ttl = 1000;
return redlock.lock('locks:' + key, ttl).then(function(lock) {
let res = client1.incr(key)
lock.unlock();
return res;
});
}
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 8000
});
server.route({
method: 'GET',
path:'/sequence/{key}',
handler: function (request, reply) {
let key = request.params.key
return reply(getExclusiveSequence(key)
.then(function(val) {
return {
"key": key,
sequence: val
}
}));
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment