2021-10-19 14:48:46 +08:00
|
|
|
// Package balance ...
|
|
|
|
//
|
|
|
|
// Description : 轮询机制的负载均衡
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 2021-10-19 12:35 下午
|
|
|
|
package balance
|
|
|
|
|
|
|
|
import (
|
2021-11-22 16:52:08 +08:00
|
|
|
"net/http"
|
2021-10-19 14:48:46 +08:00
|
|
|
"sync"
|
|
|
|
|
|
|
|
"git.zhangdeman.cn/zhangdeman/gopkg/balance/define"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
// NewPoll 获取轮询实例
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 12:40 下午 2021/10/19
|
2021-11-22 17:21:05 +08:00
|
|
|
func NewPoll(serverList []*define.ServerNode) (IBalance, error) {
|
2021-10-19 14:48:46 +08:00
|
|
|
if nil == serverList || len(serverList) == 0 {
|
|
|
|
return nil, errors.New("server list is empty")
|
|
|
|
}
|
|
|
|
return &Poll{
|
|
|
|
base: base{
|
2021-11-22 17:21:41 +08:00
|
|
|
lock: &sync.RWMutex{},
|
|
|
|
severList: serverList,
|
2021-10-19 14:48:46 +08:00
|
|
|
},
|
|
|
|
currentServerIndex: 0,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Poll ...
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 12:41 下午 2021/10/19
|
|
|
|
type Poll struct {
|
|
|
|
base
|
|
|
|
currentServerIndex int
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetServerNode 获取服务节点
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 12:43 下午 2021/10/19
|
2021-11-22 16:52:08 +08:00
|
|
|
func (p *Poll) GetServerNode(req *http.Request) (*define.ServerNode, error) {
|
2021-11-22 17:21:05 +08:00
|
|
|
severList := p.GetServerNodeList()
|
|
|
|
if len(severList) == 0 {
|
2021-10-19 14:48:46 +08:00
|
|
|
return nil, errors.New("server list is empty")
|
|
|
|
}
|
|
|
|
p.Lock()
|
|
|
|
defer p.Unlock()
|
|
|
|
var (
|
|
|
|
serverNode *define.ServerNode
|
|
|
|
)
|
|
|
|
// 循环次数
|
|
|
|
loopTimes := 0
|
2021-11-22 17:21:05 +08:00
|
|
|
for loopTimes < len(severList) {
|
2021-10-19 14:48:46 +08:00
|
|
|
loopTimes++
|
2021-11-22 17:21:05 +08:00
|
|
|
p.currentServerIndex = (p.currentServerIndex + 1) % len(severList)
|
|
|
|
if serverNode = severList[p.currentServerIndex]; serverNode.Status != define.ServerNodeStatusNormal {
|
2021-10-19 14:48:46 +08:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
if nil == serverNode || serverNode.Status != define.ServerNodeStatusNormal {
|
|
|
|
return nil, errors.New("has no server node be used")
|
|
|
|
}
|
|
|
|
|
|
|
|
return serverNode, nil
|
|
|
|
}
|