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

}
相关推荐
前端不太难18 小时前
从 Navigation State 反推架构腐化
前端·架构·react
前端程序猿之路19 小时前
Next.js 入门指南 - 从 Vue 角度的理解
前端·vue.js·语言模型·ai编程·入门·next.js·deepseek
大布布将军19 小时前
⚡️ 深入数据之海:SQL 基础与 ORM 的应用
前端·数据库·经验分享·sql·程序人生·面试·改行学it
川贝枇杷膏cbppg19 小时前
Redis 的 RDB 持久化
前端·redis·bootstrap
JIngJaneIL19 小时前
基于java+ vue农产投入线上管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
天外天-亮20 小时前
v-if、v-show、display: none、visibility: hidden区别
前端·javascript·html
jump_jump20 小时前
手写一个 Askama 模板压缩工具
前端·性能优化·rust
be or not to be20 小时前
HTML入门系列:从图片到表单,再到音视频的完整实践
前端·html·音视频
90后的晨仔21 小时前
在macOS上无缝整合:为Claude Code配置魔搭社区免费API完全指南
前端
java1234_小锋21 小时前
[免费]SpringBoot+Vue勤工助学管理系统【论文+源码+SQL脚本】
spring boot·后端·mybatis·勤工助学