/
discovery.go
56 lines (51 loc) · 1.16 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
package tidb
import (
"context"
"fmt"
"strings"
"time"
"github.com/HuJingwei/go-zero/pkg/conf/env"
"github.com/HuJingwei/go-zero/pkg/log"
"github.com/HuJingwei/go-zero/pkg/naming"
"github.com/HuJingwei/go-zero/pkg/naming/discovery"
)
var _schema = "tidb://"
func (db *DB) nodeList() (nodes []string) {
var (
insZone *naming.InstancesInfo
ins []*naming.Instance
ok bool
)
if insZone, ok = db.dis.Fetch(context.Background()); !ok {
return
}
if ins, ok = insZone.Instances[env.Zone]; !ok || len(ins) == 0 {
return
}
for _, in := range ins {
for _, addr := range in.Addrs {
if strings.HasPrefix(addr, _schema) {
addr = strings.Replace(addr, _schema, "", -1)
nodes = append(nodes, addr)
}
}
}
log.Info("tidb get %s instances(%v)", db.appid, nodes)
return
}
func (db *DB) disc() (nodes []string) {
db.dis = discovery.Build(db.appid)
e := db.dis.Watch()
select {
case <-e:
nodes = db.nodeList()
case <-time.After(10 * time.Second):
panic("tidb init discovery err")
}
if len(nodes) == 0 {
panic(fmt.Sprintf("tidb %s no instance", db.appid))
}
go db.nodeproc(e)
log.Info("init tidb discvoery info successfully")
return
}