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

Commit

Permalink
Make the current index of the round-robin balancer thread-safe (#20)
Browse files Browse the repository at this point in the history
* fix: make the current index of the round-robin balancer thread-safe

* ci: upgrade go version to 1.21

* ci: upgrade golangci-lint version to 1.54
  • Loading branch information
biningo authored Nov 23, 2023
1 parent 6e8ef29 commit c1d79cf
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 9 deletions.
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

0 comments on commit c1d79cf

Please sign in to comment.