Documentation
¶
Overview ¶
Package lb provides load balancing functionality with a Round Robin algorithm.
The package offers a thread-safe RoundRobin balancer that distributes requests across a list of hosts in a cyclic manner. It supports dynamic host list updates and is safe for concurrent use by multiple goroutines.
Basic usage:
hostList := []string{"localhost:8080", "localhost:8081"}
balancer := lb.NewRoundRobin(hostList)
host, err := balancer.Next()
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNoHostsToBalance is returned when no hosts are available for balancing. ErrNoHostsToBalance = errors.New("no hosts to balance") )
Functions ¶
This section is empty.
Types ¶
type RoundRobin ¶
type RoundRobin struct {
// contains filtered or unexported fields
}
RoundRobin implements a Round Robin load balancing algorithm. It distributes requests across a list of hosts in a cyclic order. The RoundRobin balancer is safe for concurrent use by multiple goroutines.
func NewRoundRobin ¶
func NewRoundRobin(hosts []string) *RoundRobin
NewRoundRobin creates a new RoundRobin balancer with the provided list of hosts. The initial position is set to a random index if hosts are provided. It returns a pointer to the newly created RoundRobin instance.
func (*RoundRobin) Next ¶
func (b *RoundRobin) Next() (string, error)
Next returns the next host from the list using the Round Robin algorithm. It cycles through the hosts in order, returning ErrNoHostsToBalance if the list is empty. This method is safe for concurrent use.
func (*RoundRobin) Size ¶
func (b *RoundRobin) Size() int
Size returns the current number of hosts in the balancer. This method is safe for concurrent use.
func (*RoundRobin) Upgrade ¶
func (b *RoundRobin) Upgrade(hosts []string)
Upgrade updates the list of hosts to balance. It resets the current position to a random index if hosts are provided. This method is safe for concurrent use.