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)
希望其他人会跳进去让我知道是否有更正确的方法来实现我的目标,但是在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)
| 归档时间: |
|
| 查看次数: |
4952 次 |
| 最近记录: |