增加随机负载均衡策略
This commit is contained in:
parent
ad8c3dc47d
commit
39e3cdef91
@ -49,21 +49,17 @@ type Poll struct {
|
||||
//
|
||||
// Date : 12:43 下午 2021/10/19
|
||||
func (p *Poll) GetServerNode(req *http.Request) (*define.ServerNode, error) {
|
||||
severList := p.GetServerNodeList()
|
||||
if len(severList) == 0 {
|
||||
return nil, errors.New("server list is empty")
|
||||
}
|
||||
p.Lock()
|
||||
defer p.Unlock()
|
||||
p.RLock()
|
||||
defer p.RUnlock()
|
||||
var (
|
||||
serverNode *define.ServerNode
|
||||
)
|
||||
// 循环次数
|
||||
loopTimes := 0
|
||||
for loopTimes < len(severList) {
|
||||
for loopTimes < len(p.severList) {
|
||||
loopTimes++
|
||||
p.currentServerIndex = (p.currentServerIndex + 1) % len(severList)
|
||||
if serverNode = severList[p.currentServerIndex]; serverNode.Status != define.ServerNodeStatusNormal {
|
||||
p.currentServerIndex = (p.currentServerIndex + 1) % len(p.severList)
|
||||
if serverNode = p.severList[p.currentServerIndex]; serverNode.Status != define.ServerNodeStatusNormal {
|
||||
continue
|
||||
}
|
||||
break
|
||||
|
59
balance/random.go
Normal file
59
balance/random.go
Normal 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
|
||||
}
|
Loading…
Reference in New Issue
Block a user