posts - 110, comments - 101, trackbacks - 0, articles - 7
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

redis 设置分布式锁

Posted on 2014-01-15 19:00 云云 阅读(13379) 评论(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<Long>() {
     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<String>() {
@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如何设置

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


网站导航: