一、鸭子类型
符合golang设计理念的鸭子类型
1.设计
package consul
import (
"fmt"
"github.com/hashicorp/consul/api"
)
type Registry struct {
Host string
Port int
}
type RegistryClient interface {
Register(address string, port int, name string, tags []string, id string) error
DeRegister(service string) error
}
func NewRegistryClient(host string, port int) RegistryClient {
return &Registry{
Host: host,
Port: port,
}
}
func (r *Registry) Register(address string, port int, name string, tags []string, id string) error {
cfg := api.DefaultConfig()
cfg.Address = fmt.Sprintf("%s:%d")
client, err := api.NewClient(cfg)
if err != nil {
panic(err)
}
registration := new(api.AgentServiceRegistration)
registration.Name = name
registration.ID = id
registration.Port = port
registration.Tags = tags
registration.Address = address
//生成对应的检查对象
check := &api.AgentServiceCheck{
HTTP: "http://10.231.72.37:8023/health",
Timeout: "5s",
Interval: "5s",
DeregisterCriticalServiceAfter: "10s",
}
registration.Check = check
err = client.Agent().ServiceRegister(registration)
if err != nil {
panic(err)
}
return nil
}
func (r *Registry) DeRegister(service string) error {
return nil
}
2.使用
register_client:=consul.NewRegistryClient(Host,global.Port)