elasticsearch.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package config
  2. import (
  3. "crypto/tls"
  4. "net"
  5. "net/http"
  6. "os"
  7. "time"
  8. "github.com/elastic/go-elasticsearch/v8"
  9. "github.com/sirupsen/logrus"
  10. )
  11. var (
  12. Elastic *elasticsearch.Client
  13. )
  14. func ExistElastic() bool {
  15. if Elastic == nil {
  16. return false
  17. }
  18. return true
  19. }
  20. func GetElastic() *elasticsearch.Client {
  21. if Elastic == nil {
  22. panic("elastic没有初始化")
  23. }
  24. return Elastic
  25. }
  26. func InitElastic() {
  27. if os.Getenv("ELASTIC_ADDR") == "" {
  28. logrus.Warn("没有配置elastic,跳过初始化...")
  29. return
  30. }
  31. nt := &net.Dialer{Timeout: time.Second * 10}
  32. client, err := elasticsearch.NewClient(elasticsearch.Config{
  33. Addresses: []string{os.Getenv("ELASTIC_ADDR")},
  34. Username: os.Getenv("ELASTIC_USERNAME"),
  35. Password: os.Getenv("ELASTIC_PASSWORD"),
  36. Transport: &http.Transport{
  37. MaxIdleConnsPerHost: 10,
  38. ResponseHeaderTimeout: time.Second * 10,
  39. DialContext: nt.DialContext,
  40. TLSClientConfig: &tls.Config{
  41. MinVersion: tls.VersionTLS12,
  42. InsecureSkipVerify: true, //添加这一行跳过验证
  43. },
  44. },
  45. })
  46. if err != nil {
  47. logrus.Warnf("连接elastic[%v]不成功, err:%+v", os.Getenv("ELASTIC_ADDR"), err)
  48. return
  49. }
  50. if _, err = client.Info(); err != nil {
  51. logrus.Warnf("连接elastic[%v]不成功, getting response err:%+v", os.Getenv("ELASTIC_ADDR"), err)
  52. return
  53. }
  54. Elastic = client
  55. }