在spring boot中使用opsForValue增加值时是否可以设置过期时间

问题描述

现在我正在使用此代码在 spring boot 中增加一个值:

 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 Boot 中没有直接的方法。

其中一种间接方式是使用 LUA srcipt。

例如:

RedisScript script = RedisScript.of(
        "local i = redis.call('INCRBY',KEYS[1],ARGV[1])"
        + " redis.call('EXPIRE',ARGV[2])"
        + " return i");

redisTemplate.execute(script,key,String.valueOf(increment),String.valueOf(expiration));

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...