我有一个简单的缓存,用于按IP存储Guava RateLimiter实例。请参阅下面的代码块。put()调用不会将任何内容放入cache。在Guava Cache中存储RateLimiter有什么限制吗?有什么明显的我遗漏了什么吗?
@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()方法
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
}发布于 2020-02-23 15:46:16
您是如何确定包含断点注释的行上的缓存为空的?我非常有兴趣看到在同一位置打印/记录cache.asMap()的值的结果。
https://stackoverflow.com/questions/60358386
复制相似问题