SpringBoot项目集成Redisson实现分布式锁

一、导入 Redisson 依赖

        
        
            org.redisson
            redisson
            3.6.3
        

或者

        
        
            org.redisson
            redisson-spring-boot-starter
            3.8.2
        

二、原生 Redisson 需要初始化 RedissonClient 实例,(redisson-spring-boot-starter)不需要初始化

1、初始化 RedissonClient  实例配置类

package com.hkl.mpjoin.configure;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RedissonConfigure {

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.port:6379}")
    private int port;


    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://" + redisHost + ":" + port)
                .setPassword(password);
        config.setCodec(new JsonJacksonCodec());
        return Redisson.create(config);
    }

}

备用代码(这里只是备份,并不需要):

//    @Bean
//    public RedissonReactiveClient redissonReactiveClient() {
//        Config config = new Config();
//        config.useSingleServer()
//                .setAddress("redis://" + redisHost + ":" + port)
//                .setPassword(password);
//        config.setCodec(new JsonJacksonCodec());
//        return Redisson.createReactive(config);
//    }

//    @Bean
//    public static RedissonReactiveClient createReactive() {
//        Config config = new Config();
//        config.useSingleServer().setAddress("redis://127.0.0.1:6379");
//        return createReactive(config);
//    }

备注:redisson-spring-boot-starter 方式不需要手动初始化 RedissonClient 实例

三、使用测试分布式锁

1、工具类代码

package com.hkl.mpjoin.utils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.RedissonMultiLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 

Description:分布式锁工具类

*

Author:hkl

*

Date:2022/11/25

*/ @Component @Slf4j public class LockUtil { @Resource RedissonClient redissonClient; @SneakyThrows public void doTryLock(String lockKey, long waitTime, TimeUnit unit, Runnable task) { RLock lock = redissonClient.getLock(lockKey); try { log.info("get redis lock, lock key : {}", lockKey); boolean isLocked = lock.tryLock(waitTime, unit); if (isLocked) { log.info("get redis lock success, lock key : {}", lockKey); task.run(); } else { log.info("get redis lock fail, lock key : {}", lockKey); } } finally { //解锁 unlock(lock, lockKey); } } public boolean tryLock(String lockKey, TimeUnit unit, int waitTime) { try { log.info("get redis lock, lock key : {}", lockKey); RLock rLock = redissonClient.getLock(lockKey); return rLock.tryLock(waitTime, unit); } catch (Exception e) { log.error("RedisUtils method tryLock Exception:", e); return false; } } public void unTryLock(String lockKey) { try { log.info("try release redis lock, lock key : {}", lockKey); RLock rLock = redissonClient.getLock(lockKey); if (rLock.isLocked()) { rLock.unlock(); } } catch (Exception e) { log.error("RedisUtils method unTryLock Exception:", e); } } private void unlock(RLock rLock, String lockKey) { try { log.info("try release redis lock, lock key : {}", lockKey); rLock.unlock(); log.info("release redis lock success, lock key : {}", lockKey); } catch (Exception e) { log.info("release redis lock fail, lock key : {}, message : {}", lockKey, e.getMessage()); } } @SneakyThrows public void doInMultiLock(RedissonMultiLock lock, long waitTime, TimeUnit unit, Runnable task) { try { log.info("get redis multiLock, lock key : {}", lock); lock.tryLock(waitTime, unit); log.info("get redis multiLock success, lock key : {}", lock); task.run(); } finally { unMultiLock(lock); } } private void unMultiLock(RedissonMultiLock multiLock) { try { multiLock.unlock(); } catch (Exception e) { log.error("RedisUtils method unMultiLock Exception:", e); } } public RedissonMultiLock getMultiLock(Set keys) { RLock[] locks = keys.stream().map(key -> redissonClient.getLock(key)).toArray(RLock[]::new); return new RedissonMultiLock(locks); } }

你可能感兴趣的:(Redis和SpCache,SpringBoot,spring,boot,redis,分布式)