如何将单线程curl_multi_init请求改造成多线程以提高效率?
curl_multi_init单线程改多线程实现
curl_multi_init能够实现多线程请求,提高执行效率。将其应用于单线程请求场景,需要对原有代码进行改造。
采用以下方案进行改写:
$newData = array_chunk($data, 10, true);foreach ($newData as $k => $tmp) { $mh = curl_multi_init(); $chs = []; foreach ($tmp as $key => $url) { $ch = curl_init(); $chs[$key] = $ch; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type:application/x-www-form-urlencoded;charset=utf-8;')); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $tmp); curl_multi_add_handle($mh, $ch); } $active = null; 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); } } foreach ($chs as $key => $ch) { $res[$k][$key] = curl_multi_getcontent($ch); curl_multi_remove_handle($mh, $ch); } curl_multi_close($mh);}var_dump($res);
原代码存在的几个问题:
- $ch 每一个都应该是独立的句柄,而不是通用一个
- curl_multi_getcontent 应该调用在每个 $ch 句柄上,而不是只调用每组最后一个 $ch 的。
- curl_multi_remove_handle 应该调用在每个 $ch 句柄上,这里合适的位置是在前面的 curl_multi_getcontent 之后调用。