Add dbx library: PostgreSQL cluster with master/replica routing, retry, health checking
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
35
balancer.go
Normal file
35
balancer.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package dbx
|
||||
|
||||
import "sync/atomic"
|
||||
|
||||
// Balancer selects the next node from a list.
|
||||
// It must return nil if no suitable node is available.
|
||||
type Balancer interface {
|
||||
Next(nodes []*Node) *Node
|
||||
}
|
||||
|
||||
// RoundRobinBalancer distributes load evenly across healthy nodes.
|
||||
type RoundRobinBalancer struct {
|
||||
counter atomic.Uint64
|
||||
}
|
||||
|
||||
// NewRoundRobinBalancer creates a new round-robin balancer.
|
||||
func NewRoundRobinBalancer() *RoundRobinBalancer {
|
||||
return &RoundRobinBalancer{}
|
||||
}
|
||||
|
||||
// Next returns the next healthy node, or nil if none are healthy.
|
||||
func (b *RoundRobinBalancer) Next(nodes []*Node) *Node {
|
||||
n := len(nodes)
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
idx := b.counter.Add(1)
|
||||
for i := 0; i < n; i++ {
|
||||
node := nodes[(int(idx)+i)%n]
|
||||
if node.IsHealthy() {
|
||||
return node
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user