每次请求都会重置过期时间为当前时间10秒后;
也就是说每次自增都会把过期时间重置
如果不想这样可以直接使用设置过期时间的那种方法,设置一次。以后只要每次自增都会重置;

  @GetMapping("/redisj")
    @NoAuthorization
    public String redisTest() {
        Long test = redisTemplate.boundValueOps("test").increment(1);
        Long timeout = redisTemplate.boundValueOps("test").getExpire();
        redisTemplate.boundValueOps("test").expireAt(new Date(System.currentTimeMillis()+10000));
        return timeout+"";

    }

每次自增都不会改变过期时间,会获取自增时间还有多少,然后设置回去;由于是设置什么时候过期,所以需要获取当前时间然后计算相对过期时间进行设置,比如还有10秒过去,那我就获得当前时间+10000,获取到7就7000因为获取的值是秒为单位;

@GetMapping("/redisc")
    @NoAuthorization
    public String redisTestc() {
        Long test = redisTemplate.boundValueOps("test").increment(1);
        Long timeout = redisTemplate.boundValueOps("test").getExpire();
        System.out.println("值:"+test+"__剩余时间:"+timeout);
        if (timeout<0){timeout=0L;}
        redisTemplate.boundValueOps("test").expireAt(new Date(System.currentTimeMillis()+timeout*1000));
        return timeout+"";

    }

第二种方法

   RedisAtomicLong aLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        long andIncrement = aLong.getAndIncrement();
        aLong.expireAt();//设置到什么时间过期,可以和上面方法同样使用
        aLong.expire();//设置多久以后过期,每次自增都会重置过期时间;
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐