esQuery.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package service
  2. import (
  3. "context"
  4. "esproxy/internal/consts"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/os/gcron"
  7. "github.com/gogf/gf/v2/util/gconv"
  8. )
  9. var (
  10. EsStatusQuery *esStatusQuery = &esStatusQuery{}
  11. )
  12. type (
  13. esStatusQuery struct {
  14. }
  15. ThreadPool struct {
  16. ThreadPool struct {
  17. Search struct {
  18. Threads int `json:"threads"`
  19. Queue int `json:"queue"`
  20. Active int `json:"active"`
  21. Rejected int `json:"rejected"`
  22. Largest int `json:"largest"`
  23. Completed int `json:"completed"`
  24. } `json:"search"`
  25. } `json:"thread_pool"`
  26. }
  27. ResponseStruct struct {
  28. Nodes map[string]ThreadPool `json:"nodes"`
  29. }
  30. )
  31. // GetEsStatus 查询获取Es状态
  32. func (*esStatusQuery) GetEsStatus(ctx context.Context) (esStatus consts.EsStatus) {
  33. esStatus = consts.EsStatus_block
  34. client := g.Client()
  35. username, password := g.Cfg().MustGet(ctx, "elasticSearch.queryState.elasticsearch.username").String(), g.Cfg().MustGet(ctx, "elasticSearch.queryState.elasticsearch.password").String()
  36. if username != "" || password != "" {
  37. client.SetBasicAuth(username, password)
  38. }
  39. r, err := client.Get(ctx, g.Cfg().MustGet(ctx, "elasticSearch.queryState.curlAddr").String())
  40. if err != nil {
  41. g.Log().Errorf(ctx, "请求异常 err:%v", err)
  42. return
  43. }
  44. defer r.Close()
  45. rs := &ResponseStruct{}
  46. if err := gconv.Struct(r.ReadAllString(), rs); err != nil || rs == nil || len(rs.Nodes) == 0 {
  47. g.Log().Errorf(ctx, "请求结果异常 err:%v", err)
  48. return
  49. }
  50. maxQueue, maxActive := 0, 0
  51. for _, val := range rs.Nodes {
  52. if val.ThreadPool.Search.Queue > maxQueue {
  53. maxQueue = val.ThreadPool.Search.Queue
  54. }
  55. if val.ThreadPool.Search.Active > maxActive {
  56. maxActive = val.ThreadPool.Search.Active
  57. }
  58. }
  59. if maxQueue == 0 && maxActive < 6 {
  60. esStatus = consts.EsStatus_Free
  61. } else if maxQueue < 6 && maxActive < 10 {
  62. esStatus = consts.EsStatus_Busy
  63. }
  64. g.Log().Debugf(ctx, "now maxQueue:%d maxActive:%d finalStatus:%d", maxQueue, maxActive, esStatus)
  65. return
  66. }
  67. // GetEsStatusRunning es状态持续查询
  68. func (*esStatusQuery) GetEsStatusRunning(cron string, job func(ctx context.Context)) error {
  69. e, err := gcron.New().Add(context.Background(), cron, job)
  70. if err != nil {
  71. return err
  72. }
  73. e.Start()
  74. select {}
  75. }