php多进程编程spatie/async
有些业务场景可能需要同时调用三方接口 50 次甚至更多
使用多进程,提高接口响应效率
一。安装扩展包#
安装扩展包 composer require spatie/async
先看效果 减少了 47 秒的响应时间,这样就能满足业务需求
二。对于多次 api 请求业务可以异步编程,但是对于哪些密集型计算的同步耗时更短。看使用场景#
代码如下
<?php
require './vendor/autoload.php';
use Spatie\Async\Pool;
use GuzzleHttp\Client;
$stime = microtime(true); //获取程序开始执行的时间
echo "初始: " . round(memory_get_usage() / 1024 / 1024, 2) . ' MB' . "\n";
// 业务逻辑
$d = []; //存储数据使用
//100次curl 请求
$pool = Pool::create();
$client = new Client();
foreach (range(1, 99) as $i) {
$pool[] = async(function () use ($i, $client) {
$response = $client->get('https://www.xxx.cn/api/getTemplateLogInfo', [
]);
$output = $response->getBody()->getContents();
$d[] = $output;
return $output;
})->then(function ($output) use (&$d) {
$d[] = $output;
});
}
await($pool);
//foreach (range(1, 99) as $i) {
//
// $j = curlGet();
//
// $d[] = $j;
//
//}
$etime = microtime(true);//获取程序执行结束的时间
$total = $etime - $stime; //计算差值
echo "[页面执行时间:{$total} ]秒" . "\n";
echo "使用: " . round(memory_get_usage() / 1024 / 1024, 2) . ' MB' . "\n";// 获取运行时间 和 占用内存
var_dump($d);
function curlGet()
{
$client = new Client();
$response = $client->get('https://www.xxx.cn/api/getTemplateLogInfo', [
]);
$content = $response->getBody()->getContents();
return $content;
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: