service.query.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package query
  2. import (
  3. "fmt"
  4. "go-admin/app/observe/models"
  5. "time"
  6. "github.com/pkg/errors"
  7. )
  8. type Service struct {
  9. Query
  10. }
  11. func NewService() Service {
  12. q := Query{}
  13. q.Init()
  14. return Service{q}
  15. }
  16. func (q Service) HasNode(appAlias string, serviceName string) (bool, error) {
  17. key := fmt.Sprintf("observe__service_node_sets_%s", appAlias)
  18. dur, _ := q.rdb.TTL(key).Result()
  19. if dur == -1 { // 如果没有设置ttl,则设置为1分钟, time.Duration类型可以与数字比较, 因为它本身就是数字
  20. q.rdb.Expire(key, time.Minute)
  21. }
  22. has, err := q.rdb.SIsMember(key, serviceName).Result()
  23. if err != nil || !has { // 如果出错或不存在,去库里查找
  24. cnt := int64(0)
  25. res := q.db.Model(&models.ServiceNode{}).Where("app_alias=? and service_name=?", appAlias, serviceName).Count(&cnt)
  26. if res.Error != nil {
  27. return false, errors.Wrap(res.Error, "查询服务node是否存在失败")
  28. }
  29. if cnt == 0 {
  30. return false, nil
  31. }
  32. q.rdb.SAdd(key, serviceName)
  33. }
  34. return true, nil
  35. }
  36. func (q Service) HasEdge(appAlias, source, target string) (bool, error) {
  37. key := fmt.Sprintf("observe__service_edge_sets_%s", appAlias)
  38. dur, _ := q.rdb.TTL(key).Result()
  39. if dur == -1 { // 如果没有设置ttl,则设置为1分钟, time.Duration类型可以与数字比较, 因为它本身就是数字
  40. q.rdb.Expire(key, time.Minute)
  41. }
  42. st := fmt.Sprintf("%s_%s", source, target)
  43. has, err := q.rdb.SIsMember(key, st).Result()
  44. if err != nil || !has {
  45. cnt := int64(0)
  46. res := q.db.Model(&models.ServiceEdge{}).Where("app_alias=? and source=? and target=?", appAlias, source, target).Count(&cnt)
  47. if res.Error != nil {
  48. return false, errors.Wrap(res.Error, "查询服务edge是否存在失败")
  49. }
  50. if cnt == 0 {
  51. return false, nil
  52. }
  53. q.rdb.SAdd(key, st)
  54. }
  55. return true, nil
  56. }
  57. func (q Service) ServiceMap(appAlias string) (map[string]string, error) {
  58. svcList := []struct {
  59. Name string
  60. ServiceName string
  61. }{}
  62. if err := q.db.Model(&models.ServiceNode{}).Select("name, service_name").Where("app_alias", appAlias).Find(&svcList).Error; err != nil {
  63. return map[string]string{}, errors.Wrap(err, "查询服务数据失败")
  64. }
  65. svcMap := map[string]string{}
  66. for _, svc := range svcList {
  67. name := svc.Name
  68. if name == "" {
  69. name = svc.ServiceName
  70. }
  71. svcMap[svc.ServiceName] = name
  72. }
  73. return svcMap, nil
  74. }