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
1、 getAndSet(K key, V value)
方法含义:获取原来key键对应的值并重新赋新值
使用方法:
redisTemplate.opsForValue().getAndSet("stringkey", "newvalue");
2、Boolean setIfAbsent(K key, V value)
方法含义:如果键不存在则新增,存在则不改变已经有的值。
使用方法:
redisTemplate.opsForValue().setIfAbsent("newkey", "newvalue");