From 39e3cdef9181b9eaa0c21acd5ed52afd17b7eb49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Mon, 22 Nov 2021 18:34:37 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=9A=8F=E6=9C=BA=E8=B4=9F?= =?UTF-8?q?=E8=BD=BD=E5=9D=87=E8=A1=A1=E7=AD=96=E7=95=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- balance/poll.go | 14 ++++------- balance/random.go | 59 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 9 deletions(-) create mode 100644 balance/random.go diff --git a/balance/poll.go b/balance/poll.go index aea081a..b4b2a51 100644 --- a/balance/poll.go +++ b/balance/poll.go @@ -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 diff --git a/balance/random.go b/balance/random.go new file mode 100644 index 0000000..7f75658 --- /dev/null +++ b/balance/random.go @@ -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 +}