core/service/register.go

129 lines
2.8 KiB
Go

package service
import (
"context"
"strings"
"time"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/vars"
clientv3 "go.etcd.io/etcd/client/v3"
)
// ServiceRegister 创建租约注册服务
type ServiceRegister struct {
cli *clientv3.Client //etcd client
leaseID clientv3.LeaseID //租约ID
//租约keepalieve相应chan
keepAliveChan <-chan *clientv3.LeaseKeepAliveResponse
key string //key
val string //value
}
// NewRegister 注册服务至路由表.
//
// ec:EtcdConfig;
//
// routeKey: ServiceRouteRootPrefix + ServiceKey + "/" + utils.GetLocationIP() + addr;
//
// gs:grpc.Server;
func RegisterService(cli *clientv3.Client, routeKey string, methods []string, lease int64) (*ServiceRegister, error) {
ser := &ServiceRegister{
cli: cli,
key: routeKey,
val: strings.Join(methods, ","),
}
//申请租约设置时间keepalive
if err := ser.putKeyWithLease(lease); err != nil {
return nil, err
}
return ser, nil
}
// 设置租约
func (s *ServiceRegister) putKeyWithLease(lease int64) error {
//设置租约时间
resp, err := s.cli.Grant(context.Background(), lease)
if err != nil {
return err
}
//注册服务并绑定租约
_, err = s.cli.Put(context.Background(), s.key, s.val, clientv3.WithLease(resp.ID))
if err != nil {
return err
}
//设置续租 定期发送需求请求
leaseRespChan, err := s.cli.KeepAlive(context.Background(), resp.ID)
if err != nil {
return err
}
s.leaseID = resp.ID
s.keepAliveChan = leaseRespChan
return nil
}
// ListenLeaseRespChan 监听 续租情况
func (s *ServiceRegister) ListenLeaseRespChan() {
for {
select {
case leaseKeepResp := <-s.keepAliveChan:
if leaseKeepResp == nil {
//log.Println("close lease.")
return
} else {
goto END
}
}
END:
time.Sleep(500 * time.Millisecond)
}
}
// Close 注销服务
func (s *ServiceRegister) Close() error {
//撤销租约
if _, err := s.cli.Revoke(context.Background(), s.leaseID); err != nil {
return err
}
return s.cli.Close()
}
func (s *ServiceRegister) SetAnonymous(key string, urls []string) {
// remove reppeat, clear service all anonymous uri.
anonymous, _ := s.cli.Get(context.Background(), key)
var as []string
if len(anonymous.Kvs) > 0 {
val := string(anonymous.Kvs[0].Value)
as = strings.Split(val, ",")
}
as = append(clearService(as), urls...)
newAnonymous := strings.Join(as, ",")
// put anonymous to etcd
_, err := s.cli.Put(context.Background(), key, newAnonymous)
if err != nil {
print.Error("[BSM Register] Anonymous Fail.")
} else {
print.Info("[BSM Register] Anonymous: %s", newAnonymous)
}
}
func clearService(as []string) (out []string) {
for _, v := range as {
if len(v) >= len(vars.ServiceKey) {
if v[0:len(vars.ServiceKey)] != vars.ServiceKey {
out = append(out, v)
}
}
}
return
}