Node distributed locking using redis
发布于 16 天前 作者 NextZeus 200 次浏览 来自 分享

最近做游戏的PVP系统,用到了redis 的分布式锁,在github上找到了 redislock分布式锁

看了文档之后,自己也做了个小测试, redislocktest

//redis.js
var redis = require('redis');
var redislock = require('redislock');
var client = redis.createClient('127.0.0.1',6379);
exports.lockPlayer = function(key, callback){
    var playerlock = redislock.createLock(client);
    playerlock.acquire(key+":lock", function (err) {
        callback(err,playerlock);
    });
}
exports.releasePlayerLock = function(playerlock,callback){
    playerlock.release(function (err) {
        callback(err);
});
//test.js
var playlock ;
async.waterfall([
    function (cb) {//获取锁
        redisUtil.lockPlayer('lock_xiaodong', function (err,data) {
            console.log('lock player error:',err);//null
            if(!err && !!data){
                playlock = data;
            }
            cb(err);
        });
    },
    function (cb) {
	    //默认10秒钟expire
        setTimeout(function () {
            redisUtil.lockPlayer('lock_xiaodong', function (err,data) {
                console.log('lock player error1:',err);//null
                if(!err && !!data){
                    playlock = data;
                }
            });
        },10000);
        cb();
    },
    function (cb) {//释放锁
        redisUtil.releasePlayerLock(playlock, function (err) {
            console.log('release player lock error:',err);//null
            cb(err);
        });
    }
], function (err) {
    if(!!err){
        redisUtil.releasePlayerLock(playlock, function (err) {
            console.log('release player lock error1:',err);
        });
    } else {
        console.log('lock and release lock success!!');
    }
});
}
回到顶部