1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
service.go 2.09 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-08-15 13:12 . fixed address
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)
}
if s.registry != nil {
return s.registry.Register(&s.conf.Service, s.endPoints)
}
return nil
}
func (s *defaultService) Stop() {
if s.conf.Check.Ttl {
s.stop <- true
}
if s.registry != nil {
_ = s.registry.Deregister(&s.conf.Service, s.endPoints)
}
}
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() {
sys := system.Exit()
ticker := time.NewTicker(time.Second * s.conf.Check.Interval)
for {
select {
case _ = <-s.stop:
s.revoke()
logger.Error("def.service: server stop")
return
case <-ticker.C:
s.register()
case <-sys.Done():
s.stop <- true
case <-system.Closed():
s.stop <- true
}
}
}
func (s *defaultService) register() {
if s.registry == nil {
return
}
if err := s.registry.Register(&s.conf.Service, s.endPoints); err != nil {
logger.Error("def.service: register err= %v", err)
}
}
// 撤销
func (s *defaultService) revoke() {
if s.registry == nil {
return
}
if err := s.registry.Deregister(&s.conf.Service, s.endPoints); err != nil {
logger.Error("def.service: deregister err= %v", err)
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.8.96

搜索帮助