PHP中的非同步Curl請求
在PHP中非同步執行curl post請求可以提高效能並防止潛在的延遲。以下是如何使用不同的方法實現此目的:
使用非同步 cURL 函數
使用curl_multi_*時,您可以同時執行多個 cURL 要求。以下是一個範例程式碼:
$curl = curl_init($request);
curl_setopt($curl, CURLOPT_URL, $url_onfleet);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERPWD, $api_onfleet);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_ENCODING, "");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, '{"destination":{"address":{"unparsed":"'.$pickup_address.'"},"notes":"'.$comments.'"},"recipients":[{"name":"'.$name.'","phone":" 61'.$phone.'","notes":"Number of riders: '.$riders.'"}],"completeBefore":'.$timestamp.',"pickupTask":"yes","autoAssign":{"mode":"distance"}}');
$mh = curl_multi_init();
curl_multi_add_handle($mh,$curl);
$active = null;
//execute the handles
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
//close the handles
curl_multi_remove_handle($mh, $curl);
curl_multi_close($mh);
使用 pThreads
pThreads 是 PHP 的執行緒函式庫。以下是如何將它用於非同步curl請求:
class Request1 extends Thread {
public function run() {
// Execute the first cURL request here
}
}
class Request2 extends Thread {
public function run() {
// Execute the second cURL request here
}
}
$req1 = new Request1();
$req1->start();
$req2 = new Request2();
$req2->start();
兩種方法都允許非同步執行curl請求,從而實現更好的效能和高效處理並行任務。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3