聊聊nacos-coredns-plugin的Domain

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

你可能感兴趣的:(golang)