31、Hyperf 3 快速使用 - Hyperf 3 协程 Elasticsearch 客户端的使用

作者: 温新

分类: 【Hyperf 3 基础系列】

阅读: 430

时间: 2023-04-25 16:08:28

hi,我是温新,一名 PHPer

Hypref 版本:Hyperf 3.0

学习目标:掌握 Hyperf 3 协程 Elasticsearch 客户端的使用

hyperf/elasticsearch 主要是对 elasticsearch-php 进行了客户端创建的工厂类封装,elasticsearch-php 默认使用 Guzzle Ring 客户端。Hyperf 中实现了协程版本的 Handler,因此可以直接使用 Hyperf\Elasticsearch\ClientBuilderFactory 创建一个新的 Builder

在使用 ES 客户端之前,确保服务器已安装了 ES 软件。

第一步:安装组件

composer require hyperf/elasticsearch

第二步:使用 ES

方式一:使用 ClientBuilderFactory 创建客户端

<?php

namespace App\Controller\Test;

use Hyperf\Contract\ContainerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Elasticsearch\ClientBuilderFactory;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;

#[Controller]
class EsClientController
{
    #[Inject]
    protected ContainerInterface $container;

    #[GetMapping('/es/index')]
    public function index()
    {
        $builder = $this->container->get(ClientBuilderFactory::class)->create();
        $client  = $builder->setHosts(['http://192.168.31.90:9200'])->build();

        $info    = $client->info();
        var_dump($info);
        
        $params = [
            // 索引名称
            'index'=>'ziruchu_posts_test122',
            'body' => [
                // settings 可以为空数组,但不能不写
                "settings" => [
                    // 分片数量
                    'number_of_shards'   => 1,
                    // 副本数量
                    'number_of_replicas' => 0,
                ]
            ],
        ];

        return $client->indices()->create($params);
    }
}

postman 测试

get http://192.168.31.90:9501/es/index

{
    "acknowledged": true,
    "shards_acknowledged": true,
    "index": "ziruchu_posts_test122"
}

方式二:自行创建客户端

<?php

use Elasticsearch\ClientBuilder;
use Hyperf\Guzzle\RingPHP\PoolHandler;

#[GetMapping('/es/add')]
public function add()
{
    $builder = ClientBuilder::create();
    if (\Swoole\Coroutine::getCid() > 0) {
        $handler = make(PoolHandler::class, [
            'option' => [
                'max_connections' => 50,
            ],
        ]);
        $builder->setHandler($handler);
    }
    
    $client = $builder->setHosts(['http://192.168.31.90:9200'])->build();
    return $client->info();
}

postman 测试结果

get http://192.168.31.90:9501/es/add

{
    "name": "localhost",
    "cluster_name": "elasticsearch",
    "cluster_uuid": "VwN1jXPtSxWtWNfokHdElw",
    "version": {
        "number": "8.6.0",
        "build_flavor": "default",
        "build_type": "tar",
        "build_hash": "f67ef2df40237445caa70e2fef79471cc608d70d",
        "build_date": "2023-01-04T09:35:21.782467981Z",
        "build_snapshot": false,
        "lucene_version": "9.4.2",
        "minimum_wire_compatibility_version": "7.17.0",
        "minimum_index_compatibility_version": "7.0.0"
    },
    "tagline": "You Know, for Search"
}

关于客户端到这里就结束了。剩下 ConsulJetNacos 等,等后续使用到再进行编写。

我是温新,本篇文章到此结束。

请登录后再评论