Redisson实战

915 阅读1分钟

1.引入redisson

<!-- https://mvnrepository.com/artifact/org.redisson/redisson -->
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.15.6</version>
</dependency>
        

2.注入redissonClient

@Configuration
public class RedissonConfig {

    @Value("${spring.redisson.address}")
    private String redissonAddress;
    @Value("${spring.redisson.db}")
    private Integer redissonDB;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress(redissonAddress)
                .setDatabase(redissonDB);
        return Redisson.create(config);
    }

}

3.使用锁

    private final RedissonClient redissonClient;
    
    // 这里初始化redissonKey
    String redissonKey = "";
    RLock rLock = redissonClient.getLock(redissonKey);
    // 配置超时参数
    rLock.lock(paramConfig.getRedissonUserWaitTimeout(), TimeUnit.SECONDS);
    try {
       // 业务1
       ...
    } catch (Exception e) {
        log.error("Error,", e);
    } finally {
        log.info("unlock, redissonKey:{}", redissonKey);
        // 解锁
        if (rLock.isLocked()) {
            rLock.unlock();
        }
    }