1. 程式人生 > 實用技巧 >@Async 非同步http請求,彙總資料處理

@Async 非同步http請求,彙總資料處理

專案需求:

請求第三方介面獲取資料,一個小時大概有5000條左右的資料。

吐槽一下,第三方介面竟然分頁返回,一次只給2000條,擦了,只能非同步請求然後彙總了。

我需要每個小時獲取資料,並對資料進行分析處理,將結果存到本地。

具體實現:

主要使用@Async註釋,實現非同步,用定時任務一個小時執行一次。

@Async註釋如何新增請參考我的另一篇隨筆:

https://www.cnblogs.com/SamNicole1809/p/12610398.html

上程式碼:(示例)

1 - 非同步Http請求服務

@Service
public class AsyncService {

// 注入HttpUtils
@Async
public CompletableFuture<String> getData(String uri, int page) {
uri += "&page=" + page; return CompletableFuture.completedFuture(httpUtils.Get(uri)); } }

2 - 非同步一下子請求10000條(再讓你分頁返回,哼)

// 注入AsyncService
// 注意:在同一類中一個非同步呼叫另一個非同步是不生效的
// 這點與@Transactional註解類似,可以查一下

@Async
public void
getOneHourData(String uri) throws InterruptedException, ExecutionException { // 一頁2000條,非同步搞他10000條又怎樣
CompletableFuture
<String> future1 = asyncSer.getData(uri, 1); CompletableFuture<String> future2 = asyncSer.getData(uri, 2); CompletableFuture<String> future3 = asyncSer.getData(uri, 3); CompletableFuture
<String> future4 = asyncSer.getData(uri, 4); CompletableFuture<String> future5 = asyncSer.getData(uri, 5);
// 等待所有非同步請求完成 CompletableFuture.allOf(future1, future2, future3, future4, future5).join(); String data1 = future1.get();
......
// 處理資料,儲存到資料庫 }

3 - 定時任務處理資料

// 注入service
// cron表示式可以瞭解下,有線上生成工具,此處表示1個小時執行一次

@Scheduled(cron = "0 0 * * * ?")
@Async
public void s3() throws ExecutionException, InterruptedException {
    // 由於有很多裝置需要進行資料獲取,我得意的笑,全非同步
    List<Device> deviceList = ...;
    for (Device device : deviceList) {
        // 生成uri
        service.getOneHourData(uri);
    }
}

關鍵程式碼已經給出,可參考使用