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");
相关推荐
Chasing__Dreams7 分钟前
Redis--基础知识点--33--String Hash List Set ZSet
redis·list·哈希算法
2601_9657984723 分钟前
Contractor Web Setup: Deploying Bathrooms & Kitchens Theme Fast
前端·web3·php·wordpress
Dxy123931021626 分钟前
Python XPath position() 完整使用指南,避坑合集(lxml适用)
前端·javascript·python
晴天1634 分钟前
HarmonyOS 和 React 对比-Day22
前端·华为·harmonyos
zone_z37 分钟前
Oracle 数据库基础故障排查系列(12 篇)
数据库·oracle·dba·troubleshooting·blog-series
DBA_G40 分钟前
GBase 8a数据库RANGE分区操作详细解读
数据库·oracle
某不知名網友2 小时前
MySQL数据表详解|创建、查看、修改、删除实战教程
数据库·mysql
Wang's Blog2 小时前
PostgreSQL笔记20: 实例、集群、模板数据库与表空间 —— 逻辑体系架构深度解析
数据库·笔记·postgresql
2602_959960922 小时前
大厂Java面试:Spring Boot、JVM、Redis、Kafka与Elasticsearch在内容社区UGC场景下的实战拷问
java·jvm·spring boot·redis·面试题
AlienZHOU7 小时前
DeepSeek Harness 插件:HTML 实时可视化编辑
前端·agent·deepseek