register fix

This commit is contained in:
Piotr Biernat 2022-12-02 03:22:36 +01:00
parent 2204f6116b
commit b8cfbf6b99

View File

@ -62,7 +62,6 @@ func (s *Service) Register() error {
Address: s.Address,
Port: s.Port,
Tags: s.getTags(),
// Meta: s.getMetadata(),
Check: &consul.AgentServiceCheck{
TTL: s.TTL.String(),
},
@ -71,7 +70,23 @@ func (s *Service) Register() error {
if err := s.ConsulAgent.ServiceRegister(def); err != nil {
return err
}
go s.UpdateTTL(def)
go func() { // startup register
ticker := time.NewTicker(time.Millisecond * 100)
for range ticker.C {
ok, _ := s.healthCheck()
if ok {
ticker.Stop()
}
}
}()
go func() { // TTL
ticker := time.NewTicker(s.TTL)
for range ticker.C {
s.healthCheck()
}
}()
return nil
}
@ -79,53 +94,38 @@ func (s *Service) Unregister() error {
return s.ConsulAgent.ServiceDeregister(s.GetID())
}
func (s *Service) UpdateTTL(service *consul.AgentServiceRegistration) {
ticker := time.NewTicker(s.TTL / 2)
for range ticker.C {
ok, err := s.check()
if !ok {
if err := s.ConsulAgent.FailTTL("service:"+s.GetID(), err.Error()); err != nil {
log.Println(err)
fmt.Println(err)
}
} else {
if err := s.ConsulAgent.PassTTL("service:"+s.GetID(), "OK"); err != nil {
log.Println(err)
fmt.Println(err)
}
func (s *Service) healthCheck() (bool, error) {
alive := func() bool {
client := &http.Client{}
healthUrl := s.GetFullAddr() + "health"
req, err := http.NewRequest(http.MethodGet, healthUrl, nil)
if err != nil {
return false
}
}
}
req.Header.Set("User-Agent", "Health Check")
func (s *Service) check() (bool, error) {
client := &http.Client{}
healthUrl := fmt.Sprintf("%shealth", s.GetFullAddr())
fmt.Println("HCheck: " + healthUrl)
req, err := http.NewRequest(http.MethodGet, healthUrl, nil)
if err != nil {
return false, ErrServiceUnavailable
}
req.Header.Set("User-Agent", "Health Check")
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
resp, err := client.Do(req)
if err != nil {
return false, ErrServiceUnavailable
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
}()
if resp.StatusCode == http.StatusOK {
if alive {
if err := s.ConsulAgent.PassTTL("service:"+s.GetID(), "OK"); err != nil {
log.Println("health-check pass err:" + err.Error())
}
return true, nil
}
if err := s.ConsulAgent.FailTTL("service:"+s.GetID(), ErrServiceUnavailable.Error()); err != nil {
log.Println("health-check fail err:" + err.Error())
}
return false, ErrServiceUnavailable
}
func (s *Service) getMetadata() map[string]string {
m := map[string]string{}
return m
}
func (s *Service) getTags() []string {
tags := []string{
"traefik.enable=true",