代码链接ES报超时问题

来源:6-6 Go操作ES的一些技巧和注意事项(一)

404_

2023-02-02

我使用的是老师给的docker文件在虚拟机上跑的ES集群,kibana访问没有问题。
但是我的代码在创建索引和搜索的时候全部报超时。

package main

import (
	"context"
	"crypto/tls"
	"fmt"
	"github.com/olivere/elastic/v7"
	"net/http"
)

var indexCreateJson = `
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0
  },
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword",
        "doc_values": false,
        "norms": false,
        "similarity": "boolean"
      },
      "name": {
        "type": "text"
      },
        "price": {
        "type": "double"
      },
      "last_month_sales": {
        "type": "long"
      },
      "favorites": {
        "type": "long"
      },
      "year":{
        "type": "short"
      }
    }
  }
}
`

func main() {
	urls := []string{"https://192.168.2.48:9200"}
	client, err := elastic.NewClient(elastic.SetURL(urls...), elastic.SetBasicAuth("elastic", "elastic"), elastic.SetScheme("https"),
		elastic.SetHttpClient(&http.Client{
			Transport: &http.Transport{
				DisableKeepAlives: true,
				TLSClientConfig:   &tls.Config{InsecureSkipVerify: true},
			},
		}),
		elastic.SetHealthcheck(false),
	)
	if err != nil {
		panic(err)
	}
	fmt.Println(client)

	// 创建索引
	res, err := client.CreateIndex("zsy-cs").BodyJson(indexCreateJson).Do(context.Background())
	//res, err := client.Search().Index("goods").Pretty(true).IgnoreUnavailable(true).Do(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Println(res)
}

打印的输出结果是:

https://172.18.0.3:9200 [dead=false,failures=0,deadSince=<nil>], https://172.18.0.5:9200 [dead=false,failures=0,deadSince=<nil>], https://172.18.0.4:9200 [dead=false,failures=0,deadSince=<nil>]
panic: Put "https://172.18.0.3:9200/zsy-cs": dial tcp 172.18.0.3:9200: connect: operation timed out

能显示出集群中es节点的信息,证明ES集群时没有问题的。就是 client.CreateIndex() 和 client.Search()这出了问题.

我现在遇到的问题是:调用elastic.NewClient 生成了 client对象,但是这个client对象在调用其他方法的时候都是会超时。不知道哪出了问题

写回答

1回答

少林码僧

2023-02-03

在 6-6 Go操作ES的一些技巧和注意事项(一)这小节视频中有介绍过一个参数  SetSniff,用来控制是否开启嗅探模式。

默认会开启,开启后sdk将会获取ES的全部节点ip用来连接,我们是不建议开启的,主要原因是生成环境一般会设置专门的协调节点,让请求全部打到协调节点上。这里出问题的原因就在这个参数上,因为docker部署的的ES节点ip是docker容器的ip,对宿主机是不可见的,而docker的ES是服务只有第一个节点暴露9200端口给宿主机的,所以通过宿主机ip能访问到第一个es节点,通过容器内的ip访问则会出现超时的情况。

具体代码见:

https://gitee.com/phper95/pkg/blob/master/es/client.go

核心代码如下:

//开启Sniff,SDK会定期(默认15分钟一次)嗅探集群中全部节点,将全部节点都加入到连接列表中
//后续新增的节点也会自动加入到可连接列表,但实际生产中我们可能会设置专门的协调节点,所以默认不开启嗅探
options = append(options, elastic.SetSniff(false))


0
0

海量数据高并发场景,构建Go+ES8企业级搜索微服务

全新 ES8 配合技术组件,实现高性能搜索

267 学习 · 54 问题

查看课程