Using guzzle to perform batch requests

一世执手 提交于 2020-12-15 03:48:20

问题


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;
}

回答1:


NOTE:

The answer here is similar to question I suggested but it contains a proof to help the question asker, please inform me if you feel like the answer is not needed here, I will remove it, but I would prefer not the answer to be downvoted for that purpose.

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,



来源:https://stackoverflow.com/questions/64919582/using-guzzle-to-perform-batch-requests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!