golang-im聊天
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

addrs_resolver.go 1.2 KiB

2 anni fa
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package addrs
  2. import (
  3. "strings"
  4. "google.golang.org/grpc/resolver"
  5. )
  6. // 实现多个IP地址解析,比如,addrs:///127.0.0.1:50000,127.0.0.1:50001
  7. func init() {
  8. RegisterResolver()
  9. }
  10. func RegisterResolver() {
  11. resolver.Register(NewAddrsBuilder())
  12. }
  13. type addrsBuilder struct {
  14. }
  15. func NewAddrsBuilder() resolver.Builder {
  16. return &addrsBuilder{}
  17. }
  18. func (b *addrsBuilder) Build(target resolver.Target, clientConn resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
  19. ips := strings.Split(target.Endpoint, ",")
  20. state := resolver.State{
  21. Addresses: getAddrs(ips),
  22. }
  23. clientConn.UpdateState(state)
  24. return &addrsResolver{
  25. addrs: ips,
  26. clientConn: clientConn,
  27. }, nil
  28. }
  29. func (b *addrsBuilder) Scheme() string {
  30. return "addrs"
  31. }
  32. type addrsResolver struct {
  33. addrs []string
  34. clientConn resolver.ClientConn
  35. }
  36. func (r *addrsResolver) ResolveNow(opt resolver.ResolveNowOptions) {
  37. state := resolver.State{
  38. Addresses: getAddrs(r.addrs),
  39. }
  40. r.clientConn.UpdateState(state)
  41. }
  42. func (r *addrsResolver) Close() {
  43. }
  44. func getAddrs(ips []string) []resolver.Address {
  45. addresses := make([]resolver.Address, len(ips))
  46. for i := range ips {
  47. addresses[i].Addr = ips[i]
  48. }
  49. return addresses
  50. }