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;
    }
}
相关推荐
保持学习ing2 天前
苍穹外卖day3--公共字段填充+新增菜品
java·阿里云·实战·springboot·前后端·外卖项目·阿里云文件存储
默默coding的程序猿3 天前
3.前端和后端参数不一致,后端接不到数据的解决方案
java·前端·spring·ssm·springboot·idea·springcloud
衍生星球4 天前
Maven 3.9.6的下载和配置
java·maven·springboot
还是鼠鼠14 天前
日志技术-Logback入门程序
java·后端·spring·springboot·logback
starstarzz17 天前
解决idea无法正常加载lombok包
java·ide·spring·intellij-idea·springboot·web
vivo互联网技术19 天前
Spring Boot 启动优化实践
后端·springboot·spring启动加速·异步初始化
七烦20 天前
vue3 + springboot实现微信登录
vue·springboot·微信公众号
LUCIAZZZ22 天前
项目拓展-Apache对象池,对象池思想结合ThreadLocal复用日志对象
java·jvm·数据库·spring·apache·springboot
LUCIAZZZ22 天前
钉钉机器人-自定义卡片推送快速入门
java·jvm·spring boot·机器人·钉钉·springboot
LUCIAZZZ22 天前
项目拓展-Jol分析本地对象or缓存的内存占用
java·开发语言·jvm·数据库·缓存·springboot