Browse Source

feat(remoting): random load balance for getty sessions #598

tags/v2.0.0
yombo GitHub 2 years ago
parent
commit
c5fc98a59a
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 13 deletions
  1. +17
    -6
      pkg/remoting/loadbalance/random_loadbalance.go
  2. +11
    -7
      pkg/remoting/loadbalance/random_loadbalance_test.go

+ 17
- 6
pkg/remoting/loadbalance/random_loadbalance.go View File

@@ -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]
}

+ 11
- 7
pkg/remoting/loadbalance/random_loadbalance_test.go View File

@@ -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)))
@@ -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) {


Loading…
Cancel
Save