You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.5 KiB
56 lines
1.5 KiB
package node_manager
|
|
|
|
import (
|
|
"fmt"
|
|
"sync/atomic"
|
|
)
|
|
|
|
type INodeSelector interface {
|
|
Select(nodes []*NodeConnection) (*NodeConnection, error)
|
|
}
|
|
|
|
type RoundRobinSelector struct {
|
|
index int32
|
|
}
|
|
|
|
func (s *RoundRobinSelector) Select(nodes []*NodeConnection) (*NodeConnection, error) {
|
|
if len(nodes) == 0 {
|
|
return nil, fmt.Errorf("没有可用的节点")
|
|
}
|
|
|
|
// 原子读取当前索引
|
|
currentIndex := atomic.LoadInt32(&s.index)
|
|
selectedNode := nodes[currentIndex%int32(len(nodes))]
|
|
|
|
// TODO 检查节点状态, 暂时先不检查节点健康状态
|
|
s.UpdateIndex() // 如果节点健康,更新索引
|
|
if selectedNode == nil {
|
|
return nil, fmt.Errorf("无此索引的节点。%d", currentIndex)
|
|
}
|
|
|
|
return selectedNode, nil
|
|
|
|
//if selectedNode.NArgs.Status == et_rpc.NodeState_Healthy {
|
|
// s.UpdateIndex() // 如果节点健康,更新索引
|
|
// return selectedNode, nil
|
|
//}
|
|
|
|
// 如果当前节点不健康,尝试查找下一个健康节点
|
|
//for i := 1; i < len(nodes); i++ { // 从下一个节点开始查找
|
|
// nextIndex := (currentIndex + int32(i)) % int32(len(nodes))
|
|
// selectedNode = nodes[nextIndex]
|
|
// if selectedNode.NArgs.Status == et_rpc.NodeState_Healthy {
|
|
// s.UpdateIndex() // 找到健康节点,更新索引
|
|
// return selectedNode, nil
|
|
// }
|
|
//}
|
|
//
|
|
//// 如果没有健康节点,重置索引并返回错误
|
|
//atomic.StoreInt32(&s.index, 0)
|
|
//return nil, fmt.Errorf("所有节点都不健康")
|
|
}
|
|
|
|
// 更新索引的单独方法
|
|
func (s *RoundRobinSelector) UpdateIndex() {
|
|
atomic.AddInt32(&s.index, 1) // 原子增加索引
|
|
}
|
|
|