簡體   English   中英

批量REST API POST處理

[英]Bulk REST API POST Processing

我正在將40,000條記錄從一個系統遷移到另一個系統,將數據導入接收系統的唯一方法是通過rest API POST調用。

我正在尋找有關迭代40,000個REST API調用的最快方法的建議。 我有需要傳輸的數據格式為JSON,我已經使用PHP將對象分成40+ .json文件。 理想情況下,如果可能的話,我想異步處理POST,對使用PHP,JavaScript,Node.js或bash的方法的任何建議都會非常有用。

您可以通過curl的多功能與PHP同時進行POST調用。 代碼中的注釋。

$json_files = array('1.json','2.json', ... , '40.json');
$count = 0;
foreach($json_files as $json_file) {

    $list_of_objects = json_decode(file_get_contents($json_file),true);

    if(!$list_of_objects) {
        //log error
        continue;
    }

    //chunk into arrays of size 10 
    //or whatever # you want to run simultaneously
    $chunked_list = array_chunk($list_of_objects,10);

    foreach($chunked_list as $chunk) {
        $handles = array();    
        $mh = curl_multi_init();  

        foreach($chunk as $item) {
            $ch = curl_init('your api url here');  
            curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch,CURLOPT_POST, 1);
            curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($item));
            curl_multi_add_handle($mh, $ch);
            //index your handles by item id so 
            //you know what succeeded or failed
            $handles[$item['id']] = $ch;
        }

        //execute all 10 posts simultaneously
        //continue when all are complete
        $running = null;
        do {
            $status = curl_multi_exec($mh, $running);
        } while ($status === CURLM_CALL_MULTI_PERFORM || $running);

        foreach($handles as $item_id => $handle) {

            if(curl_multi_getcontent($handle) == 'my success message') {
                //log $item_id to success file
            }
            else {
                //log $item_id to fail file so you can retry later
            }

            curl_multi_remove_handle($mh, $handle);        
        }

        curl_multi_close($mh);
        $count += 10;
        print "$count ...\n";        
    }
}

首先要說的是:如果您已經使用PHP編寫這些JSON文件,我確信您可以調整該PHP腳本以直接發布到新服務器嗎?

這是一個批處理作業,因此您可以假設這是一次性腳本(盡管最好編寫它以便您可以重復使用它)。 關鍵是找出新服務器可以處理多少並發請求。 40k請求,比如10個並發請求,比如每個1秒,你應該在兩個小時內完成。

特別是在節點中,如果新服務器可以處理它,請確保將全局並行請求數設置為6以上。 http.globalAgent.maxSockets = 20 - 對同一主機名的最大請求數)。

您可以使用async類的模塊,也可以為並行請求編寫自己的簡單模塊。 如果您使用的是異步,那么您可以使用async.parallelLimit()來實現此目的。

要獲得更具體的答案,您必須更多地指定您的請求,可能會拋出一些代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM