redis方法 setIfAbsent

复制代码
    private void recordErrorTimes(LoginInfoReq req, String errorTimesKey) {
        String errorTimes = stringRedisTemplate.opsForValue().get(errorTimesKey);
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(errorTimesKey, "1", BasicConstants.CACHE_TIME_5, TimeUnit.MINUTES);
        if (!Boolean.TRUE.equals(result)) {
			//是false的情况下,说明redis中已经设置了这个key,已经有了这个键
			//如果是true,则是该redis中没有这个键
            // 已记录过登录失败次数,失败次数加1
            stringRedisTemplate.opsForValue().increment(errorTimesKey);
        }
        log.info("LoginServiceImpl.userLogin , 登录失败, 失败次数: {}, req:{}", errorTimes, JSON.toJSONString(req));
    }

大致意思是
判断该键在redis中是否存在,不存在返回true则新增并且赋值
存在了 则返回false

方法链接 getAndSet setIfAbsent

复制代码
1、 getAndSet(K key, V value)

方法含义:获取原来key键对应的值并重新赋新值

使用方法:

redisTemplate.opsForValue().getAndSet("stringkey", "newvalue");

2、Boolean setIfAbsent(K key, V value)

方法含义:如果键不存在则新增,存在则不改变已经有的值。

使用方法:

redisTemplate.opsForValue().setIfAbsent("newkey", "newvalue");
相关推荐
明月_清风27 分钟前
性能级目录同步:IntersectionObserver 实战
前端·javascript
明月_清风29 分钟前
告别暴力轮询:深度解锁浏览器“观察者家族”
前端·javascript
摸鱼的春哥32 分钟前
Agent教程17:LangChain的持久化和人工干预
前端·javascript·后端
程序员爱钓鱼2 小时前
Go操作Excel实战详解:github.com/xuri/excelize/v2
前端·后端·go
子兮曰10 小时前
async/await高级模式:async迭代器、错误边界与并发控制
前端·javascript·github
恋猫de小郭10 小时前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
GIS之路12 小时前
ArcGIS Pro 中的 Notebooks 入门
前端
IT_陈寒14 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
NineData15 小时前
NineData智能数据管理平台新功能发布|2026年1-2月
数据库·sql·数据分析
Kagol15 小时前
TinyVue 支持 Skills 啦!现在你可以让 AI 使用 TinyVue 组件搭建项目
前端·agent·ai编程