<?php
require 'vendor/autoload.php';
use Monolog\Logger;
use Elasticsearch\ClientBuilder;
$logger = new Logger('name');
$logger->pushHandler(new \Monolog\Handler\StreamHandler('future.log'));
// 更改批量值
// 默認的批量值爲 100 個,意味着在客戶端強制 future 對象解析前(執行 curl_multi 調用),隊列可以容納 100 個請求。批量值可以更改,取決於你的需求。
// 批量值的調整是通過配置 HTTP handler 時設置 max_handles 參數來實現
$handlerParams = [
'max_handles' => 500
];
$defaultHandler = ClientBuilder::defaultHandler($handlerParams);
$client = ClientBuilder::create()->setLogger($logger)->setHandler($defaultHandler)->build();
// 使用 Future 模式(異步模式)
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' =>1,
'client' => [
'future' => 'lazy'
]
];
// 返回一個future對象,future對象是待處理對象,類似佔位符
//$future = $client->get($params);
//$doc = $future['_source'];
//print_r($doc);
// 上面的設置會更改批量發送數量爲 500。注意:不管隊列數量是否爲最大批量值,強制解析 future 對象都會引起底層的 curl 執行批量請求操作。
// 在如下的示例中,只有 499 個對象加入隊列,但最後的 future 對象被解析會引起強制發送批量請求:
$futures = [];
for ($i = 1; $i <499; $i++){
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => $i,
'client' => [
'future' => 'lazy'
]
];
$futures[] = $client->get($params);
}
// future 對象可以用迭代關聯數組的方式解析特定的值(輪流解析未解析的請求和值)
//foreach ($futures as $future) {
// print_r($future['_source']);
//}
// 如果你想強制解析 future 對象,但又不立刻獲取響應數據。可以用 future 對象的 wait() 方法來強制解析
// print_r($futures[497]->wait());
// 各種批量執行
// 隊列裏面允許存在各種請求。比如,你可以把 get 請求、index 請求和 search 請求放到隊列裏面:
$futures = [];
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 1,
'client' => [
'future' => 'lazy'
]
];
$futures['getRequest'] = $client->get($params);
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 2,
'body' => [
'field' => 'name'
],
'client' => [
'future' => 'lazy'
]
];
$futures['indexRequest'] = $client->index($params);
$params = [
'index' => 'my_index',
'type' => 'my_type',
'body' => [
'query' => [
'match' => [
'field' => 'name'
]
]
],
'client' => [
'future' => 'lazy'
]
];
$futures['searchRequest'] = $client->search($params);
$doc = $futures['getRequest']['_source'];
print_r($doc);
$searchResults = $futures['searchRequest']['hits'];
print_r($searchResults);
4.elasticsearch-php中future模式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.