feature/balance #3

Merged
zhangdeman merged 7 commits from feature/balance into master 2021-11-22 19:13:50 +08:00
2 changed files with 64 additions and 9 deletions
Showing only changes of commit 39e3cdef91 - Show all commits

View File

@ -49,21 +49,17 @@ type Poll struct {
// //
// Date : 12:43 下午 2021/10/19 // Date : 12:43 下午 2021/10/19
func (p *Poll) GetServerNode(req *http.Request) (*define.ServerNode, error) { func (p *Poll) GetServerNode(req *http.Request) (*define.ServerNode, error) {
severList := p.GetServerNodeList() p.RLock()
if len(severList) == 0 { defer p.RUnlock()
return nil, errors.New("server list is empty")
}
p.Lock()
defer p.Unlock()
var ( var (
serverNode *define.ServerNode serverNode *define.ServerNode
) )
// 循环次数 // 循环次数
loopTimes := 0 loopTimes := 0
for loopTimes < len(severList) { for loopTimes < len(p.severList) {
loopTimes++ loopTimes++
p.currentServerIndex = (p.currentServerIndex + 1) % len(severList) p.currentServerIndex = (p.currentServerIndex + 1) % len(p.severList)
if serverNode = severList[p.currentServerIndex]; serverNode.Status != define.ServerNodeStatusNormal { if serverNode = p.severList[p.currentServerIndex]; serverNode.Status != define.ServerNodeStatusNormal {
continue continue
} }
break break

59
balance/random.go Normal file
View File

@ -0,0 +1,59 @@
// Package balance...
//
// Description : balance...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2021-11-22 6:27 下午
package balance
import (
"errors"
"net/http"
"sync"
"git.zhangdeman.cn/zhangdeman/gopkg/util"
"git.zhangdeman.cn/zhangdeman/gopkg/balance/define"
)
// NewRandom ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 6:29 下午 2021/11/22
func NewRandom(severList []*define.ServerNode) (IBalance, error) {
if nil == severList || len(severList) == 0 {
return nil, errors.New("sever list is empty")
}
return &Random{
base{
lock: &sync.RWMutex{},
severList: make([]*define.ServerNode, 0),
},
}, nil
}
// Random 随机负载均衡
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 6:27 下午 2021/11/22
type Random struct {
base
}
// GetServerNode ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 6:31 下午 2021/11/22
func (r *Random) GetServerNode(req *http.Request) (*define.ServerNode, error) {
r.RLock()
defer r.RUnlock()
if len(r.severList) == 0 {
return nil, errors.New("sever list is empty")
}
randomID := util.GetHashID(util.GenRandomString("", 128)) % uint64(len(r.severList))
return r.severList[int(randomID)], nil
}