Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Guava rate limiter
private RateLimiter createGuavaRateLimiter() {
double permitsPerSecond = ((double) hourlyLimit) / (60d * 60); // hourlyLimit / seconds-per-hour
logger.info("Creating rate limiter with {} permits per seconds", permitsPerSecond);
RateLimiter rateLimiter = RateLimiter.create(permitsPerSecond);
// initialize with a full number of permits. Use refleciton, as guava does not expose that functionality
try {
Class<?> limiterClass = Class.forName("com.google.common.util.concurrent.SmoothRateLimiter");
Field field = ReflectionUtils.findField(limiterClass, "storedPermits");
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, rateLimiter, hourlyLimit);
Field maxField = ReflectionUtils.findField(limiterClass, "maxPermits");
ReflectionUtils.makeAccessible(maxField);
ReflectionUtils.setField(maxField, rateLimiter, hourlyLimit);
Field burstField = ReflectionUtils.findField(Class.forName("com.google.common.util.concurrent.SmoothRateLimiter$SmoothBursty"), "maxBurstSeconds");
ReflectionUtils.makeAccessible(burstField);
setFinal(burstField, rateLimiter, 10);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return rateLimiter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment