-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsularis.go
More file actions
71 lines (59 loc) · 1.48 KB
/
consularis.go
File metadata and controls
71 lines (59 loc) · 1.48 KB
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
package goconsularis
import (
consul "github.com/armon/consul-api"
log "github.com/cihub/seelog"
"strconv"
"time"
)
//Register service and keep it registered.
func RegisterService(name string, port int, ttl int) {
go registerService(name, port, ttl)
}
func registerCheckTtl(name string, ttl int, agent *consul.Agent) {
reg := &consul.AgentCheckRegistration{
Name: name,
}
reg.TTL = strconv.Itoa(ttl) + "s"
if err := agent.CheckRegister(reg); err != nil {
log.Error("Failed to register check: ", err)
}
}
//continue to register a service preferably ran in a go routine.
func registerService(name string, port int, ttl int) {
reportInterval := make(chan bool, 1)
go func() {
for {
time.Sleep(time.Duration(ttl) / 2 * time.Second)
reportInterval <- true
}
}()
client, err := consul.NewClient(consul.DefaultConfig())
if nil != err {
log.Error("Failed to get consul client")
}
agent := client.Agent()
serviceRegister(name, port, ttl, agent)
for {
select {
case <-reportInterval: //report registration
{
servicePassing(name, agent)
}
}
}
}
func servicePassing(name string, agent *consul.Agent) {
agent.PassTTL("service:"+name, "Service up and ready!")
}
func serviceRegister(name string, port int, ttl int, agent *consul.Agent) {
reg := &consul.AgentServiceRegistration{
Name: name,
Port: port,
Check: &consul.AgentServiceCheck{
TTL: strconv.Itoa(ttl) + "s",
},
}
if err := agent.ServiceRegister(reg); err != nil {
log.Error("err: ", err)
}
}