|
|
|
@ -15,7 +15,7 @@ type Registrar interface {
|
|
|
|
|
Register(service Service) error
|
|
|
|
|
|
|
|
|
|
// 注销服务
|
|
|
|
|
DeRegister(service Service) error
|
|
|
|
|
DeRegister() error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 基于Etcd的服务发现中间件,实现Registrar
|
|
|
|
@ -25,6 +25,8 @@ type RegistrarEtcd struct {
|
|
|
|
|
// 租约信息,基于租约来做健康监测
|
|
|
|
|
leaseID clientv3.LeaseID
|
|
|
|
|
leaseTTL int64
|
|
|
|
|
// 续约响应channel
|
|
|
|
|
leaseKeepAliveRespCh <-chan *clientv3.LeaseKeepAliveResponse
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const leaseTTL = 5
|
|
|
|
@ -75,17 +77,35 @@ func (re *RegistrarEtcd) Register(service Service) error {
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//三,租约续约
|
|
|
|
|
_, err = re.cli.KeepAlive(context.Background(), re.leaseID)
|
|
|
|
|
re.leaseKeepAliveRespCh, err = re.cli.KeepAlive(context.Background(), re.leaseID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 并发的接收续约的响应
|
|
|
|
|
go re.HandleKeepAliveResp()
|
|
|
|
|
// log
|
|
|
|
|
log.Printf("service %s(%s) was registed \n", service.Name(), service.Addr())
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
func (re *RegistrarEtcd) HandleKeepAliveResp() {
|
|
|
|
|
// 从ch中接收内容即可
|
|
|
|
|
for resp := range re.leaseKeepAliveRespCh {
|
|
|
|
|
log.Printf("service was Keepalive with %x\n", resp.ID)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 注销
|
|
|
|
|
// 撤销租约
|
|
|
|
|
func (re *RegistrarEtcd) DeRegister() error {
|
|
|
|
|
// lease revoke
|
|
|
|
|
if _, err := re.cli.Revoke(context.Background(), re.leaseID); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// close etcd client
|
|
|
|
|
if err := re.cli.Close(); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (re *RegistrarEtcd) DeRegister(service Service) error {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|