golang-im聊天
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

64 lignes
1.2 KiB

  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. }