Java線程池如何實現(xiàn)精準(zhǔn)控制每秒API請求
Java中基于線程池實現(xiàn)指定每秒發(fā)送一定數(shù)量的API請求,可以使用ScheduledExecutorService來調(diào)度任務(wù),同時使用ThreadPoolExecutor來處理并發(fā)請求,可以根據(jù)實際需求調(diào)整每秒請求數(shù)量、執(zhí)行時間、以及線程池大小。
實現(xiàn)思路
1.創(chuàng)建線程池
- 使用
Executors.newScheduledThreadPool()來創(chuàng)建一個調(diào)度線程池 - 并使用
Executors.newFixedThreadPool()來創(chuàng)建一個用于發(fā)送API請求的線程池
2.調(diào)度任務(wù)
- 使用
ScheduledExecutorService來按固定速率調(diào)度任務(wù)。 - 通過控制任務(wù)的頻率,可以確保每秒發(fā)送指定數(shù)量的請求。
3.定義API請求任務(wù)
- 定義一個實現(xiàn)
Runnable接口的類 - 負(fù)責(zé)執(zhí)行具體的API請求
4.控制請求速率
- 使用調(diào)度器每秒提交指定數(shù)量的任務(wù)到線程池中執(zhí)行。
引入依賴
<!-- Apache HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2</version>
</dependency>實現(xiàn)代碼
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import java.io.IOException;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class ApiRequestScheduler {
// 定義線程池,用于并發(fā)發(fā)送API請求
private final ExecutorService requestExecutor;
// 定義調(diào)度線程池,用于定時調(diào)度請求任務(wù)
private final ScheduledExecutorService scheduler;
// 記錄已發(fā)送的請求數(shù)量
private final AtomicInteger requestCounter;
// 每秒發(fā)送的請求數(shù)量
private final int requestsPerSecond;
// Apache HttpClient 實例
private final CloseableHttpClient httpClient;
// API 請求的目標(biāo)URL
private final String apiUrl;
// 構(gòu)造函數(shù),初始化線程池和調(diào)度器
public ApiRequestScheduler(int requestsPerSecond, String apiUrl) {
this.requestsPerSecond = requestsPerSecond;
this.requestExecutor = Executors.newFixedThreadPool(requestsPerSecond);
this.scheduler = Executors.newScheduledThreadPool(1);
this.requestCounter = new AtomicInteger(0);
this.httpClient = HttpClients.createDefault();
this.apiUrl = apiUrl;
}
// 開始調(diào)度API請求任務(wù)
public void start() {
// 每秒調(diào)度任務(wù),按照每秒發(fā)送的請求數(shù)量來執(zhí)行
scheduler.scheduleAtFixedRate(() -> {
for (int i = 0; i < requestsPerSecond; i++) {
requestExecutor.submit(this::sendApiRequest);
}
}, 0, 1, TimeUnit.SECONDS);
}
// 停止調(diào)度和關(guān)閉線程池及HttpClient
public void stop() {
scheduler.shutdown();
requestExecutor.shutdown();
try {
if (!scheduler.awaitTermination(1, TimeUnit.SECONDS)) {
scheduler.shutdownNow();
}
if (!requestExecutor.awaitTermination(1, TimeUnit.SECONDS)) {
requestExecutor.shutdownNow();
}
httpClient.close();
} catch (InterruptedException | IOException e) {
scheduler.shutdownNow();
requestExecutor.shutdownNow();
try {
httpClient.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
// 使用Apache HttpClient發(fā)送API請求
private void sendApiRequest() {
int requestId = requestCounter.incrementAndGet();
HttpUriRequestBase request = new HttpGet(apiUrl);
System.out.println("Sending API request #" + requestId);
try (CloseableHttpResponse response = httpClient.execute(request)) {
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("Request #" + requestId + " completed with status: " + response.getCode() +
", response: " + responseBody);
} catch (IOException | ParseException e) {
System.err.println("Request #" + requestId + " failed: " + e.getMessage());
}
}
public static void main(String[] args) {
// 每秒發(fā)送5個API請求,目標(biāo)URL為http://example.com/api
ApiRequestScheduler scheduler = new ApiRequestScheduler(5, "http://www.dzy.com/api");
// 啟動調(diào)度器
scheduler.start();
// 運行10秒后停止調(diào)度器
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// 停止調(diào)度器
scheduler.stop();
}
}實現(xiàn)效果
每秒發(fā)送指定數(shù)量的API請求,使用Apache HttpClient處理HTTP通信,并確保在多線程環(huán)境中正確管理資源。
可以根據(jù)實際需求調(diào)整每秒請求數(shù)量、API URL、以及線程池大小。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot 配置 Quartz 定時任務(wù)的方法
這篇文章主要介紹了Spring Boot 配置 Quartz 定時任務(wù)的方法,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09
Springboot項目全局異常統(tǒng)一處理案例代碼
最近在做項目時需要對異常進行全局統(tǒng)一處理,主要是一些分類入庫以及記錄日志等,因為項目是基于Springboot的,所以去網(wǎng)絡(luò)上找了一些博客文檔,然后再結(jié)合項目本身的一些特殊需求做了些許改造,現(xiàn)在記錄下來便于以后查看2023-01-01
spring-boot-autoconfigure模塊用法詳解
autoconfigure就是自動配置的意思,spring-boot通過spring-boot-autoconfigure體現(xiàn)了"約定優(yōu)于配置"這一設(shè)計原則,而spring-boot-autoconfigure主要用到了spring.factories和幾個常用的注解條件來實現(xiàn)自動配置,思路很清晰也很簡單,感興趣的朋友跟隨小編一起看看吧2022-11-11
Spring Native 基礎(chǔ)環(huán)境搭建過程
Spring?Native可以通過GraalVM將Spring應(yīng)用程序編譯成原生鏡像,提供了一種新的方式來部署Spring應(yīng)用,本文介紹Spring?Native基礎(chǔ)環(huán)境搭建,感興趣的朋友跟隨小編一起看看吧2024-02-02
SpringQuartz定時任務(wù)核心組件JobDetail與Trigger配置
Spring框架與Quartz調(diào)度器的集成提供了強大而靈活的定時任務(wù)解決方案,本文主要介紹了SpringQuartz定時任務(wù)核心組件JobDetail與Trigger配置,具有一定的參考價值,感興趣的可以了解一下2025-04-04
Java初學(xué)者之五子棋游戲?qū)崿F(xiàn)教程
這篇文章主要為大家詳細(xì)介紹了Java初學(xué)者之五子棋游戲?qū)崿F(xiàn)教程,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10

