53 lines
1.2 KiB
Go
53 lines
1.2 KiB
Go
// Package dispatch ...
|
|
//
|
|
// Description : Round Robin 轮询选择服务器
|
|
//
|
|
// Author : go_developer@163.com<张德满>
|
|
//
|
|
// Date : 2021-04-01 8:04 下午
|
|
package implement
|
|
|
|
import (
|
|
"git.zhangdeman.cn/gateway/balance/abstract"
|
|
"git.zhangdeman.cn/zhangdeman/exception"
|
|
|
|
"git.zhangdeman.cn/gateway/balance/define"
|
|
)
|
|
|
|
// NewRoundRobin 轮询调度
|
|
//
|
|
// Author : go_developer@163.com<张德满>
|
|
//
|
|
// Date : 8:07 下午 2021/4/1
|
|
func NewRoundRobin() abstract.IBalance {
|
|
return &RoundRobin{
|
|
nextNodeIndex: 0,
|
|
}
|
|
}
|
|
|
|
// RoundRobin 轮询选择机器
|
|
//
|
|
// Author : go_developer@163.com<张德满>
|
|
//
|
|
// Date : 8:06 下午 2021/4/1
|
|
type RoundRobin struct {
|
|
nextNodeIndex int
|
|
}
|
|
|
|
// Get ...
|
|
//
|
|
// Author : go_developer@163.com<张德满>
|
|
//
|
|
// Date : 8:05 下午 2021/4/1
|
|
func (r *RoundRobin) Get(nodeList []*define.SeverNode) (*define.SeverNode, exception.IException) {
|
|
if len(nodeList) == 0 {
|
|
return nil, exception.New(define.ErrorTypeNodeListEmpty, nil, "服务器可用节点为空")
|
|
}
|
|
if r.nextNodeIndex >= len(nodeList) {
|
|
// 记录过索引之后, 在下次访问之前, 可能移除了某些节点, 所以要检测越界
|
|
r.nextNodeIndex = len(nodeList) - 1
|
|
}
|
|
r.nextNodeIndex = (r.nextNodeIndex + 1) % len(nodeList)
|
|
return nodeList[r.nextNodeIndex], nil
|
|
}
|