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;
    }
}
相关推荐
小胖墩有点瘦6 天前
【基于协同过滤的校园二手交易平台】
java·vue·毕业设计·springboot·计算机毕业设计·协同过滤·校园二手交易平台
叫我阿柒啊7 天前
从Java全栈到前端框架的实战之路
java·数据库·微服务·typescript·前端框架·vue3·springboot
叫我阿柒啊8 天前
Java全栈开发实战:从基础到微服务的深度解析
java·微服务·kafka·vue3·springboot·jwt·前端开发
lssjzmn8 天前
Spring Web 异步响应实战:从 CompletableFuture 到 ResponseBodyEmitter 的全链路优化
java·前端·后端·springboot·异步·接口优化
叫我阿柒啊9 天前
Java全栈开发工程师的实战面试经历:从基础到微服务
java·微服务·typescript·vue·springboot·前端开发·后端开发
Jerry&Grj9 天前
SpringBoot埋点功能技术实现方案深度解析:架构设计、性能优化与扩展性实践
java·微服务·性能优化·springboot·架构设计·埋点技术
叫我阿柒啊12 天前
从Java全栈到前端框架:一次真实的面试对话与技术解析
java·javascript·typescript·vue·springboot·react·前端开发
荣淘淘13 天前
互联网大厂求职面试记:谢飞机的搞笑答辩
java·jvm·spring·面试·springboot·线程池·多线程
叫我阿柒啊14 天前
从全栈开发到微服务架构:一位Java工程师的实战经验分享
java·ci/cd·kafka·mybatis·vue3·springboot·fullstack