Skip to content
This repository has been archived by the owner on Sep 5, 2024. It is now read-only.

Make the current index of the round-robin balancer thread-safe #20

Merged
merged 3 commits into from
Nov 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.17
go-version: 1.21
cache: false

- name: Build
run: go build -v ./...
Expand All @@ -25,7 +26,9 @@ jobs:
run: go test -v -race ./...

- name: golangci-lint
uses: golangci/[email protected]
uses: golangci/golangci-lint-action@v3
with:
version: v1.54

- name: Coverage
run: go test -v ./... -coverprofile=coverage.txt -covermode=atomic
Expand Down
9 changes: 5 additions & 4 deletions balancer/round_robin.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

package balancer

import "sync/atomic"

//RoundRobin will select the server in turn from the server to proxy
type RoundRobin struct {
BaseBalancer
i uint64
i atomic.Uint64
}

func init() {
Expand All @@ -17,7 +19,7 @@ func init() {
// NewRoundRobin create new RoundRobin balancer
func NewRoundRobin(hosts []string) Balancer {
return &RoundRobin{
i: 0,
i: atomic.Uint64{},
BaseBalancer: BaseBalancer{
hosts: hosts,
},
Expand All @@ -31,7 +33,6 @@ func (r *RoundRobin) Balance(_ string) (string, error) {
if len(r.hosts) == 0 {
return "", NoHostError
}
host := r.hosts[r.i%uint64(len(r.hosts))]
r.i++
host := r.hosts[r.i.Add(1)%uint64(len(r.hosts))]
return host, nil
}
5 changes: 3 additions & 2 deletions balancer/round_roubin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package balancer

import (
"sync/atomic"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -28,7 +29,7 @@ func TestRoundRobin_Add(t *testing.T) {
hosts: []string{"http://127.0.0.1:1011",
"http://127.0.0.1:1012", "http://127.0.0.1:1013"},
},
i: 0,
i: atomic.Uint64{},
},
},
{
Expand All @@ -41,7 +42,7 @@ func TestRoundRobin_Add(t *testing.T) {
hosts: []string{"http://127.0.0.1:1011",
"http://127.0.0.1:1012"},
},
i: 0,
i: atomic.Uint64{},
},
},
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/zehuamama/balancer

go 1.17
go 1.21

require (
github.com/gorilla/mux v1.8.0
Expand Down
Loading