业务场景
在开发中,当有业务需求需要调用第三方服务实现功能,但是服务接口有QPS限制,所以我们需要在发送请求时限制发送频率防止请求失败。
实现方法
使用 Java Semaphore
类来实现控制请求QPS
QPS限制
@Component
public class QPSController {private static final int MAX_QPS = 2;private final Semaphore semaphore = new Semaphore(MAX_QPS);public QPSController() {ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);scheduler.scheduleAtFixedRate(() -> semaphore.release(MAX_QPS - semaphore.availablePermits()), 0, 1, TimeUnit.SECONDS);}public void executeRequest() throws InterruptedException {semaphore.acquire(); // 获取许可,保证每次请求被限流Thread.ofVirtual().start(() -> {// 发送请求代码// ...});}}
调用
public class ServiceImpl implements Service {@Resourceprivate QPSController qpsController;public void Test() {ArrayList<String> num = new ArrayList<>();num.add("1");num.add("2");num.add("3");for (String s : num) {try {qpsController.executeRequest();} catch (InterruptedException e) {Thread.currentThread().interrupt();log.error("Request was interrupted", e);}}}}
事例所示,使用虚拟线程,限制QPS为2次/s