官方连接
https://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html?highlight=getasync
使用guzzle 实现,需要先引用。安装请自行解决。
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
/*** 异步高并发请求*/public function asyncRequests(){// 以下三个参数是防止客户端超时set_time_limit(0);ignore_user_abort(true);
// fastcgi_finish_request();// 数据数组$list = [['id' => 1,'name' => '张三'],['id' => 2,'name' => '李四'],['id' => 3,'name' => '王五']];$client = new Client();foreach ($list as $k => $val) {// 创建多个请求,请求地址可以相同,也可以不同// $client->postAsync(); $client->getAsync();$promises[$k] = $client->getAsync('https://ad.oceanengine.com/open_api/2/advertiser/fund/get/',['headers' => ['content-type' => 'application/json', 'Access-Token' => $val['accessToken']],'body' => json_encode(['id' => $val['id'],'name' => $val['name']])]);}// 下面代码处理并发请求,并等待所有请求完成(每个请求之间是异步的,因此效率非常高),返回一个响应数组$responses = Promise \unwrap($promises);// 处理返回值foreach ($responses as $k => $response) {$result = json_decode($response->getBody()->getContents(), true);echo '<pre>';var_dump($list[$k]['name']);}}