这个业务初始化,帮我看看,我这样初始化 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()
来进行操作,这样可以吗
我无法理解 那你为啥不直接使用单例模式呢
我是想问是不是这样用的,用法正不正确
对,单例模式