场景:运用node+mongo搭建web应用时,经常碰到并发题目致使建立一条数据的时刻会同时建立多条。
经由过程redis set 要领 合营 ‘NX’ 选项即可完成锁机制。
重要的要领有三个:
Redlock.prototype.lock = function(resource,ttl,callback){
var self = this;
var _val = _random();
return new Promise(function(resolve, reject) {
var lock = new Lock(self, resource, _val);
self.client.SET(resource,_val,'EX',ttl,'NX',function(err,data){
if(!err && data === 'OK'){
return resolve(lock);
}else{
var err = err || 'resource: '+resource+' is locked.';
self.emit('lockError', err);
return reject(err);
}
})
}).asCallback(callback);
}
Redlock.prototype.unlock = function(lock,callback){
var self = this;
return new Promise(function(resolve, reject) {
if(typeof lock !== 'object') return reject('unlockError:lock is not object.');
self.client.GET(lock.resource,function(err,data){
if(!err && data === lock.value){
self.client.DEL(lock.resource,function(err){
if(err){
self.emit('unlockError',err);
return reject('unlockError:'+err);
}else{
return resolve(lock);
}
})
}else{
self.emit('unlockError',err || 'resource:' + lock.resource + ' unable to unlock.')
return reject('unlockError:' + err || ('resource:' + lock.resource + ' unable to unlock.'));
}
})
}).asCallback(callback);
}
Redlock.prototype.extend = function(lock,ttl,callback){
var self = this;
return new Promise(function(resolve, reject){
if(typeof lock !== 'object') return reject('unlockError:lock is not object.');
self.client.GET(lock.resource,function(err,data){
if(!err && data === lock.value){
self.client.expire(lock.resource,ttl,function(err,data){
if(!err && data === 1){
return resolve(lock);
}else{
self.emit('extendError', err);
return reject('extendError:'+err);
}
});
}else{
self.emit('extendError', err);
return reject('extendError:'+err);
}
})
}).asCallback(callback);
}
用法
var client = require('redis').createClient('port','host');
var redlock = new RedLock(client);
var lock;
`callback`:
//lock
redlock.lock('test-resource-lock',3,function(err,lockInstance){
lock = lockInstance;
done(err);
});
//unlock
redlock.unlock(lock,function(err,data){
done(err);
});
`promise`:
redlock.lock('test-resource-lock-promise',3).done(
function(lock){
//todo
redlock.unlock(lock);
},
function(){
}
)
PS:支撑callback and promise.
完成比较简单,100行内,有兴致的能够在 这里https://github.com/navyxie/redlock-node 检察源码