本文主要研究一下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


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...