在 spring 引导中使用 opsForValue 增加值时是否可以设置过期时间
is it possible to set expire time when using opsForValue to increment value in spring boot
现在我正在使用此代码在 spring 引导中递增一个值:
String loginFailedKey = "admin-login-failed:" + request.getPhone();
Object loginFailedCount = loginFailedTemplate.opsForValue().get(loginFailedKey);
if (loginFailedCount != null && Integer.valueOf(loginFailedCount.toString()) > 3) {
throw PostException.REACH_MAX_RETRIES_EXCEPTION;
}
List<Users> users = userService.list(request);
if (CollectionUtils.isEmpty(users)) {
loginFailedTemplate.opsForValue().increment(loginFailedKey, 1);
throw PostException.LOGIN_INFO_NOT_MATCH_EXCEPTION;
}
是否可以在增加密钥时设置过期时间?如果发生新的增量命令,则更新过期时间。我阅读了文档,但没有找到该工具。
在Spring引导中没有直接的方法。
间接 方法之一是使用 LUA srcipt。
例如:
RedisScript script = RedisScript.of(
"local i = redis.call('INCRBY', KEYS[1], ARGV[1])"
+ " redis.call('EXPIRE', KEYS[1], ARGV[2])"
+ " return i");
redisTemplate.execute(script, key, String.valueOf(increment),
String.valueOf(expiration));
现在我正在使用此代码在 spring 引导中递增一个值:
String loginFailedKey = "admin-login-failed:" + request.getPhone();
Object loginFailedCount = loginFailedTemplate.opsForValue().get(loginFailedKey);
if (loginFailedCount != null && Integer.valueOf(loginFailedCount.toString()) > 3) {
throw PostException.REACH_MAX_RETRIES_EXCEPTION;
}
List<Users> users = userService.list(request);
if (CollectionUtils.isEmpty(users)) {
loginFailedTemplate.opsForValue().increment(loginFailedKey, 1);
throw PostException.LOGIN_INFO_NOT_MATCH_EXCEPTION;
}
是否可以在增加密钥时设置过期时间?如果发生新的增量命令,则更新过期时间。我阅读了文档,但没有找到该工具。
在Spring引导中没有直接的方法。
间接 方法之一是使用 LUA srcipt。
例如:
RedisScript script = RedisScript.of(
"local i = redis.call('INCRBY', KEYS[1], ARGV[1])"
+ " redis.call('EXPIRE', KEYS[1], ARGV[2])"
+ " return i");
redisTemplate.execute(script, key, String.valueOf(increment),
String.valueOf(expiration));