【问题标题】:Using guzzle to perform batch requests使用 guzzle 执行批处理请求
【发布时间】:2021-03-03 06:51:16
【问题描述】:

我正在做一个项目,我需要使用 Guzzle 对端点执行 2000 个异步请求,并且每次我需要更改 url 中的 ID。

端点如下所示:https://jsonplaceholder.typicode.com/posts/X

我尝试使用 for 循环来做到这一点,唯一的问题是它不是异步的。执行此类任务的更有效方法是什么?

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

【问题讨论】:

标签: php laravel guzzle


【解决方案1】:

你可以试试这个,

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

它会给你输出,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 2018-08-10
    • 2023-02-09
    • 2013-09-19
    相关资源
    最近更新 更多