redis 设置分布式锁 -凯发k8网页登录

快乐成长
posts - 110, comments - 101, trackbacks - 0, articles - 7
  凯发k8网页登录-凯发天生赢家一触即发官网 :: 凯发k8网页登录首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

redis 设置分布式锁

posted on 2014-01-15 19:00 云云 阅读(13285) 评论(1)  编辑  收藏
public static boolean acquirelock(string lock) {
    // 1. 通过setnx试图获取一个lock
    boolean success = false;
    jedis jedis = pool.getresource();      
    long value = system.currenttimemillis() expired 1;    
    system.out.println(value);    
    long acquired = jedis.setnx(lock, string.valueof(value));
    //setnx成功,则成功获取一个锁
    if (acquired == 1)      
        success = true;
    //setnx失败,说明锁仍然被其他对象保持,检查其是否已经超时
    else {
        long oldvalue = long.valueof(jedis.get(lock));
 
        //超时
        if (oldvalue < system.currenttimemillis()) {
            string getvalue = jedis.getset(lock, string.valueof(value));              
            // 获取锁成功
            if (long.valueof(getvalue) == oldvalue)
                success = true;
            // 已被其他进程捷足先登了
            else
                success = false;
        }
        //未超时,则直接返回失败
        else            
            success = false;
    }        
    pool.returnresource(jedis);
    return success;      
}
 
//释放锁
public static void releaselock(string lock) {
    jedis jedis = pool.getresource();      
    long current = system.currenttimemillis();      
    // 避免删除非自己获取得到的锁
    if (current < long.valueof(jedis.get(lock)))
        jedis.del(lock);      
    pool.returnresource(jedis);
}



//--------------------------

public long acquirelock(final string lockname,final long expire){
    return redistemplate.execute(new rediscallback() {
     public long doinredis(redisconnection connection) {
        byte[] lockbytes = redistemplate.getstringserializer().serialize(lockname);
boolean locked = connection.setnx(lockbytes, lockbytes);
connection.expire(lockbytes, expire);
if(locked){
return 1l;
}
            return 0l;
}
});
}


//原子操作 -----------------------

public string getandset(final string key,final string value){
return redistemplate.execute(new rediscallback() {
@override
public string doinredis(redisconnection connection)
throws dataaccessexception {
byte[] result = connection.getset(redistemplate.getstringserializer().serialize(key),
redistemplate.getstringserializer().serialize(value));
if(result!=null){
                                    return new string(result);
 }
return null;
                }
        });
}





评论

# re: redis 设置分布式锁   回复     

2016-04-20 15:04 by
请问expired如何设置

只有注册用户后才能发表评论。


网站导航:
              
 
网站地图