springboot多实例部署时,@Scheduled注释的方法重复执行

问题:springboot多实例部署时,@Scheduled注释的方法重复执行

在 Spring Boot 中要实现 Redis 的SET NX EX命令,可以借助 Spring Data Redis 来完成。SET NX EX命令用于在键不存在时设置键值对,并同时设置过期时间。

xml 复制代码
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>

当spring-boot-starter-data-redis依赖版本比较旧时,可以使用使用 Lua 脚本实现 SET NX EX,前提是不使用redis集群。

org.springframework.dao.InvalidDataAccessApiUsageException: EvalSha is not supported in cluster environment 异常时,这是因为在 Redis 集群环境下,EvalSha 命令存在一定限制,Spring Data Redis 在执行 Lua 脚本

时默认可能会尝试使用 EvalSha 命令,而该命令在集群环境中并不总是被支持。

或者分两步操作

先使用 SETNX 尝试设置键值对,若设置成功再使用 EXPIRE 设置过期时间。但这种方式不是原子操作,在 SETNX 和 EXPIRE 之间可能会出现异常,导致锁没有设置过期时间,造成死锁。

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisLockServiceV2 {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public boolean setNXEX(String key, String value, long timeout, TimeUnit timeUnit) {
        Boolean setResult = redisTemplate.opsForValue().setIfAbsent(key, value);
        if (setResult != null && setResult) {
            redisTemplate.expire(key, timeout, timeUnit);
            return true;
        }
        return false;
    }
}
相关推荐
行者-全栈开发39 分钟前
SpringBoot CI/CD 流水线实战|Jenkins+GitLab CI,从手动到自动化交付
ci/cd·jenkins·springboot·devops·自动化部署·gitlab ci
华大哥3 天前
前后端分离实现五级行政区划树形菜单及设备查询管理
sqlite·vue·springboot
码哥字节3 天前
升到 Spring Boot 4.1,虚拟线程开了,HikariCP 连接池却崩了
java·springboot·claude code
极光代码工作室4 天前
基于SpringBoot的校园论坛系统
java·springboot·web开发·后端开发
源码宝4 天前
MES系统源码:Java8 + SpringBoot2.7 + MySQL8 + Redis,后端源码清爽易扩展
java·后端·源码·springboot·mes系统·源码二开·mes源码
MaCa .BaKa5 天前
55-宠物爱心救助领养系统-宠物救助领养系统
java·vue.js·tomcat·maven·springboot·宠物救助领养系统
苏渡苇5 天前
Spring Cloud Gateway 网关限流
spring cloud·gateway·springboot·网关限流
段ヤシ.5 天前
回顾Java知识点,面试题汇总Day17(持续更新)
java·springboot·spring security·shiro·mybatis-plus·jdbctemplate·spring data jpa
苦逼的猿宝6 天前
洗衣店订单管理系统(源码+论文)
java·毕业设计·springboot·计算机毕业设计
苦逼的猿宝6 天前
宠物咖啡馆平台的设计与实现(源码+论文)
java·毕业设计·springboot·计算机毕业设计