当前位置:网站首页>Redisson 分布式锁

Redisson 分布式锁

2022-08-09 23:33:00 川流不息的车呀

@Service
@Slf4j
public class RedissonUtils {
    @Autowired
    private RedissonClient redissonClient;


    public RLock lock(String s, int seconds) {
        RLock rlock = redissonClient.getLock(s);
        rlock.lock(seconds, TimeUnit.SECONDS);
        return rlock;
    }


}

 Redis 版本比较高的,连接redis地址要加redis://,否则连接会报错

@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedissonConfiguration {

    @Autowired
    private RedisProperties redisProperties;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        String redissonAddr = "redis://" + redisProperties.getHost() + ":" + redisProperties.getPort();
        config.useSingleServer().setAddress(redissonAddr);
        config.useSingleServer().setDatabase(redisProperties.getDatabase());
        return Redisson.create(config);
    }

}

配置文件获取redis配置参数:

@Component
@ConfigurationProperties(prefix = "spring.redis")
@Data
public class RedisProperties {

    private String host;

    private Integer port;

    private Integer database;
}

具体使用如下:

首先unlock最好写在finally里面,不管异常情况,最终都会执行,防止异常情况下,锁没有及时删除的情况(虽然设置过期时间,如果过期时间比较长,下次调用会获取不到锁)

if (locked.isLocked() && locked.isHeldByCurrentThread()) 

锁过期时间短,已经删除的情况下使用。否则报错:java.lang.IllegalMonitorStateException: attempt to unlock lock, not locked by current thread by node

 @Override
    public void setUpShop(setUpRequest request){
        RLock locked = null;
        try {
            String key = "设置的key";
            locked = redissonUtils.lock(key, 1);
            if (locked != null) {
                //处理业务
            }
        } finally {
            if (locked != null) {
               //判断要解锁的key是否已被锁定;判断要解锁的key是否被当前线程持有
                if (locked.isLocked() && locked.isHeldByCurrentThread()) {
                    locked.unlock();
                }
            }
        }
    }

原网站

版权声明
本文为[川流不息的车呀]所创,转载请带上原文链接,感谢
https://blog.csdn.net/u010738038/article/details/126250055