I'm trying to implement a cache which will count the number of login attempts in the last 5 minutes, in my code i want to check if the user has attempted more than MAX_ATTEMPTS.
In all the code examples i found online for "Guava Cache" use the load method to fetch the value from some other source or calculate it using some method, how can i increment it every time there is a cache hit ?
static LoadingCache<String, Integer> cache = CacheBuilder.newBuilder()
.maximumSize(100000)
.expireAfterAccess(5, TimeUnit.MINUTES)
.build(
new CacheLoader<String, Integer>() {
public Integerload(String user) {
return ????;
}
}
);
later at runtime i would like to check:
if(cache.getIfPresent(user) != null && cache.get(user) > MAX_ATTEMPTS)
and also increment it if:
if(cache.getIfPresent(user) != null && cache.get(user) <= MAX_ATTEMPTS)
@Oren Your solution isn't thread-safe, since you're operating on a value outside Cache. You'd better use Cache#asMap()
view and change value inside ConcurrentMap#compute(K, BiFunction<K, V, V>)
method:
forgetPasswordCache.asMap().compute(email, (cachedEmail, currentCount) -> {
if (currentCount != null && currentCount >= RESET_PASSWORD_MAX_ATTEMPTS) {
logger.error("User with id: " + user.getId() + " and email: " + email +
" has reached the maximum number of reset password attempts, the mail will not be sent");
return null;
}
if (currentCount == null) {
return 1;
} else {
return currentCount + 1;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With