1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
service.go 2.71 KB
一键复制 编辑 原始数据 按行查看 历史
package etcd
import (
"context"
"encoding/json"
"gitee.com/h79/goutils/common/logger"
"gitee.com/h79/goutils/common/system"
"gitee.com/h79/goutils/discovery/config"
"gitee.com/h79/goutils/discovery/registry"
"gitee.com/h79/goutils/discovery/service"
clientV3 "go.etcd.io/etcd/client/v3"
"time"
)
var _ service.Service = (*edService)(nil)
type edService struct {
Base
lease clientV3.Lease
leaseId clientV3.LeaseID
cancelFunc func()
keepAliveChan <-chan *clientV3.LeaseKeepAliveResponse
cfg config.Config
}
// NewService
// 注册一个服务
func NewService(cfg config.Config, points config.EndPoints, registry registry.Registry) (service.Service, error) {
cli, err := NewClient3(&points, 30)
if err != nil {
return nil, err
}
logger.Info("etcd.service: register service")
return NewServiceWith(cli, cfg)
}
func NewServiceWith(cli *clientV3.Client, cfg config.Config) (service.Service, error) {
// 创建租约
lease := clientV3.NewLease(cli)
// 设置租约时间
leaseResp, err := lease.Grant(context.TODO(), cfg.Check.Interval.Microseconds())
if err != nil {
_ = cli.Close()
return nil, err
}
// 设置续租
ctx, cancelFunc := context.WithCancel(context.TODO())
keepaliveChan, err := lease.KeepAlive(ctx, leaseResp.ID)
if err != nil {
_ = cli.Close()
cancelFunc()
return nil, err
}
ser := &edService{
Base: Base{
client: cli,
watcher: nil,
},
lease: lease,
leaseId: leaseResp.ID,
cancelFunc: cancelFunc,
keepAliveChan: keepaliveChan,
cfg: cfg,
}
if err = ser.create(); err != nil {
ser.Stop()
logger.Error("etcd.service: register service failure,%+v", err)
return nil, err
}
return ser, nil
}
// Start
/**
* Service interface
* 使用 goroutine go Start
*/
func (s *edService) Start() error {
system.ChildRunning(s.keepAlive)
return nil
}
// Stop interface
func (s *edService) Stop() {
s.revoke()
s.cancelFunc()
}
func (s *edService) keepAlive() {
if !s.cfg.Check.Ttl {
return
}
for {
select {
case c := <-s.keepAliveChan:
if c == nil {
logger.Error("etcd.service: 已经关闭续租功能")
return
} else {
logger.NDebug("etcd.service: 续租成功")
}
case <-system.Closed():
return
}
}
}
func (s *edService) create() error {
key := s.cfg.Node.NameWith("")
data, err := json.Marshal(&s.cfg.Server)
if err != nil {
return err
}
kv := clientV3.NewKV(s.client)
_, err = kv.Put(context.TODO(), key, string(data), clientV3.WithLease(s.leaseId))
return err
}
func (s *edService) revoke() {
time.Sleep(2 * time.Second)
if s.lease != nil {
_, _ = s.lease.Revoke(context.TODO(), s.leaseId)
s.lease = nil
}
if s.client != nil {
_ = s.client.Close()
s.client = nil
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.15

搜索帮助