使用Guzzle 6创建异步json请求池以发送到API端点的正确方法是什么?

Zel*_*elf 6 php json asynchronous guzzle guzzle6

我的目标是使用Guzzle 6创建一个PUT json数据的异步请求池.然后监控每个$ promise成功/失败.

为了与我的POOL代码示例进行比较,对$ client-> request()的以下单个请求将第3个参数转换为编码的json,然后添加Content-type:application/json.**

$client = new Client([
    'base_uri' => BASE_URL . 'test/async/', // Base URI is used with relative requests
    'timeout'  => 0, // 0 no timeout for operations and watching Promises
]);

$response = $client->request('PUT', 'cool', ['json' => ['foo' => 'bar']]);
Run Code Online (Sandbox Code Playgroud)

在接收API端点上,我可以通过执行以下操作从上面的单个请求中读取json:

$json = file_get_contents('php://input');
$json = json_decode($json, true);
Run Code Online (Sandbox Code Playgroud)

使用文档中并发请求示例,为了使用新的Request()创建异步请求池,我希望可以使用相同的参数(方法,url端点,json标志),就像在单个$ client->请求中一样( )上面的例子.但是,yield new Request()不处理第3个json参数$client->request().从我的池代码调用正确设置json和内容类型的Guzzle函数是什么?或者是否有更好的方法来创建大量异步请求并监视其结果?

POOL代码示例:

$this->asyncRequests = [
    [
        'endpoint' => 'cool'
    ],
    [
        'endpoint' => 'awesome'
    ],
    [
        'endpoint' => 'crazy'
    ],
    [
        'endpoint' => 'weird'
    ]
];

$client = new Client([
    'base_uri' => BASE_URL, // Base URI is used with relative requests
    'timeout'  => 0 // 0 no timeout for operations and watching Promises
]);

$requests = function ($asyncRequests) {
    $uri = BASE_URL . 'test/async/';

    foreach ($asyncRequests as $key => $data) {
        yield new Request('PUT', "{$uri}{$data['endpoint']}", ['json' => ['foo' => 'bar']]);
    }
};

$pool = new Pool($client, $requests($this->asyncRequests), [
    'concurrency' => 10,
    'fulfilled' => function ($response, $index) {
        $this->handleSuccessPromises($response, $index);
    },
    'rejected' => function ($reason, $index) {
        $this->handleFailurePromises($reason, $index);
    },
]);

$promise = $pool->promise(); // Initiate the transfers and create a promise

$promise->wait(); // Force the pool of requests to complete.
Run Code Online (Sandbox Code Playgroud)

Zel*_*elf 9

希望其他人会跳进去让我知道是否有更正确的方法来实现我的目标,但是在Guzzle的引擎盖下我意识到新的Request()的第3个参数是寻找标题信息,第4个参数正在寻找一个身体.所以下面的代码使用池:

foreach ($syncRequests as $key => $headers) {
    yield new Request('PUT', "{$uri}{$headers['endpoint']}", ['Content-type' => 'application/json'], json_encode(['json' => ['nonce' => $headers['json']]]));
}
Run Code Online (Sandbox Code Playgroud)

也在Psr7\Request的文档中 在此输入图像描述

  • 天啊,花了多长时间才意识到 body 和 json 应该在第 4 个参数中!感谢您如此清楚地解释这一点! (2认同)