Skip to content

Commit

Permalink
round-robin and random balancers
Browse files Browse the repository at this point in the history
  • Loading branch information
nbari committed Sep 8, 2017
1 parent 0945d44 commit 9f407a8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
16 changes: 12 additions & 4 deletions balancer.go
Expand Up @@ -5,6 +5,7 @@ import (
"log"
"math/rand"
"net"
"sync/atomic"
"time"
)

Expand Down Expand Up @@ -45,13 +46,20 @@ func (sq *Slashquery) Balancer(name, network, port string) (net.Conn, error) {
break
}

// Select a random endpoint
rand.Seed(time.Now().UnixNano())
i := rand.Intn(len(endpoints))
// find endpoint based on the load balance type
var i int
switch sq.Upstreams[name].LBtype {
case "random":
// Select a random endpoint
rand.Seed(time.Now().UnixNano())
i = int(rand.Intn(len(endpoints)))
default:
i = int(atomic.AddUint32(&sq.Upstreams[name].RRindex, 1) % uint32(len(endpoints)))
}
endpoint := endpoints[i]

if sq.Debug() {
log.Printf("Upstream: %q, using endpoint: %s\n", name, endpoint)
log.Printf("Upstream: %q, using endpoint: %s LB type: %s \n", name, endpoint, sq.Upstreams[name].LBtype)
}

// Try to connect
Expand Down
9 changes: 9 additions & 0 deletions slashquery.go
Expand Up @@ -55,8 +55,17 @@ type Route struct {

// Upstream structure
type Upstream struct {
// Servers list of IP's
Servers []string

// Timeout before trying another server
Timeout int

// LBtype round-robin, random
LBtype string

// RRindex last used server
RRindex uint32
}

// Servers keep IP's from upstreams (needs a resolver)
Expand Down

0 comments on commit 9f407a8

Please sign in to comment.