问题描述
我正在一个项目中,我需要使用Guzzle向端点执行2000个异步请求,并且每次需要更改url参数中的ID.
i'm working on a project where i need to perform 2000 asynchronous requests using Guzzle to an endpoint and each time i need to change the ID in the url param.
终结点看起来像这样: http://example.com/api/book?id = X
the endpoint looks like this: http://example.com/api/book?id=X
我试图使用for循环来做到这一点,唯一的问题是它不是异步的.做这样的任务更有效的方法是什么?
I tried to use a for loop to do that the only issue is that it's not asynchronous. what's the more efficient way to do such task?
public function fetchBooks () {
$client = new Client();
$responses = [];
for ($i=1; $i < 2000; $i++) {
$response = $client->post('https://example.com/api/book?id=' . $i);
array_push($responses, json_decode($response->getBody(), true));
}
return $responses;
}
推荐答案
@wasserholz答案仍在使用2 array_push(占用更多内存,从而使api变慢,因此改用[])是正确的,&可以减少一个array_push.
@wasserholz answer is correct still using 2 array_push(takes more memory thus making api slower, so instead use []), & one array_push can be reduced.
use GuzzleHttp\Psr7\Response;
$responses = [];
$client = new \GuzzleHttp\Client([
'base_uri' => 'https://example.com'
]);
$requests = function () use ($client) {
for ($i = 0; $i < 2000; $i++) {
yield function() use ($client,$i) {
return $client->postAsync('/api/book?id=' . $i);
};
}
};
$pool = new \GuzzleHttp\Pool($client, $requests(),[
'concurrency' => 5,
'fulfilled' => function (Response $response, $index) use (&$responses) {
// if ($response->getStatusCode() == 200) {
$responses[] = json_decode($response->getBody(), true);
// }
print_r($responses); // this will have all the responses
},
'rejected' => function (\GuzzleHttp\Exception\RequestException $reason, $index) {
// dd($reason); //you can store it in laravel logs
},
]);
$pool->promise()->wait();
return response()->json($responses);
这篇关于使用Guzzle执行批处理请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!