-
Notifications
You must be signed in to change notification settings - Fork 0
/
service_registry.go
81 lines (68 loc) · 1.54 KB
/
service_registry.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package service_registry
import (
"context"
"fmt"
"sync"
"time"
"github.com/coreos/etcd/clientv3"
)
var (
serviceRegistry *ServiceRegistry
once sync.Once
serviceKeyTemplate = "/service/%s"
)
type ServiceRegistry struct {
client *clientv3.Client
serviceId int
}
func Register(host string, serviceId int) *ServiceRegistry {
once.Do(func() {
client, err := clientv3.New(clientv3.Config{
Endpoints: []string{host},
DialTimeout: 5 * time.Second,
})
if err != nil {
panic(err)
}
serviceRegistry = &ServiceRegistry{
client: client,
serviceId: serviceId,
}
})
return serviceRegistry
}
func Client() *ServiceRegistry {
return serviceRegistry
}
func (s *ServiceRegistry) Start() {
for {
value := "ready"
ttl := 15
// Create a lease with the desired TTL
leaseResp, err := s.client.Grant(context.Background(), int64(ttl))
if err != nil {
fmt.Println(err)
return
}
_, err = s.client.Put(context.Background(), fmt.Sprintf(serviceKeyTemplate, s.serviceId), value, clientv3.WithLease(leaseResp.ID))
if err != nil {
fmt.Println(err)
return
}
time.Sleep(time.Second * 10)
}
}
func (s *ServiceRegistry) PublishEvent(event string) {
ttl := 15
// Create a lease with the desired TTL
leaseResp, err := s.client.Grant(context.Background(), int64(ttl))
if err != nil {
fmt.Println(err)
return
}
_, err = s.client.Put(context.Background(), fmt.Sprintf(serviceKeyTemplate, s.serviceId), event, clientv3.WithLease(leaseResp.ID))
if err != nil {
fmt.Println(err)
return
}
}