package query import ( "fmt" "go-admin/app/observe/models" "time" "github.com/pkg/errors" ) type Service struct { Query } func NewService() Service { q := Query{} q.Init() return Service{q} } func (q Service) HasNode(appAlias string, serviceName string) (bool, error) { key := fmt.Sprintf("observe__service_node_sets_%s", appAlias) dur, _ := q.rdb.TTL(key).Result() if dur == -1 { // 如果没有设置ttl,则设置为1分钟, time.Duration类型可以与数字比较, 因为它本身就是数字 q.rdb.Expire(key, time.Minute) } has, err := q.rdb.SIsMember(key, serviceName).Result() if err != nil || !has { // 如果出错或不存在,去库里查找 cnt := int64(0) res := q.db.Model(&models.ServiceNode{}).Where("app_alias=? and service_name=?", appAlias, serviceName).Count(&cnt) if res.Error != nil { return false, errors.Wrap(res.Error, "查询服务node是否存在失败") } if cnt == 0 { return false, nil } q.rdb.SAdd(key, serviceName) } return true, nil } func (q Service) HasEdge(appAlias, source, target string) (bool, error) { key := fmt.Sprintf("observe__service_edge_sets_%s", appAlias) dur, _ := q.rdb.TTL(key).Result() if dur == -1 { // 如果没有设置ttl,则设置为1分钟, time.Duration类型可以与数字比较, 因为它本身就是数字 q.rdb.Expire(key, time.Minute) } st := fmt.Sprintf("%s_%s", source, target) has, err := q.rdb.SIsMember(key, st).Result() if err != nil || !has { cnt := int64(0) res := q.db.Model(&models.ServiceEdge{}).Where("app_alias=? and source=? and target=?", appAlias, source, target).Count(&cnt) if res.Error != nil { return false, errors.Wrap(res.Error, "查询服务edge是否存在失败") } if cnt == 0 { return false, nil } q.rdb.SAdd(key, st) } return true, nil } func (q Service) ServiceMap(appAlias string) (map[string]string, error) { svcList := []struct { Name string ServiceName string }{} if err := q.db.Model(&models.ServiceNode{}).Select("name, service_name").Where("app_alias", appAlias).Find(&svcList).Error; err != nil { return map[string]string{}, errors.Wrap(err, "查询服务数据失败") } svcMap := map[string]string{} for _, svc := range svcList { name := svc.Name if name == "" { name = svc.ServiceName } svcMap[svc.ServiceName] = name } return svcMap, nil }