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();
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容