Skip to content

Commit

Permalink
feat(remoting): random load balance for getty sessions #598
Browse files Browse the repository at this point in the history
  • Loading branch information
xyombo authored Aug 8, 2023
1 parent 97d6a39 commit c5fc98a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 13 deletions.
23 changes: 17 additions & 6 deletions pkg/remoting/loadbalance/random_loadbalance.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,31 @@
package loadbalance

import (
"math/rand"
"sync"
"time"

getty "github.com/apache/dubbo-getty"
)

func RandomLoadBalance(sessions *sync.Map, xid string) getty.Session {
var session getty.Session
//collect sync.Map keys
//filted out closed session instance
var keys []getty.Session
sessions.Range(func(key, value interface{}) bool {
session = key.(getty.Session)
session := key.(getty.Session)
if session.IsClosed() {
sessions.Delete(session)
return true
sessions.Delete(key)
} else {
keys = append(keys, session)
}
return false
return true
})
return session
//keys eq 0 means there are no available session
if len(keys) == 0 {
return nil
}
//random in keys
randomIndex := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(len(keys))
return keys[randomIndex]
}
18 changes: 11 additions & 7 deletions pkg/remoting/loadbalance/random_loadbalance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ import (
"github.com/stretchr/testify/assert"
)

func TestRandomLoadBalance_Nomal(t *testing.T) {
func TestRandomLoadBalance_Normal(t *testing.T) {
ctrl := gomock.NewController(t)
sessions := &sync.Map{}

for i := 0; i < 3; i++ {
for i := 0; i < 10; i++ {
session := mock.NewMockTestSession(ctrl)
session.EXPECT().IsClosed().Return(i == 2).AnyTimes()
sessions.Store(session, fmt.Sprintf("session-%d", (i+1)))
Expand All @@ -44,20 +44,24 @@ func TestRandomLoadBalance_Nomal(t *testing.T) {
}

func TestRandomLoadBalance_All_Closed(t *testing.T) {

ctrl := gomock.NewController(t)
sessions := &sync.Map{}

//mock closed sessions
for i := 0; i < 10; i++ {
session := mock.NewMockTestSession(ctrl)
session.EXPECT().IsClosed().Return(true).AnyTimes()
sessions.Store(session, fmt.Sprintf("session-%d", (i+1)))
}
result := RandomLoadBalance(sessions, "some_xid")
if result := RandomLoadBalance(sessions, "some_xid"); result != nil {
t.Errorf("Expected nil, actual got %+v", result)
}
}

assert.NotNil(t, result)
assert.True(t, result.IsClosed(), "found one un-closed session instance in ALL_CLOSED_SESSION_MAP")
func TestRandomLoadBalance_Empty(t *testing.T) {
sessions := &sync.Map{}
if result := RandomLoadBalance(sessions, "some_xid"); result != nil {
t.Errorf("Expected nil, actual got %+v", result)
}
}

func TestRandomLoadBalance_All_Opening(t *testing.T) {
Expand Down

0 comments on commit c5fc98a

Please sign in to comment.