You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
2.2 KiB
66 lines
2.2 KiB
|
2 weeks ago
|
package common.ecommerce.hengjian.http;
|
||
|
|
|
||
|
|
import java.util.HashMap;
|
||
|
|
import java.util.Map;
|
||
|
|
import java.util.function.LongSupplier;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 按接口路径的令牌桶(间隔式)。
|
||
|
|
*
|
||
|
|
* <p>恒健文档未公开限流值,先按保守默认 {@link common.ecommerce.hengjian.HengjianConstants#PERMITS_PER_SECOND}
|
||
|
|
* 节流;429 的 {@code Retry-After} 由宿主处理,这里只做本地限速。</p>
|
||
|
|
*
|
||
|
|
* <p>进程内实现,多实例部署会叠加;需要跨实例限流时由宿主替换。
|
||
|
|
* 可注入 {@link Sleeper} 与纳秒时钟,测试不真的 sleep。</p>
|
||
|
|
*/
|
||
|
|
public final class HengjianRateLimiter {
|
||
|
|
|
||
|
|
/** 便于测试注入,生产用 {@link Thread#sleep}。 */
|
||
|
|
public interface Sleeper {
|
||
|
|
void sleep(long millis, int nanos);
|
||
|
|
}
|
||
|
|
|
||
|
|
private final Map<String, Long> nextAllowed = new HashMap<String, Long>();
|
||
|
|
private final Sleeper sleeper;
|
||
|
|
private final LongSupplier nanoClock;
|
||
|
|
|
||
|
|
public HengjianRateLimiter() {
|
||
|
|
this(new Sleeper() {
|
||
|
|
@Override
|
||
|
|
public void sleep(long millis, int nanos) {
|
||
|
|
try {
|
||
|
|
Thread.sleep(millis, nanos);
|
||
|
|
} catch (InterruptedException e) {
|
||
|
|
Thread.currentThread().interrupt();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}, new LongSupplier() {
|
||
|
|
@Override
|
||
|
|
public long getAsLong() {
|
||
|
|
return System.nanoTime();
|
||
|
|
}
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
public HengjianRateLimiter(Sleeper sleeper, LongSupplier nanoClock) {
|
||
|
|
this.sleeper = sleeper;
|
||
|
|
this.nanoClock = nanoClock;
|
||
|
|
}
|
||
|
|
|
||
|
|
/** 同一路径两次调用之间至少间隔 {@code 1e9 / permitsPerSecond} 纳秒。 */
|
||
|
|
public synchronized void acquire(String path, int permitsPerSecond) {
|
||
|
|
if (permitsPerSecond <= 0) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
long interval = 1_000_000_000L / permitsPerSecond;
|
||
|
|
long now = nanoClock.getAsLong();
|
||
|
|
Long next = nextAllowed.get(path);
|
||
|
|
if (next != null && now < next) {
|
||
|
|
long wait = next - now;
|
||
|
|
sleeper.sleep(wait / 1_000_000L, (int) (wait % 1_000_000L));
|
||
|
|
now = nanoClock.getAsLong();
|
||
|
|
}
|
||
|
|
nextAllowed.put(path, now + interval);
|
||
|
|
}
|
||
|
|
}
|