discovery.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package tidb
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "time"
  7. "go-common/library/conf/env"
  8. "go-common/library/log"
  9. "go-common/library/naming"
  10. "go-common/library/naming/discovery"
  11. )
  12. var _schema = "tidb://"
  13. func (db *DB) nodeList() (nodes []string) {
  14. var (
  15. insMap map[string][]*naming.Instance
  16. ins []*naming.Instance
  17. ok bool
  18. )
  19. if insMap, ok = db.dis.Fetch(context.Background()); !ok {
  20. return
  21. }
  22. if ins, ok = insMap[env.Zone]; !ok || len(ins) == 0 {
  23. return
  24. }
  25. for _, in := range ins {
  26. for _, addr := range in.Addrs {
  27. if strings.HasPrefix(addr, _schema) {
  28. addr = strings.Replace(addr, _schema, "", -1)
  29. nodes = append(nodes, addr)
  30. }
  31. }
  32. }
  33. log.Info("tidb get %s instances(%v)", db.appid, nodes)
  34. return
  35. }
  36. func (db *DB) disc() (nodes []string) {
  37. db.dis = discovery.Build(db.appid)
  38. e := db.dis.Watch()
  39. select {
  40. case <-e:
  41. nodes = db.nodeList()
  42. case <-time.After(10 * time.Second):
  43. panic("tidb init discovery err")
  44. }
  45. if len(nodes) == 0 {
  46. panic(fmt.Sprintf("tidb %s no instance", db.appid))
  47. }
  48. go db.nodeproc(e)
  49. log.Info("init tidb discvoery info successfully")
  50. return
  51. }