curl
应用程序以 curl 发起 http 请求的形式实现异步。但是 curl 请求也需要等待请求返回,程序同样会阻塞,这时我们需要设置 http 请求的超时时间为1s,这样相当于发起了一个 http 请求去执行任务,但是不等待其返回结果,继续向下执行程序,这样就可以实现异步效果。
function asyncCurl($url, $data)
{
if (is_array($data)) {
$data = http_build_query($data, null, '&');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result['response'] = curl_exec($ch);
$result['httpCode'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return $result;
}
$url = "<http://127.0.0.1/exec.php>";
$data = [];
asyncCurl($url, $data);
echo "OK";
curl 请求实现异步方式的缺陷就是 http 请求的最小超时时间为1s。也就是应用程序无论如何都要等待1s钟以上才能响应(现在 curl 扩展也能支持毫秒级别的超时时间设置,不过毫秒时间的超时很容易造成请求失败)。
curl实现毫秒级的超时设置:
curl_setopt($ch, CURLOPT_NOSIGNAL, true); //注意,毫秒超时一定要设置这个
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200); //超时时间200毫秒
一定要设置 CURLOPT_NOSIGNAL 设置为true,具体原因见 鸟哥的分析 http://www.laruence.com/2014/01/21/2939.html
参考: