Redisson分布式锁解决方案

官方地址


官网: https://redisson.org

github: https://github.com/redisson/redisson

基于setnx实现的分布式锁存在的问题


redisson分布式锁原理

  • 不可重入: 利用hash结构记录线程id和重入次数
  • 不可重试: 利用信号量和PubSub功能实现等待、唤醒, 获取锁失败的重试机制
  • 超时释放: 利用WatchDog, 每隔一段时间(releaseTime/3), 重置超时时间

依赖和配置


  • 引入依赖
xml 复制代码
		<dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.13.6</version>
        </dependency>
  • 配置
java 复制代码
	@Bean
    public RedissonClient redissonClient(){
        Config config = new Config();
        // 添加redis地址, 这里添加了单点的地址, 也可以用config.useClusterServers()添加集群地址
        config.useSingleServer().setAddress("redis://localhost:6379").setPassword("123456");
        return Redisson.create(config);
    }
  • 三台单点redis服务
java 复制代码
	@Bean
    public RedissonClient redissonClient(){
        Config config = new Config();
        // 添加redis地址, 这里添加了单点的地址, 也可以用config.useClusterServers()添加集群地址
        config.useSingleServer().setAddress("redis://localhost:6379").setPassword("123456");
        return Redisson.create(config);
    }

    @Bean
    public RedissonClient redissonClient2(){
        Config config = new Config();
        // 添加redis地址, 这里添加了单点的地址, 也可以用config.useClusterServers()添加集群地址
        config.useSingleServer().setAddress("redis://localhost:6380").setPassword("123456");
        return Redisson.create(config);
    }

    @Bean
    public RedissonClient redissonClient3(){
        Config config = new Config();
        // 添加redis地址, 这里添加了单点的地址, 也可以用config.useClusterServers()添加集群地址
        config.useSingleServer().setAddress("redis://localhost:6381").setPassword("123456");
        return Redisson.create(config);
    }
java 复制代码
	RLock multiLock;

    @BeforeEach
    void setUp() {
        RLock lock = redissonClient.getLock("xiaoyuxia");
        RLock lock2 = redissonClient2.getLock("xiaoyuxia");
        RLock lock3 = redissonClient3.getLock("xiaoyuxia");
        multiLock = redissonClient.getMultiLock(lock, lock2, lock3);
    }

    @Test
    void test() throws Exception {
        boolean b = multiLock.tryLock();
        try {
            if (b) {
                // TODO
            }
        } finally {
            multiLock.unlock();
        }
    }
相关推荐
AI 小老六1 小时前
Google AX 控制面拆解:分布式 Agent 如何把断点恢复、审计策略和执行调度收进同一条链路
人工智能·分布式·后端·ai·架构·ai编程
functionflux2 小时前
kafka-python:Python 生态中最成熟的 Kafka 客户端
分布式·python·其他·kafka
kyle~6 小时前
DDS分布式实时系统---自省机制
开发语言·分布式·机器人·c#·接口·ros2
q21030633726 小时前
kafka启动几秒后挂了,重启多次无果
分布式·kafka
凯源智能7 小时前
工商业分布式光伏箱变智能监控落地实战
分布式·箱变测控·光伏箱变测控装置·箱变监控系统·箱式变测控装置
沂水弦音7 小时前
软控 EI 系列模块优势与竞品对比分析:面向 EtherCAT 分布式 I/O 的工程选型视角
分布式·制造·工业自动化·ethercat·io模块
木心术18 小时前
在NVIDIA DGX Spark上部署NemoClaw的实际操作方案以及实际应用便利性。
大数据·分布式·spark
kuokay8 小时前
MLOps 与 AIOps 的核心概
人工智能·分布式·大模型·agent·llama
openFuyao9 小时前
openFuyao InferNex:云原生分布式 LLM 推理加速套件——从生产痛点到算力的极致释放
分布式·云原生·ai原生·openfuyao·多样化算力
咖啡星人k1 天前
MonkeyCode 开源协作指南:如何让分布式团队高效使用AI编程
分布式·开源·ai编程·monkeycode