service/library/servicediscovery/sd.go

85 lines
1.7 KiB
Go
Raw Normal View History

2024-05-14 09:48:34 +08:00
package servicediscovery
import (
"fmt"
consul "github.com/hashicorp/consul/api"
"service/library/configcenter"
"service/library/logger"
)
type ConsulSD struct {
client *consul.Client
serviceName string
}
var defaultConsulSD *ConsulSD
func GetDefaultConsulSD() *ConsulSD {
return defaultConsulSD
}
func Init(cfg *configcenter.ConsulServiceDiscovery) error {
if len(cfg.Host) <= 0 {
return fmt.Errorf("invalid host: %v", cfg.Host)
}
if len(cfg.ServiceName) <= 0 {
return fmt.Errorf("invalid service_name: %v", cfg.ServiceName)
}
config := consul.DefaultConfig()
config.Address = cfg.Host
client, err := consul.NewClient(config)
if err != nil {
return err
}
defaultConsulSD = &ConsulSD{
client: client,
serviceName: cfg.ServiceName,
}
return nil
}
// 注册服务
func Register(ip string, port int) error {
csd := GetDefaultConsulSD()
var (
key = fmt.Sprintf(`upstreams/%s/%s:%d`, csd.serviceName, ip, port)
value = fmt.Sprintf(`{"weight":1, "max_fails":2, "fail_timeout":10}`)
)
r, err := csd.client.KV().Put(
&consul.KVPair{
Key: key,
Value: []byte(value),
},
nil,
)
if err != nil {
return err
}
logger.Info("Service Register success, %v, %v", key, r.RequestTime.String())
return nil
}
// 注销服务
func DeRegister(ip string, port int) error {
csd := GetDefaultConsulSD()
var (
key = fmt.Sprintf(`upstreams/%s/%s:%d`, csd.serviceName, ip, port)
value = fmt.Sprintf(`{"weight":1, "max_fails":2, "fail_timeout":10, "down": 1}`)
)
r, err := csd.client.KV().Put(
&consul.KVPair{
Key: key,
Value: []byte(value),
},
nil,
)
if err != nil {
return err
}
logger.Info("Service DeRegister success, %v, %v", key, r.RequestTime.String())
return nil
}