前言
环境
项目 | 版本 |
PHP | v8.0 |
Hyperf | v3.0 |
Elasticsearch | v8.0 |
elasticsearch-php | v7.17.1 |
服务地址
使用nginx将 服务器本地9200端口的elasticsearch服务映射到es.test.cn/es/
![](https://img-blog.csdnimg.cn/img_convert/2c79513e084849a08796a7f164cb6619.png)
起因
代码
在hyperf中使用elasticsearch-php库连接elasticsearch服务,代码如下:
#[GetMapping(path: "ela")]
public function ela () {
$host = "http://es.test.cn/es/";
$builder = $this->container->get(ClientBuilderFactory::class)->create();
$client = $builder
->setHosts([$host])
->setBasicAuthentication("username", "pwd")
->build();
$info = $client->info();
return $info;
}
接口返回
![](https://img-blog.csdnimg.cn/img_convert/6e1d22de38c24b109ac15592e51e1327.png)
服务端报错信息
[ERROR] No alive nodes found in your cluster[64] in /data/project/vendor/elasticsearch/elasticsearch/src/Elasticsearch/ConnectionPool/StaticNoPingConnectionPool.php
![](https://img-blog.csdnimg.cn/img_convert/c81141b220d449f3b07655ed4a6aa9ce.png)
分析
官方文档
按照elasticsearch官方的文档,host可以使用以下类型
IP + 端口
仅IP
域名 + 端口
仅域名
Https 本地地址
Https IP + 端口
![](https://img-blog.csdnimg.cn/img_convert/9fea8aa853bb48b19db24aff00699833.png)
库源码
查看elasticsearch-php库源码,发现在解析host时,如果没有端口会默认加上9200端口,位置如下:
vendor\elasticsearch\elasticsearch\src\Elasticsearch\ClientBuilder.php
![](https://img-blog.csdnimg.cn/img_convert/12646a231c814987a18dfb73cd78c668.png)
解决
代码
所以这个问题的解决就是在域名后加上相应nginx映射端口,我是默认80端口:es.test.cn:80,代码如下:
#[GetMapping(path: "ela")]
public function ela () {
$host = "http://es.test.cn:80/es/";
$builder = $this->container->get(ClientBuilderFactory::class)->create();
$client = $builder
->setHosts([$host])
->setBasicAuthentication("username", "pwd")
->build();
$info = $client->info();
return $info;
}
接口返回
如下图,正确返回服务信息:
![](https://img-blog.csdnimg.cn/img_convert/a03956319bb14f4fbc5a25fa3cea78ae.png)