业务初始化 初始Elasticsearch

小叽叽叽叽

问题描述

这个业务初始化,帮我看看,我这样初始化 Elasticsearch 对不对

MemReport.php

use app\service\Elasticsearch;

use Elastic\Elasticsearch\Client;
use Elastic\Elasticsearch\ClientBuilder;
use Webman\Bootstrap;

class MemReport implements Bootstrap
{
    static $client;

    public static function start($worker)
    {
        // Is it console environment ?
        $is_console = !$worker;
        if ($is_console) {
            // If you do not want to execute this in console, just return.
            return;
        }
        Elasticsearch::init();

    }

}

Elasticsearch.php


namespace app\service;

use Elastic\Elasticsearch\ClientBuilder;

class Elasticsearch
{
    static $client;

    static function init()
    {
        $hosts = [
            'host' => 'http://host.docker.internal:9200',    // 只有 host 是必须的
        ];
      self::$client =ClientBuilder::create()->setHosts($hosts)->setRetries(2)->build();
    }

    public static function client(): \Elastic\Elasticsearch\Client
    {
        return self::$client;
    }

}

然后我直接调用 Elasticsearch::client() 来进行操作,这样可以吗

675 1 0
1个回答

小Z先生

我无法理解 那你为啥不直接使用单例模式呢

×
🔝