example_test.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package discovery_test
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/library/naming"
  6. "go-common/library/naming/discovery"
  7. "time"
  8. )
  9. // this example creates a registry service to register instance info
  10. // to discovery server.
  11. // when the program is about to exit,registry.Cancel should be called.
  12. func Example() {
  13. var c = &discovery.Config{
  14. Nodes: []string{"api.bilibili.co"},
  15. Zone: "sh001",
  16. Env: "pre",
  17. Key: "0c4b8fe3ff35a4b6",
  18. Secret: "b370880d1aca7d3a289b9b9a7f4d6812",
  19. }
  20. var ins = &naming.Instance{
  21. AppID: "main.arch.test2",
  22. Addrs: []string{
  23. "grpc://127.0.0.1:8080",
  24. },
  25. Version: "1",
  26. Metadata: map[string]string{
  27. "weight": "128",
  28. "color": "blue",
  29. },
  30. }
  31. d := discovery.New(c)
  32. cacenl, err := d.Register(context.TODO(), ins)
  33. if err != nil {
  34. return
  35. }
  36. defer cacenl()
  37. //start to Serve
  38. time.Sleep(time.Second * 5)
  39. }
  40. // this example creates a discovery client to poll instances from discovery server.
  41. func ExampleDiscovery() {
  42. d := discovery.Build("1231234")
  43. ch := d.Watch()
  44. for {
  45. <-ch
  46. ins, ok := d.Fetch(context.TODO())
  47. if ok {
  48. fmt.Println("new instances found:", ins)
  49. }
  50. }
  51. }