美文网首页
SpringBoot集成Redis分布式锁

SpringBoot集成Redis分布式锁

作者: CaryZheng | 来源:发表于2021-07-23 14:29 被阅读0次

    版本

    • 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();
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:SpringBoot集成Redis分布式锁

          本文链接:https://www.haomeiwen.com/subject/aozumltx.html