Redisson是架设在Redis基础上的一个Java驻内存数据网格。

Redisson是一个基于Java的开源的、高级的Redis客户端,它实现了Redis的分布式和响应式特性,Redisson能够让Java开发者更方便地与Redis进行交互。

简单来说Redisson就是一个Redis的客户端,RedisTemplate更高级,更简单

怎么写一个简单的Redis分布式锁?

以Spring Data Redis为例,用RedisTemplate来操作Redis(setIfAbsent已经是setNx + expire的合并命令),如下:

 // 加锁

public Boolean tryLock(String key, String value, long timeout, TimeUnit unit) {

    return redisTemplate.opsForValue().setIfAbsent(key, value, timeout, unit);

}

// 解锁,防止删错别人的锁,以uuid为value校验是否自己的锁

public void unlock(String lockName, String uuid) {

    if(uuid.equals(redisTemplate.opsForValue().get(lockName)){        redisTemplate.opsForValue().del(lockName);    }

}

 

// 结构

if(tryLock){

    // todo

}finally{

    unlock;

}

但get和del操作非原子性,并发一旦大了,无法保证进程安全。于是张用Lua脚本

依赖

<!-- 原生,本章使用-->
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.13.6</version>
</dependency>
 
<!-- 另一种Spring集成starter,本章未使用 -->
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.13.6</version>
</dependency>

配置

@Configuration
public class RedissonConfiguration {
​
    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        //设置redis的地址,这里是单机模式
        config.useSingleServer().setAddress("redis://127.0.0.1:6379");
        //设置Redisson存储数据的格式,这里是使用的Json格式
        config.setCodec(new JsonJacksonCodec());
        return Redisson.create(config);
    }
}

使用

 
@Resource
private RedissonClient redissonClient;
 
RLock rLock = redissonClient.getLock(lockName);
try {
    boolean isLocked = rLock.tryLock(expireTime, TimeUnit.MILLISECONDS);
    if (isLocked) {
        // TODO
                }
    } catch (Exception e) {
            rLock.unlock();
    }