github.com/glide-im/glide@v1.6.0/pkg/rpc/service_router.go (about)

     1  package rpc
     2  
     3  import (
     4  	"context"
     5  	"github.com/smallnest/rpcx/client"
     6  )
     7  
     8  // RoundRobinSelector selects servers with roundrobin.
     9  type RoundRobinSelector struct {
    10  	servers []string
    11  	i       int
    12  }
    13  
    14  func NewRoundRobinSelector() client.Selector {
    15  	return &RoundRobinSelector{servers: []string{}}
    16  }
    17  
    18  func (s *RoundRobinSelector) Select(ctx context.Context, servicePath, serviceMethod string, args interface{}) string {
    19  	return s.SelectNext()
    20  }
    21  
    22  func (s *RoundRobinSelector) SelectNext() string {
    23  	ss := s.servers
    24  	if len(ss) == 0 {
    25  		return ""
    26  	}
    27  	i := s.i
    28  	i = i % len(ss)
    29  	s.i = i + 1
    30  	return ss[i]
    31  }
    32  
    33  func (s *RoundRobinSelector) UpdateServer(servers map[string]string) {
    34  	ss := make([]string, 0, len(servers))
    35  	for k := range servers {
    36  		ss = append(ss, k)
    37  	}
    38  
    39  	s.servers = ss
    40  }