我的目标是使用Guzzle 6创建一个 PUT json 数据的异步请求池。然后监控每个 $promise 成功/失败。
为了与我的 POOL 代码示例进行比较,以下对 $client->request() 的单个请求将第三个参数转换为编码的 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']]);
在接收 API 端点上,我可以通过执行以下操作从上面的单个请求中读取 json:
$json = file_get_contents('php://input');
$json = json_decode($json, true);
使用文档中的并发请求示例,为了使用 new Request() 创建异步请求池,我希望可以使用相同的参数(方法、url 端点、json 标志),就像在单个 $client->request( ) 上面的例子。但是,yield new Request()
不处理 3rd json 参数,如$client->request()
. 从我的池代码调用正确设置 json 和内容类型的正确 Guzzle 函数是什么?或者有没有更好的方法来创建大量异步请求并监控它们的结果?
池代码示例:
$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.