pool.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2016 Google LLC.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package internal
  5. import (
  6. "errors"
  7. "google.golang.org/grpc/naming"
  8. )
  9. // PoolResolver provides a fixed list of addresses to load balance between
  10. // and does not provide further updates.
  11. type PoolResolver struct {
  12. poolSize int
  13. dialOpt *DialSettings
  14. ch chan []*naming.Update
  15. }
  16. // NewPoolResolver returns a PoolResolver
  17. // This is an EXPERIMENTAL API and may be changed or removed in the future.
  18. func NewPoolResolver(size int, o *DialSettings) *PoolResolver {
  19. return &PoolResolver{poolSize: size, dialOpt: o}
  20. }
  21. // Resolve returns a Watcher for the endpoint defined by the DialSettings
  22. // provided to NewPoolResolver.
  23. func (r *PoolResolver) Resolve(target string) (naming.Watcher, error) {
  24. if r.dialOpt.Endpoint == "" {
  25. return nil, errors.New("no endpoint configured")
  26. }
  27. addrs := make([]*naming.Update, 0, r.poolSize)
  28. for i := 0; i < r.poolSize; i++ {
  29. addrs = append(addrs, &naming.Update{Op: naming.Add, Addr: r.dialOpt.Endpoint, Metadata: i})
  30. }
  31. r.ch = make(chan []*naming.Update, 1)
  32. r.ch <- addrs
  33. return r, nil
  34. }
  35. // Next returns a static list of updates on the first call,
  36. // and blocks indefinitely until Close is called on subsequent calls.
  37. func (r *PoolResolver) Next() ([]*naming.Update, error) {
  38. return <-r.ch, nil
  39. }
  40. // Close releases resources associated with the pool and causes Next to unblock.
  41. func (r *PoolResolver) Close() {
  42. close(r.ch)
  43. }