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");
相关推荐
马尔代夫哈哈哈7 小时前
Spring IoC&DI
数据库·sql
a1117768 小时前
医院挂号预约系统(开源 Fastapi+vue2)
前端·vue.js·python·html5·fastapi
液态不合群9 小时前
[特殊字符] MySQL 覆盖索引详解
数据库·mysql
0思必得09 小时前
[Web自动化] Selenium处理iframe和frame
前端·爬虫·python·selenium·自动化·web自动化
计算机毕设VX:Fegn08959 小时前
计算机毕业设计|基于springboot + vue蛋糕店管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
瀚高PG实验室9 小时前
PostgreSQL到HighgoDB数据迁移
数据库·postgresql·瀚高数据库
打码人的日常分享10 小时前
智能制造数字化工厂解决方案
数据库·安全·web安全·云计算·制造
三水不滴10 小时前
Redis 过期删除与内存淘汰机制
数据库·经验分享·redis·笔记·后端·缓存
行走的陀螺仪10 小时前
uni-app + Vue3编辑页/新增页面给列表页传参
前端·vue.js·uni-app
-孤存-11 小时前
MyBatis数据库配置与SQL操作全解析
数据库·mybatis