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);
    }

}
相关推荐
@菜菜_达4 分钟前
jquery.inputmask插件介绍
前端·javascript·jquery
QuZhengRong4 分钟前
【Luck-Report】缓存
java·前端·后端·vue·excel
jiayong239 分钟前
前端面试题库 - 浏览器与网络篇
前端·网络·面试
Csvn13 分钟前
小程序开发:微信小程序与 uni-app 实战指南
前端
摸鱼小李上线了19 分钟前
vue项目页面添加水印实现方法
前端·javascript·vue.js
砍材农夫25 分钟前
物联网 基于netty构建mqtt协议规范(主题通配符订阅)
java·前端·javascript·物联网·netty
彩票管理中心秘书长29 分钟前
智能体状态指示:何时思考、何时调用工具、何时出错
前端·后端·程序员
彩票管理中心秘书长29 分钟前
React + TypeScript拆解一整套“AI 变现代码流程”
前端·后端·程序员
广州华水科技32 分钟前
单北斗GNSS变形监测在基础设施安全中的应用与维护
前端
码途漫谈34 分钟前
把前端组件做成一座小岛:Animal-Island-UI 的自然风 React 组件库拆解
前端·开源