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;
    }
}
相关推荐
闻哥10 小时前
深入理解 ES 词库与 Lucene 倒排索引底层实现
java·大数据·jvm·elasticsearch·面试·springboot·lucene
千寻技术帮1 天前
10404_基于Web的校园网络安全防御系统
网络·mysql·安全·web安全·springboot
金牌归来发现妻女流落街头4 天前
【Spring Boot注解】
后端·springboot
千寻技术帮5 天前
10368_基于SpringBoot的共享租车管理系统
源码·springboot·安装·文档·共享单车·单车租赁
闻哥6 天前
Redis 避坑指南:从命令到主从的全链路踩坑实录
java·数据库·redis·缓存·面试·springboot
悟空码字6 天前
SpringBoot深度整合高德地图,构建高性能位置服务
java·springboot·高德地图·编程技术·后端开发
千寻技术帮6 天前
10392_基于SpringBoot的大学迎新系统
mysql·vue·源码·springboot·代码·新生报到
曹轲恒8 天前
配置文件的占位符
springboot
code袁8 天前
基于微信小程序的宿舍维修小程序的设计与实现
微信小程序·小程序·毕业设计·springboot·notepad++·宿舍维修小程序