12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- package config
- import (
- "crypto/tls"
- "net"
- "net/http"
- "os"
- "time"
- "github.com/elastic/go-elasticsearch/v8"
- "github.com/sirupsen/logrus"
- )
- var (
- Elastic *elasticsearch.Client
- )
- func ExistElastic() bool {
- if Elastic == nil {
- return false
- }
- return true
- }
- func GetElastic() *elasticsearch.Client {
- if Elastic == nil {
- panic("elastic没有初始化")
- }
- return Elastic
- }
- func InitElastic() {
- if os.Getenv("ELASTIC_ADDR") == "" {
- logrus.Warn("没有配置elastic,跳过初始化...")
- return
- }
- nt := &net.Dialer{Timeout: time.Second * 10}
- client, err := elasticsearch.NewClient(elasticsearch.Config{
- Addresses: []string{os.Getenv("ELASTIC_ADDR")},
- Username: os.Getenv("ELASTIC_USERNAME"),
- Password: os.Getenv("ELASTIC_PASSWORD"),
- Transport: &http.Transport{
- MaxIdleConnsPerHost: 10,
- ResponseHeaderTimeout: time.Second * 10,
- DialContext: nt.DialContext,
- TLSClientConfig: &tls.Config{
- MinVersion: tls.VersionTLS12,
- InsecureSkipVerify: true, //添加这一行跳过验证
- },
- },
- })
- if err != nil {
- logrus.Warnf("连接elastic[%v]不成功, err:%+v", os.Getenv("ELASTIC_ADDR"), err)
- return
- }
- if _, err = client.Info(); err != nil {
- logrus.Warnf("连接elastic[%v]不成功, getting response err:%+v", os.Getenv("ELASTIC_ADDR"), err)
- return
- }
- Elastic = client
- }
|