当前位置: 首页>后端>正文

SpringBoot集成Redis分布式锁

版本

  • SpringBoot: 2.4.8
  • redisson-spring-boot-starter: 3.15.6

pom.xml

......
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.15.6</version>
</dependency>
......

application.yaml

spring:
  redis:
    host: 127.0.0.1
    port: 6379

注:配置文件中 redishostport 视实际情况而定。

RedissonConfig

@Configuration
public class RedissonConfig {

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

    @Value("${spring.redis.port}")
    public String port;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://" + host + ":" + port);

        return Redisson.create(config);
    }
}

使用

@Autowired
private RedissonClient redissonClient;

public void test(String phone) {
    String key = "redis:phone:" + phone;

    RLock rLock = redissonClient.getLock(key);
    try {
        boolean result = rLock.tryLock(3, 10, TimeUnit.SECONDS);
        if (!result) {
            System.out.println("获取分布式锁失败1");
        } else {
            System.out.println("获取分布式锁成功");
        }
    } catch (Exception e) {
        System.out.println("获取分布式锁失败2");
    } finally {
        if(rLock.isLocked()) {
            if(rLock.isHeldByCurrentThread()) {
                rLock.unlock();
            }
        }
    }
}

https://www.xamrdz.com/backend/3n41925137.html

相关文章: