- 好处
在单线程环境下,执行 n 个请求的时间等于 n 个请求时间相加。在 multi interface 功能下,执行 n 个请求的时间等于最慢的一个请求时间。 - future 模式实现异步
$client = ClientBuilder::create()->build();
$futures = [];
for ($i = 0; $i < 1000; $i++) {
$params = [
'index' => 'test',
'type' => 'test',
'id' => $i,
'client' => [
'future' => 'lazy'
]
];
$futures[] = $client->get($params); //queue up the request
//这里会返回一个 future 对象,而不是真正的响应数据。future 对象是待处理对象,它看起来就像是个占位符。你可以把 future 对象当成是普通对象在代码中传递使用。
}
//wait() forces future resolution and will execute the underlying curl batch
//如果你想强制解析 future 对象,但又不立刻获取响应数据。你可以用 future 对象的 wait() 方法来强制解析:
$futures[999]->wait();
$handlerParams = [
'max_handles' => 500
];
$defaultHandler = ClientBuilder::defaultHandler($handlerParams);
$client = ClientBuilder::create()
->setHandler($defaultHandler)
->build();