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;
    }
}
相关推荐
fouryears_234171 天前
@PathVariable与@RequestParam的区别
java·spring·mvc·springboot
飞翔的佩奇2 天前
OpenTelemetry学习笔记(十二):在APM系统中,属性的命名空间处理遵循规则
笔记·学习·springboot·sdk·apm·opentelemetry
rhyme3 天前
源码浅析:SpringBoot main方法结束为什么程序不停止
springboot·markdown·java多线程·源码解析·mermaid
fouryears_234173 天前
Spring MVC 统一响应格式:ResponseBodyAdvice 从浅入深
java·spring·mvc·springboot
666HZ6664 天前
若依框架角色菜单权限
java·spring·springboot
鼠鼠我捏,要死了捏6 天前
Spring Boot中REST与gRPC并存架构设计与性能优化实践指南
springboot·restful·grpc
fanTuanye7 天前
前端环境搭建---基于SpringBoot+MySQL+Vue+ElementUI+Mybatis前后端分离面向小白管理系统搭建
vue.js·elementui·npm·springboot·前端开发环境搭建
飞鸟_Asuka8 天前
SpringBoot集成测试笔记:缩小测试范围、提高测试效率
java·单元测试·集成测试·springboot
nextera-void8 天前
SpringBoot 3.0 挥别 spring.factories,拥抱云原生新纪元
java·开发语言·springboot
TinpeaV8 天前
Springboot3整合Elasticsearch8(elasticsearch-java)
java·大数据·elasticsearch·搜索引擎·springboot