main.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package main
  2. import (
  3. "context"
  4. _ "github.com/gogf/gf/contrib/nosql/redis/v2"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/os/gcron"
  7. "github.com/gogf/gf/v2/os/gctx"
  8. "github.com/gogf/gf/v2/util/gconv"
  9. )
  10. type ResponseStruct struct {
  11. Nodes map[string]ThreadPool `json:"nodes"`
  12. }
  13. type ThreadPool struct {
  14. ThreadPool struct {
  15. Search struct {
  16. Threads int `json:"threads"`
  17. Queue int `json:"queue"`
  18. Active int `json:"active"`
  19. Rejected int `json:"rejected"`
  20. Largest int `json:"largest"`
  21. Completed int `json:"completed"`
  22. } `json:"search"`
  23. } `json:"thread_pool"`
  24. }
  25. func job(ctx context.Context) {
  26. client := g.Client()
  27. username, password := g.Cfg().MustGet(ctx, "elasticsearch.username").String(), g.Cfg().MustGet(ctx, "elasticsearch.password").String()
  28. if username != "" || password != "" {
  29. client.SetBasicAuth(username, password)
  30. }
  31. r, err := client.Get(ctx, g.Cfg().MustGet(ctx, "curlAddr").String())
  32. if err != nil {
  33. g.Log().Errorf(ctx, "请求异常 err:%v", err)
  34. return
  35. }
  36. defer r.Close()
  37. rs := &ResponseStruct{}
  38. if err := gconv.Struct(r.ReadAllString(), rs); err != nil || rs == nil || len(rs.Nodes) == 0 {
  39. g.Log().Errorf(ctx, "请求结果异常 err:%v", err)
  40. return
  41. }
  42. maxQueue, maxActive, finalStatus := 0, 0, 2
  43. for _, val := range rs.Nodes {
  44. if val.ThreadPool.Search.Queue > maxQueue {
  45. maxQueue = val.ThreadPool.Search.Queue
  46. }
  47. if val.ThreadPool.Search.Active > maxActive {
  48. maxActive = val.ThreadPool.Search.Active
  49. }
  50. }
  51. if maxQueue == 0 && maxActive < 6 {
  52. finalStatus = 0
  53. } else if maxQueue < 6 && maxActive < 10 {
  54. finalStatus = 1
  55. }
  56. g.Log().Debugf(ctx, "now maxQueue:%d maxActive:%d finalStatus:%d", maxQueue, maxActive, finalStatus)
  57. _, _ = g.Redis().Set(ctx, "es_status", finalStatus)
  58. }
  59. func main() {
  60. ctx := gctx.New()
  61. e, err := gcron.New().Add(ctx, g.Cfg().MustGet(ctx, "cron").String(), job)
  62. if err != nil {
  63. panic(err)
  64. }
  65. e.Start()
  66. select {}
  67. }