Skip to content

Instantly share code, notes, and snippets.

@Glamdring
Last active July 14, 2017 12:37
Show Gist options
  • Save Glamdring/287844346374297bc0880b06df9dd492 to your computer and use it in GitHub Desktop.
Save Glamdring/287844346374297bc0880b06df9dd492 to your computer and use it in GitHub Desktop.
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