Caching 番石榴缓存<;K、 V>;。put(键、值)不向我的缓存添加值;put()方法不起作用

Caching 番石榴缓存<;K、 V>;。put(键、值)不向我的缓存添加值;put()方法不起作用,caching,guava,Caching,Guava,我有一个简单的缓存,用于通过IP存储GuavaRateLimiter实例。请参阅下面的代码块。put()调用不会将任何内容放入缓存。在番石榴缓存中存储速率限制器是否有一些限制?我有什么明显的遗漏吗 @Component public class MyRateLimiter { public static final Logger LOGGER = LoggerFactory.getLogger(MyRateLimiter.class); public static long CACHE

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

@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);
  }

}

您究竟是如何确定带有断点注释的行上的缓存为空的?我很想看到在同一个位置打印/记录cache.asMap()的值的结果。

非常确定这会起作用,但是,您可能应该使用
get(K,Callable)
我也使用过get(K,Callable)(先尝试过)。同样的结果是,这些项不会添加到缓存中={LocalCache@12368}大小=0
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
}