/
peer.go
73 lines (66 loc) · 1.27 KB
/
peer.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
package etcd
import (
"encoding/json"
"fmt"
"go.etcd.io/etcd/client"
"golang.org/x/net/context"
"log"
"os"
"time"
)
type Client interface {
HeartBeat()
}
type ClientService struct {
KeyApi client.KeysAPI
Name string
Ip string
}
type ClientInfo struct {
Name string
Ip string
Pid int
}
func RegisterClientService(name, ip string, endpoints []string) {
cfg := client.Config{
Endpoints: endpoints,
Transport: client.DefaultTransport,
HeaderTimeoutPerRequest: time.Second,
}
c, err := client.New(cfg)
if err != nil {
log.Fatal("Error: cannot connec to etcd:", err)
}
s := &ClientService{
Name: name,
KeyApi: client.NewKeysAPI(c),
Ip: ip,
}
go s.HeartBeat()
}
func (c *ClientService) HeartBeat() {
api := c.KeyApi
for {
clientInfo := &ClientInfo{
Name: c.Name,
Ip: c.Ip,
Pid: os.Getpid(),
}
key := "workers/" + c.Name
v, err := json.Marshal(clientInfo)
if err != nil {
log.Print("json marshal failed:%s", err)
break
}
resp, err := api.Set(context.Background(), key, string(v), &client.SetOptions{
TTL: 10 * time.Second,
})
if err != nil {
log.Print("api configure failed:%s", err)
break
} else {
fmt.Println(resp.Node.Value)
}
time.Sleep(5 * time.Second)
}
}