Guava Cache 。put(key,value)不向我的缓存添加值; put()方法不起作用

问题描述 投票:0回答:1

我有一个简单的缓存,用于通过IP存储Guava RateLimiter实例。请参见下面的代码块。 put()调用不会将任何内容放入cache。在番石榴RateLimiter中存储Cache有一些限制吗?我明显缺少什么吗?

@Component
public class MyRateLimiter {

  public static final Logger LOGGER = LoggerFactory.getLogger(MyRateLimiter.class);
  public static long CACHE_SIZE = 1000L;
  public static long TIMEOUT = 10L;

  private static Cache<String, RateLimiter> cache = CacheBuilder.newBuilder()
        .maximumSize(CACHE_SIZE)
        .expireAfterWrite(TIMEOUT, TimeUnit.MINUTES)
        .build();

  public boolean tryAcquire(String key, double secondsBeforeNextOperation) {
      RateLimiter rateLimiter = cache.getIfPresent(key);
      if (rateLimiter == null) {
          rateLimiter = getNewRateLimiter(secondsBeforeNextOperation);
          cache.put(key, rateLimiter);  // <- This executes..
      }
      return rateLimiter.tryAcquire();  // <- But cache is still empty at breakpoint here
  }

  private RateLimiter getNewRateLimiter(double secondsBeforeNextOperation) {
      return RateLimiter.create(1 / secondsBeforeNextOperation);
  }

}

此代码碰巧在Spring Component中运行,但默认情况下为单例作用域,cache是静态的。此外,我在return rateLimiter.tryAcquire()行上设置了一个断点,并且cache仍然为空,即使刚执行cache.put()行之后的一行代码也是如此。

JVM是Java 8,我正在SpringBoot中运行。

---更新---

这是我使用tryAcquire()get(K, Callable<V>)方法:

public boolean tryAcquire(String key, double secondsBeforeNextOperation) {
    RateLimiter rateLimiter = null;
    try {
        rateLimiter = cache.get(key, () ->
                getNewRateLimiter(secondsBeforeNextOperation));
    } catch (ExecutionException e) {
        LOGGER.warn("Throttling cache was not able to be read.");
        return false;
    }
    return rateLimiter.tryAcquire();  // <-- cache still empty at this breakpoint
}
caching guava
1个回答
0
投票

确切地说,您如何确定断点注释所在行的缓存为空?我很想看看在同一位置打印/记录cache.asMap()的值的结果。

© www.soinside.com 2019 - 2024. All rights reserved.