redission 分布式锁

<dependency>

<groupId>org.redisson</groupId>

<artifactId>redisson</artifactId>

<version>3.18.0</version> <!-- 与Spring Boot 2.7.18兼容的版本 -->

</dependency>

<!-- 如果使用redisson-spring-boot-starter -->

<dependency>

<groupId>org.redisson</groupId>

<artifactId>redisson-spring-boot-starter</artifactId>

<version>3.18.0</version>

</dependency>

虽然这2个依赖都可以,但是推荐使用第二个redisson-spring-boot-starter, 因为可以不用写如下配置类, 直接使用 RedissonClient redissonClient; 如下是定义自定义注解 和 aop切面编程,实现分布式定时任务, 只需要给 @

java 复制代码
@Slf4j
@Component
@Aspect
public class DistributdLockAspect {

    @Autowired
    private RedissonClient redissonClient;

    public static final String LOCK_PREFIX = "lock:";

    /**
     * distributedLock注解,之前抢锁, 注解方法执行之后释放锁
     * 因为 @Before通知的方法参数只能是 JoinPoint
     *  @Around方法才有 org.aspectj.lang.ProceedingJoinPoint 是 JoinPoint的子类
     *
     * @param joinPoint joinPoint
     * @param distributedLock distributedLock
     */
    @Around("@annotation(distributedLock)")
    public void action(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Throwable {
        String lockKey = LOCK_PREFIX + distributedLock.value();
        RLock lock = redissonClient.getLock(lockKey);
        boolean isLocked = false;
        try {
            isLocked = lock.tryLock(0, 30,TimeUnit.SECONDS);
            if (isLocked) {
                log.info("获取分布式锁成功,开始执行定时任务: {}", lockKey);
                joinPoint.proceed();
            } else {
                log.info("未获取到分布式锁,跳过执行: {}", lockKey);
            }
        } finally {
            if (isLocked && lock.isHeldByCurrentThread()) {
                lock.unlock();
                log.info("释放分布式锁: {}", lockKey);
            }
        }
    }

}


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @Author wangxinle5
 * @since 2025-12-01
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DistributedLock {
    String value() default "";
}
java 复制代码
import java.util.List;
import java.util.stream.Collectors;

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;
import org.springframework.util.StringUtils;

/**
 * @Author wangxinle5
 * @since 2025-11-18
 */
@Configuration
public class RedissonConfig {

    @Value("${spring.redis.sentinel.master}")
    private String master;

    @Value("${spring.redis.database}")
    private Integer database;

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

    @Value("${spring.redis.sentinel.nodes}")
    private List<String> sentinelNodes;

    @Bean
    public RedissonClient redissonClient() {
        List<String> nodes = sentinelNodes.stream().map(node -> "redis://" + node).collect(Collectors.toList());
        // 创建 Redis 哨兵配置
        Config config = new Config();
        // 配置哨兵集群模式
        config.useSentinelServers().setMasterName(master).addSentinelAddress(nodes.toArray(new String[0]))
            .setDatabase(database);
        // 只有密码不为空时才设置密码
        if (StringUtils.hasText(password)) {
            config.useSentinelServers().setPassword(password);
        }
        return Redisson.create(config);
    }

}
相关推荐
程序员黑豆1 小时前
Java包装类:基本类型与对象的桥梁
java·前端·ai编程
bugcome_com4 小时前
JWT 知识小课堂:从入门到精通,一文吃透 JSON Web Token
前端·json
To_OC4 小时前
写了三天 Next.js,我的 React 世界观被拆了又装回去
前端·全栈·next.js
独泪了无痕4 小时前
viewer.js 安装与配置指南:实现图片预览功能
前端·vue.js
Fluxart.ai6 小时前
电商商品图审核怎么自动化?规则引擎、人工复核与发布门禁
java·前端·自动化
why技术7 小时前
AI 写的文章,可能都带着手敲一遍都去不掉的“隐形水印”。
前端·人工智能·后端
愚公搬代码7 小时前
【愚公系列】《Android应用案例开发大全》016-LBS类应用掌上杭州(辅助工具类的开发)
android·前端
CodeSheep7 小时前
又一个华为天才少年,离职了!
前端·后端·程序员
kyriewen7 小时前
面试官说"打开你的AI工具"——我才发现,他考的根本不是写代码
前端·人工智能·面试
IT_陈寒8 小时前
Vue的双向绑定把我坑惨了,原来这个场景不能用
前端·人工智能·后端