github.com/searKing/golang/go@v1.2.117/net/resolver/picker.roundroubin.go (about)

     1  // Copyright 2021 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package resolver
     6  
     7  import (
     8  	"context"
     9  	"sync"
    10  )
    11  
    12  type rrPicker struct {
    13  	mu sync.Mutex
    14  	// Start at a random index, as the same RR balancer rebuilds a new
    15  	// picker when SubConn states change, and we don't want to apply excess
    16  	// load to the first server in the list.
    17  	next int
    18  }
    19  
    20  func NewRoundRobinPicker(next int) *rrPicker {
    21  	return &rrPicker{
    22  		next: next,
    23  	}
    24  }
    25  
    26  func (p *rrPicker) Pick(ctx context.Context, addrs []Address, opts ...PickOption) (Address, error) {
    27  	if len(addrs) == 0 {
    28  		return Address{}, ErrNoAddrAvailable
    29  	}
    30  	p.mu.Lock()
    31  	addr := addrs[p.next]
    32  
    33  	p.next = (p.next + 1) % len(addrs)
    34  	p.mu.Unlock()
    35  	return addr, nil
    36  }