序
本文次要钻研一下 nacos-coredns-plugin 的 Domain
Domain
nacos-coredns-plugin/nacos/nacos_domain.go
type Domain struct {
Name string `json:"dom"`
Clusters string
CacheMillis int64
LastRefMillis int64
Instances []Instance `json:"hosts"`
Env string
TTL int
}
func (domain Domain) getInstances() ([]Instance) {return domain.Instances}
func (domain Domain) String() string {b, _ := json.Marshal(domain)
return string(b)
}
func (domain Domain) SrvInstances() []Instance {var result = make([]Instance, 0)
hosts := domain.getInstances()
for _, host := range hosts {
if host.Valid && host.Weight > 0 {for i := 0; i < int(math.Ceil(host.Weight)); i++ {result = append(result, host)
}
}
}
if len(result) <= 0{panic("no host to srv:" + domain.Name)
}
return result
}
Domain 定义了 Name、Clusters、CacheMillis、LastRefMillis、Instances、Env、TTL 属性;它提供了 getInstances、String、SrvInstances 办法;其中 SrvInstances 办法依据 instance 的权重来返回对应个数的 instance
实例
nacos-coredns-plugin/nacos/nacos_domain_test.go
func TestDomain_SrvInstances(t *testing.T) {domain := Domain{}
domain.CacheMillis = 10000
domain.Clusters = "DEFAULT"
//test weight
domain.Instances = []Instance{Instance{IP: "2.2.2.2", Port: 80, Weight: 2, AppUseType: "publish", Valid: true, Site: "et2"}}
instances := domain.SrvInstances()
if len(instances) == 2 {t.Log("Domain.srvInstances weight passed.")
}
//test valid
defer func() {if err := recover(); err != nil {if strings.HasPrefix(err.(string), "no host to srv:") {t.Log("Domain.srvInstances valid passed.")
}
}
}()
domain.Instances = []Instance{Instance{IP: "2.2.2.2", Port: 80, Weight: 2, AppUseType: "publish", Valid: false, Site: "et2"}}
domain.SrvInstances()}
这里设置 instances 为一个 weight 为 2 的 instance,而后通过 SrvInstances 办法返回 2 个 instance
小结
nacos-coredns-plugin 的 Domain 定义了 Name、Clusters、CacheMillis、LastRefMillis、Instances、Env、TTL 属性;它提供了 getInstances、String、SrvInstances 办法。
doc
- nacos-coredns-plugin