balancer

package module
v0.0.0-...-404409b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2025 License: MIT Imports: 4 Imported by: 0

README

Balancer

Go Report Card

A library for balancing the load on services.

Usage

package main

import (
    "context"
    "net/http"
    "time"

    "github.com/NovikovRoman/balancer"
)

// Arbitrary structure.
type myService struct {
    client *http.Client
}

func main() {
    items := []*balancer.Item[myService]{}
    s1 := &myService{
        client: &http.Client{
            Transport: &http.Transport{
                // …
            },
        },
    }
    s2 := &myService{
        client: &http.Client{
            Transport: &http.Transport{
                // …
            },
        },
    }
    s3 := &myService{
        client: &http.Client{
            Transport: &http.Transport{
                // …
            },
        },
    }

    items = append(items, balancer.NewItem(s1, 10)) // No more than 10 requests per second.
    items = append(items, balancer.NewItem(s2, 20)) // No more than 20 requests per second.
    items = append(items, balancer.NewItem(s3, 30)) // No more than 30 requests per second.

    b := balancer.New(items)

    s := b.Acquire()
    if s != nil { // If there is a service available, then make a request.
        _, _ = s.client.Get("https://api.site.domain/path")
    }

    ctx := context.Background()
    // With expectation. 5 attempts, half a second waiting time between attempts.
    s = b.AcquireWait(ctx, 5, time.Second/2)
    if s != nil { // If there is a service available, then make a request.
        _, _ = s.client.Get("https://api.site.domain/path")
    }

    b.SetShuffle(true) // Items will be balanced in random order.
}

Testing

go test -race ./...

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Balancer

type Balancer[T any] struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func New

func New[T any](items []*Item[T]) *Balancer[T]

func (*Balancer[T]) Acquire

func (b *Balancer[T]) Acquire() *T

func (*Balancer[T]) AcquireWait

func (b *Balancer[T]) AcquireWait(ctx context.Context, attempts int, pause time.Duration) *T

func (*Balancer[T]) NumItems

func (b *Balancer[T]) NumItems() int

func (*Balancer[T]) SetShuffle

func (b *Balancer[T]) SetShuffle(shuffle bool)

func (*Balancer[T]) TotalFreeRequests

func (b *Balancer[T]) TotalFreeRequests() int

func (*Balancer[T]) TotalMaxRequests

func (b *Balancer[T]) TotalMaxRequests() int

type Item

type Item[T any] struct {
	// contains filtered or unexported fields
}

func NewItem

func NewItem[T any](item *T, maxRequests int) *Item[T]

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL