redisson分布式锁实现方式

在当下分布式开发中,分布式锁的应用非常频繁,也非常重要,所以下面根据我们实际操作,实现一下redisson的分布式锁。

1、引入maven包

powershell 复制代码
 
<!--redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>4.0.0</version>
</dependency>

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.16.3</version>
</dependency>

2、实现

创建获取分布式锁的工厂类interface

java 复制代码
public interface DistributedLockFactory {

    /**
     * 根据key获取分布式锁
     */
    DistributedLock getDistributedLock(String key);
}

基于Redisson的分布式锁实现服务

powershell 复制代码
@Component
public class RedissonLockFactory implements DistributedLockFactory {
    private final Logger logger = LoggerFactory.getLogger(RedissonLockFactory.class);

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public DistributedLock getDistributedLock(String key) {
        RLock rLock = redissonClient.getLock(key);
        return new DistributedLock() {
            @Override
            public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
                boolean isLockSuccess = rLock.tryLock(waitTime, leaseTime, unit);
                logger.info("{} get lock result:{}", key, isLockSuccess);
                return isLockSuccess;
            }

            @Override
            public void lock(long leaseTime, TimeUnit unit) {
                rLock.lock(leaseTime, unit);
            }

            @Override
            public void unlock() {
                if (isLocked() && isHeldByCurrentThread()) {
                    rLock.unlock();
                }
            }
            @Override
            public boolean isLocked() {
                return rLock.isLocked();
            }

            @Override
            public boolean isHeldByThread(long threadId) {
                return rLock.isHeldByThread(threadId);
            }

            @Override
            public boolean isHeldByCurrentThread() {
                return rLock.isHeldByCurrentThread();
            }
        };
    }
}

创建RedissonConfig配置类

下面可以设置配置文件 去配置单节点还是集群节点实例化RedissonClient

java 复制代码
@Configuration
@ConditionalOnProperty(name = "distributed.lock.type", havingValue = "redisson")
public class RedissonConfig {

    @Value("${spring.redis.address}")
    private String redisAddress;

    @Bean(name = "redissonClient")
    @ConditionalOnProperty(name = "redis.arrange.type", havingValue = "single")
    public RedissonClient singleRedissonClient() {
        Config config = new Config();
        config.useSingleServer().setAddress(redisAddress).setDatabase(0);
        return Redisson.create(config);
    }

    @Bean(name = "redissonClient")
    @ConditionalOnProperty(name = "redis.arrange.type", havingValue = "cluster")
    public RedissonClient clusterRedissonClient(){
        Config config = new Config();
        ClusterServersConfig clusterServersConfig = config.useClusterServers();
        clusterServersConfig.setNodeAddresses(Arrays.asList(redisAddress));
        return Redisson.create(config);
    }
}

配置文件

powershell 复制代码
# redisson
distributed.lock.type=redisson

#single/cluster
redis.arrange.type=single
相关推荐
落霞的思绪2 小时前
使用云虚拟机搭建hadoop集群环境
大数据·hadoop·分布式
Bug退退退12312 小时前
RabbitMQ 高级特性之事务
java·分布式·spring·rabbitmq
CodeWithMe12 小时前
【Note】《Kafka: The Definitive Guide》第四章:Kafka 消费者全面解析:如何从 Kafka 高效读取消息
分布式·kafka
Gauss松鼠会16 小时前
GaussDB应用场景全景解析:从金融核心到物联网的分布式数据库实践
数据库·分布式·物联网·金融·database·gaussdb
@Jackasher18 小时前
Redisson是如何实现分布式锁的?
分布式
❀always❀1 天前
深入浅出分布式限流(更新中)
分布式·wpf
Bug退退退1231 天前
RabbitMQ 幂等性
分布式·rabbitmq
{⌐■_■}2 天前
【Kafka】登录日志处理的三次阶梯式优化实践:从同步写入到Kafka多分区批处理
数据库·分布式·mysql·kafka·go
qq_529835352 天前
RabbitMQ的消息可靠传输
分布式·rabbitmq
CodeWithMe2 天前
【Note】《Kafka: The Definitive Guide》 第九章:Kafka 管理与运维实战
运维·分布式·kafka