本文介绍了使用guzzle执行批处理请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在一个项目中,我需要使用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.
the endpoint looks like this: https://jsonplaceholder.typicode.com/posts/X
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?
use GuzzleHttp\Client;
public function fetchPosts () {
$client = new Client();
$posts = [];
for ($i=1; $i < 2000; $i++) {
$response = $client->post('https://jsonplaceholder.typicode.com/posts/' . $i);
array_push($posts, $response->getBody());
}
return $posts;
}
解决方案
You can try this,
public function fetchBooks()
{
$results = [];
$client = new \GuzzleHttp\Client([
'base_uri' => 'https://jsonplaceholder.typicode.com'
]);
$headers = [
'Content-type' => 'application/json; charset=UTF-8'
];
$requests = function () use ($client,$headers) {
for ($i = 1; $i < 7; $i++) {
yield function() use ($client, $headers,$i) {
return $client->postAsync('/posts',[
'headers' => $headers,
'json' => [
'title' => 'foonov2020',
'body' => 'barfoonov2020',
'userId' => $i,
]
]);
};
}
};
$pool = new \GuzzleHttp\Pool($client, $requests(),[
'concurrency' => 5,
'fulfilled' => function (Response $response, $index) use (&$results) {
$results[] = json_decode($response->getBody(), true);
},
'rejected' => function (\GuzzleHttp\Exception\RequestException $reason, $index) {
throw new \Exception(print_r($reason->getBody()));
},
]);
$pool->promise()->wait();
return response()->json($results);
}
It will give you output,
这篇关于使用guzzle执行批处理请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!