1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
service.go 2.02 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-12-15 02:07 . 协程安全退出
package local
import (
"gitee.com/h79/goutils/common/logger"
"gitee.com/h79/goutils/common/result"
"gitee.com/h79/goutils/common/system"
"gitee.com/h79/goutils/discovery/config"
"gitee.com/h79/goutils/discovery/registry"
"gitee.com/h79/goutils/discovery/service"
"time"
)
var _ service.Service = (*defaultService)(nil)
type defaultService struct {
conf config.Config
endPoints config.EndPoints
registry registry.Registry
stop chan bool
}
// NewService
// 注册一个服务
func NewService(conf config.Config, points config.EndPoints, reg registry.Registry) (service.Service, error) {
logger.Info("def.service: register service")
return &defaultService{
conf: conf,
endPoints: points,
registry: reg,
stop: make(chan bool),
}, nil
}
func (s *defaultService) Start() error {
if s.conf.Check.Ttl {
system.ChildRunning(s.keepAlive)
}
return s.register()
}
func (s *defaultService) Stop() {
if s.conf.Check.Ttl {
system.Stop(time.Second, s.stop)
}
_ = s.revoke()
}
func (s *defaultService) Set(data service.Data) error {
return result.RErrNotSupport
}
func (s *defaultService) Get(key service.Key) ([]*service.Data, error) {
return nil, result.RErrNotSupport
}
func (s *defaultService) keepAlive() {
ticker := time.NewTicker(time.Second * s.conf.Check.Interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
_ = s.register()
case <-s.stop:
_ = s.revoke()
s.stop <- true
return
case <-system.Closed():
logger.Warn("def.service: server stop because system close")
_ = s.revoke()
return
}
}
}
func (s *defaultService) register() error {
if s.registry == nil {
return nil
}
err := s.registry.Register(&s.conf.Service, s.endPoints)
if err != nil {
logger.Error("def.service: register err= %v", err)
}
return err
}
// 撤销
func (s *defaultService) revoke() error {
if s.registry == nil {
return nil
}
err := s.registry.Deregister(&s.conf.Service, s.endPoints)
if err != nil {
logger.Error("def.service: deregister err= %v", err)
}
return err
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.21.4

搜索帮助