RateControl { boolean acquire(String group, String clientIP) { RateConfig config = this.config.get(group); if (config == null) { logger.warn("can not find group, group={}", group); return true; } String key = group + "/" + clientIP; Rate rate; synchronized (this) { rate = rates.computeIfAbsent(key, k -> new Rate(config.maxPermits)); } long currentTime = System.nanoTime(); return rate.acquire(currentTime, config.maxPermits, config.fillRatePerNano); } RateControl(int maxEntries); void config(String group, int maxPermits, int fillRate, TimeUnit unit); void validateRate(String group, String clientIP); public Map<String, RateConfig> config; }
@Test void acquire() { RateControl.Rate rate = new RateControl.Rate(1); rate.lastUpdateTime = 100; boolean result = rate.acquire(101, 2, 1); assertThat(result).isTrue(); assertThat(rate.currentPermits).isEqualTo(1); result = rate.acquire(101, 2, 1); assertThat(result).isTrue(); assertThat(rate.currentPermits).isEqualTo(0); result = rate.acquire(101, 2, 1); assertThat(result).isFalse(); result = rate.acquire(102, 2, 1); assertThat(result).isTrue(); assertThat(rate.currentPermits).isEqualTo(0); }