forked from Pc6/service-discovery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiscovery.go
83 lines (68 loc) · 1.6 KB
/
discovery.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
82
83
package main
import (
"context"
"encoding/json"
"errors"
"log"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/mvcc/mvccpb"
)
var cacheInfo = make(map[string]*ServiceInfo)
func GetServiceInfo(serviceName string) *ServiceInfo {
if len(serviceName) == 0 {
log.Fatalln("getInfo arg error")
}
info, ok := cacheInfo[serviceName]
if ok {
return info
}
key := prefix + serviceName
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
resp, err := client.Get(ctx, key)
cancel()
if err != nil {
log.Fatalln(err)
}
s := new(ServiceInfo)
for _, ev := range resp.Kvs {
err = json.Unmarshal(ev.Value, s)
if err != nil {
log.Fatalln(err)
}
}
cacheInfo[serviceName] = s
return s
}
func WatchServices(serviceNames ...string) error {
for _, serviceName := range serviceNames {
if len(serviceName) == 0 {
return errors.New("watch arg error")
}
key := prefix + serviceName
// ctx, cancel := context.WithCancel(context.Background())
rch := client.Watch(context.Background(), key, clientv3.WithPrefix())
// cancel()
go watchEvents(serviceName, rch)
}
return nil
}
func watchEvents(serviceName string, rch clientv3.WatchChan) {
for wresp := range rch {
for _, ev := range wresp.Events {
switch ev.Type {
case mvccpb.PUT:
s := new(ServiceInfo)
err := json.Unmarshal(ev.Kv.Value, s)
if err != nil {
log.Println("json unmarshal error")
continue
}
cacheInfo[serviceName] = s
log.Println("watch update event")
case mvccpb.DELETE:
delete(cacheInfo, serviceName)
log.Println("watch delete event")
}
}
}
}