From ad8c3dc47ddb506e53b96bb56d92807e6766fbc2 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 17:37:05 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0iphash=E8=B4=9F=E8=BD=BD?= =?UTF-8?q?=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- balance/ip_hash.go | 62 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 balance/ip_hash.go diff --git a/balance/ip_hash.go b/balance/ip_hash.go new file mode 100644 index 0000000..8f0284c --- /dev/null +++ b/balance/ip_hash.go @@ -0,0 +1,62 @@ +// Package balance... +// +// Description : balance... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2021-11-22 4:39 下午 +package balance + +import ( + "net/http" + "sync" + + "git.zhangdeman.cn/zhangdeman/gopkg/util" + + "github.com/pkg/errors" + + "git.zhangdeman.cn/zhangdeman/gopkg/balance/define" +) + +// NewIPHash ip hash 负载均衡 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 4:53 下午 2021/11/22 +func NewIPHash(severList []*define.ServerNode) (IBalance, error) { + if nil == severList || len(severList) == 0 { + return nil, errors.New("sever list is empty") + } + return &IPHash{ + base: base{ + lock: &sync.RWMutex{}, + severList: severList, + }, + serverList: severList, + }, nil +} + +// IPHash ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 4:57 下午 2021/11/22 +type IPHash struct { + base + serverList []*define.ServerNode +} + +// GetServerNode ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 4:53 下午 2021/11/22 +func (ih *IPHash) GetServerNode(req *http.Request) (*define.ServerNode, error) { + clintIPHashID := util.GetHashID(util.GetRemoteIp(req)) + ih.RLock() + defer ih.RUnlock() + if len(ih.serverList) == 0 { + return nil, errors.New("sever list is empty") + } + return ih.serverList[int(clintIPHashID%uint64(len(ih.serverList)))], nil +}