elastic.go 885 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package es
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/olivere/elastic"
  6. "iot_manager_service/config"
  7. "log"
  8. "os"
  9. "time"
  10. )
  11. type es struct {
  12. }
  13. var Es es
  14. var Client *elastic.Client
  15. func (e *es) InitES() {
  16. errLog := log.New(os.Stdout, "APP", log.LstdFlags)
  17. url := config.Instance().Es.URL
  18. client, err := elastic.NewClient(elastic.SetErrorLog(errLog))
  19. elastic.SetURL(url)
  20. if err != nil {
  21. //todo 初始化错误处理
  22. panic(err)
  23. }
  24. Client = client
  25. //启动定时删除
  26. go delTicker()
  27. }
  28. // 定时器
  29. func delTicker() {
  30. ticker := time.Tick(15 * 24 * time.Hour)
  31. for range ticker {
  32. indexName := time.Now().Add(-15 * 24 * time.Hour).Format("2006-01-02")
  33. delIndex(indexName)
  34. }
  35. }
  36. // DelIndex 删除索引
  37. func delIndex(indexName string) {
  38. res, err := Client.DeleteIndex(indexName).Do(context.Background())
  39. if err != nil {
  40. fmt.Printf("res:%v\nerror:%v\n", res, err)
  41. }
  42. }