gpt4 book ai didi

javascript - 批量 REST API POST 处理

转载 作者:搜寻专家 更新时间:2023-10-31 21:33:42 25 4
gpt4 key购买 nike

我正在将 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";
}
}

关于javascript - 批量 REST API POST 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24946176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com