У меня есть простой кэш, предназначенный для хранения экземпляров Guava RateLimiter
по IP. Смотрите кодовый блок ниже. Вызов 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
- stati c. Кроме того, я установил точку останова в строке 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
}