首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Guava键,V>.put(键,值)没有向缓存中添加值;put()方法不起作用

Guava键,V>.put(键,值)没有向缓存中添加值;put()方法不起作用
EN

Stack Overflow用户
提问于 2020-02-23 09:24:05
回答 1查看 108关注 0票数 0

我有一个简单的缓存,用于按IP存储Guava RateLimiter实例。请参阅下面的代码块。put()调用不会将任何内容放入cache。在Guava Cache中存储RateLimiter有什么限制吗?有什么明显的我遗漏了什么吗?

代码语言:javascript
复制
@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是Java8,而我运行的是SpringBoot。

-更新

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

代码语言:javascript
复制
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
}
EN

回答 1

Stack Overflow用户

发布于 2020-02-23 15:46:16

您是如何确定包含断点注释的行上的缓存为空的?我非常有兴趣看到在同一位置打印/记录cache.asMap()的值的结果。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60358386

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档