mockdiscovery.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package resolver
  2. import (
  3. "context"
  4. "go-common/library/conf/env"
  5. "go-common/library/naming"
  6. )
  7. type mockDiscoveryBuilder struct {
  8. instances map[string]*naming.Instance
  9. watchch map[string][]*mockDiscoveryResolver
  10. }
  11. func (mb *mockDiscoveryBuilder) Build(id string) naming.Resolver {
  12. mr := &mockDiscoveryResolver{
  13. d: mb,
  14. watchch: make(chan struct{}, 1),
  15. }
  16. mb.watchch[id] = append(mb.watchch[id], mr)
  17. mr.watchch <- struct{}{}
  18. return mr
  19. }
  20. func (mb *mockDiscoveryBuilder) Scheme() string {
  21. return "mockdiscovery"
  22. }
  23. type mockDiscoveryResolver struct {
  24. //instances map[string]*naming.Instance
  25. d *mockDiscoveryBuilder
  26. watchch chan struct{}
  27. }
  28. var _ naming.Resolver = &mockDiscoveryResolver{}
  29. func (md *mockDiscoveryResolver) Fetch(ctx context.Context) (map[string][]*naming.Instance, bool) {
  30. zones := make(map[string][]*naming.Instance)
  31. for _, v := range md.d.instances {
  32. zones[v.Zone] = append(zones[v.Zone], v)
  33. }
  34. return zones, len(zones) > 0
  35. }
  36. func (md *mockDiscoveryResolver) Watch() <-chan struct{} {
  37. return md.watchch
  38. }
  39. func (md *mockDiscoveryResolver) Close() error {
  40. close(md.watchch)
  41. return nil
  42. }
  43. func (md *mockDiscoveryResolver) Scheme() string {
  44. return "mockdiscovery"
  45. }
  46. func (mb *mockDiscoveryBuilder) registry(appID string, hostname, rpc string, metadata map[string]string) {
  47. ins := &naming.Instance{
  48. AppID: appID,
  49. Env: "hello=world",
  50. Hostname: hostname,
  51. Addrs: []string{"grpc://" + rpc},
  52. Version: "1.1",
  53. Zone: env.Zone,
  54. Metadata: metadata,
  55. }
  56. mb.instances[hostname] = ins
  57. if ch, ok := mb.watchch[appID]; ok {
  58. var bullet struct{}
  59. for _, c := range ch {
  60. c.watchch <- bullet
  61. }
  62. }
  63. }
  64. func (mb *mockDiscoveryBuilder) cancel(hostname string) {
  65. ins, ok := mb.instances[hostname]
  66. if !ok {
  67. return
  68. }
  69. delete(mb.instances, hostname)
  70. if ch, ok := mb.watchch[ins.AppID]; ok {
  71. var bullet struct{}
  72. for _, c := range ch {
  73. c.watchch <- bullet
  74. }
  75. }
  76. }