博客详情

springboot3.2.x集成redisson分布式锁 (原创)

作者: 朝如青丝暮成雪
发布时间:2026-11-30 16:13:24  文章分类:java编程   阅读(7)  评论(0)


1、项目pom.xml中引入依赖


      <dependency>
            <groupId>org.redisson </groupId>
            <artifactId>redisson </artifactId>
            <version>3.42.0</version>
        </dependency>
2、项目中增加RedissonConfig配置类 (单节点)



import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * redisson 分布式锁配置
 */
@Configuration
public class RedissonConfig {

    @Value("${spring.data.redis.host}")
    private String host;

    @Value("${spring.data.redis.port}")
    private int port;

    @Value("${spring.data.redis.password}")
    private String password;

    /**
     * 配置redissonClient 这个bean,必须指定销毁方法
     * @return
     */
    @Bean(destroyMethod = "shutdown") // 必须指定销毁方法
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://" + host + ":" + port)
                .setPassword(password)//密码
                .setDatabase(2) //db 2 分布式锁
                .setConnectionPoolSize(64)  //连接池大小 64,默认64
                .setConnectionMinimumIdleSize(24) //最小空闲连接数 24  默认24
                ;
        return Redisson.create(config);
    }
}


3、redissonClient的使用示例


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Redisson 分布式锁示例 (秒杀服务场景)
 */
@Component
public class SecKillService {

    @Autowired
    private RedissonClient redissonClient;

    public void processOrder(String orderId) {
        // 锁的粒度要细:按订单ID加锁,避免全局锁
        RLock lock = redissonClient.getLock("lock:order:" + orderId);
        boolean isLocked = false;
        try {
            // 尝试加锁:最多等待 3 秒,不指定 leaseTime 以启用看门狗自动续期
            isLocked = lock.tryLock(3, TimeUnit.SECONDS);

            if (!isLocked) {
                throw new RuntimeException("获取锁失败,请稍后重试");
            }

            // --- 执行业务逻辑 ---
            // 例如:检查库存、扣减库存、生成订单
            Thread.sleep(5000); // 模拟耗时业务
            System.out.println("订单处理完成: " + orderId);

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("锁等待被中断", e);
        } finally {
            // 必须判断当前线程是否持有锁,防止异常情况下释放了别人的锁
            if (isLocked && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}




Redisson 的 RLock 解决了原生 Redis 锁的三大痛点:可重入、自动续期(看门狗)、阻塞等待。

1、加锁模式选择
推荐(看门狗自动续期):调用 tryLock(waitTime, TimeUnit) 不指定 leaseTime。这样只要业务线程未结束,Redisson 会每 10 秒将锁续期至 30 秒,避免业务执行超时导致锁误删 。

硬超时模式:调用 tryLock(waitTime, leaseTime, TimeUnit)。指定 leaseTime 后看门狗失效,锁会在固定时间后强制释放,适用于能严格控制执行时长的场景 。

2、标准代码模板 ()
务必在 finally 中释放锁,并判断 isHeldByCurrentThread() 防止释放他人的锁(虽然 Redisson 内部有校验,但显式判断更安全)。


避坑指南
1、不要在 finally 中无条件 unlock:如果 tryLock 返回 false(未拿到锁),此时调用 unlock 会抛出 IllegalMonitorStateException 。

2、锁与事务的顺序:如果业务中包含 @Transactional,加锁范围必须包裹事务。即先加锁,再开启事务,事务提交后,再释放锁。否则可能出现锁已释放但事务未提交,导致其他线程读到旧数据的问题。

3、RedissonClient 单例:Starter 已将其注册为单例 Bean,切勿在代码中手动 new 或频繁创建 RedissonClient,否则看门狗机制会失效且导致连接数暴涨 


关键字:  redisson  分布式锁

上一篇:springboot服务集成plumeLog日志

下一篇:没有了

评论信息
暂无评论
发表评论

亲,您还没有登陆,暂不能评论哦! 去 登陆 | 注册

博主信息
   
数据加载中,请稍候...
文章分类
   
数据加载中,请稍候...
阅读排行
 
数据加载中,请稍候...
评论排行
 
数据加载中,请稍候...

Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1

鄂公网安备 42011102000739号