Golang實現四種負載均衡的算法(隨機,輪詢等)

隨機負載

隨機挑選目標服務器

package load_balance

import (
 "errors"
 "math/rand"
)

//隨機負載均衡
type RandomBalance struct {
 curIndex int

 rss []string
}

func (r *RandomBalance) Add(params ...string) error {
 if len(params) == 0 {
  return errors.New("params len 1 at least")
 }
 addr := params[0]
 r.rss = append(r.rss, addr)

 return nil
}

func (r *RandomBalance) Next() string {
 if len(r.rss) == 0 {
  return ""
 }
 r.curIndex = rand.Intn(len(r.rss))
 return r.rss[r.curIndex]
}

func (r *RandomBalance) Get(string) (string, error) {
 return r.Next(), nil
}

輪詢負載

服務器依次輪詢

package load_balance

import "errors"

//輪詢負載均衡
type RoundRobinBalance struct {
 curIndex int
 rss      []string
}

func (r *RoundRobinBalance) Add(params ...string) error {
 if len(params) == 0 {
  return errors.New("params len 1 at least")
 }

 addr := params[0]
 r.rss = append(r.rss, addr)
 return nil
}

func (r *RoundRobinBalance) Next() string {
 if len(r.rss) == 0 {
  return ""
 }
 lens := len(r.rss)
 if r.curIndex >= lens {
  r.curIndex = 0
 }

 curAddr := r.rss[r.curIndex]
 r.curIndex = (r.curIndex + 1) % lens
 return curAddr
}

func (r *RoundRobinBalance) Get(string) (string, error) {
 return r.Next(), nil
}

加權輪詢負載

給目標設置訪問權重,按照權重輪詢

package load_balance

import (
 "errors"
 "strconv"
)

type WeightRoundRobinBalance struct {
 curIndex int
 rss      []*WeightNode
 rsw      []int
}

type WeightNode struct {
 addr            string
 Weight          int //初始化時對節點約定的權重
 currentWeight   int //節點臨時權重,每輪都會變化
 effectiveWeight int //有效權重, 默認與weight相同 , totalWeight = sum(effectiveWeight)  //出現故障就-1
}

//1, currentWeight = currentWeight + effectiveWeight
//2, 選中最大的currentWeight節點為選中節點
//3, currentWeight = currentWeight - totalWeight

func (r *WeightRoundRobinBalance) Add(params ...string) error {
 if len(params) != 2 {
  return errors.New("params len need 2")
 }
 parInt, err := strconv.ParseInt(params[1], 10, 64)
 if err != nil {
  return err
 }
 node := &WeightNode{
  addr:   params[0],
  Weight: int(parInt),
 }
 node.effectiveWeight = node.Weight
 r.rss = append(r.rss, node)
 return nil
}

func (r *WeightRoundRobinBalance) Next() string {
 var best *WeightNode
 total := 0
 for i := 0; i < len(r.rss); i++ {
  w := r.rss[i]
  //1 計算所有有效權重
  total += w.effectiveWeight
  //2 修改當前節點臨時權重
  w.currentWeight += w.effectiveWeight
  //3 有效權重默認與權重相同,通訊異常時-1, 通訊成功+1,直到恢復到weight大小
  if w.effectiveWeight < w.Weight {
   w.effectiveWeight++
  }

  //4 選中最大臨時權重節點
  if best == nil || w.currentWeight > best.currentWeight {
   best = w
  }
 }

 if best == nil {
  return ""
 }
 //5 變更臨時權重為 臨時權重-有效權重之和
 best.currentWeight -= total
 return best.addr
}

func (r *WeightRoundRobinBalance) Get(string) (string, error) {
 return r.Next(), nil
}

func (r *WeightRoundRobinBalance) Update()  {

}

一致性hash

請求固定的URL訪問指定的IP

package load_balance

import (
 "errors"
 "hash/crc32"
 "sort"
 "strconv"
 "sync"
)

//1 單調性(唯一) 2平衡性 (數據 目標元素均衡) 3分散性(散列)
type Hash func(data []byte) uint32

type UInt32Slice []uint32

func (s UInt32Slice) Len() int {
 return len(s)
}

func (s UInt32Slice) Less(i, j int) bool {
 return s[i] < s[j]
}

func (s UInt32Slice) Swap(i, j int) {
 s[i], s[j] = s[j], s[i]
}

type ConsistentHashBalance struct {
 mux      sync.RWMutex
 hash     Hash
 replicas int               //復制因子
 keys     UInt32Slice       //已排序的節點hash切片
 hashMap  map[uint32]string //節點哈希和key的map, 鍵是hash值,值是節點key
}

func NewConsistentHashBalance(replicas int, fn Hash) *ConsistentHashBalance {
 m := &ConsistentHashBalance{
  replicas: replicas,
  hash:     fn,
  hashMap:  make(map[uint32]string),
 }
 if m.hash == nil {
  //最多32位,保證是一個2^32-1環
  m.hash = crc32.ChecksumIEEE
 }
 return m
}

func (c *ConsistentHashBalance) IsEmpty() bool {
 return len(c.keys) == 0
}

// Add 方法用來添加緩存節點,參數為節點key,比如使用IP
func (c *ConsistentHashBalance) Add(params ...string) error {
 if len(params) == 0 {
  return errors.New("param len 1 at least")
 }

 addr := params[0]
 c.mux.Lock()
 defer c.mux.Unlock()

 // 結合復制因子計算所有虛擬節點的hash值,並存入m.keys中,同時在m.hashMap中保存哈希值和key的映射
 for i := 0; i < c.replicas; i++ {
  hash := c.hash([]byte(strconv.Itoa(i) + addr))
  c.keys = append(c.keys, hash)
  c.hashMap[hash] = addr
 }

 // 對所有虛擬節點的哈希值進行排序,方便之後進行二分查找
 sort.Sort(c.keys)
 return nil
}

// Get 方法根據給定的對象獲取最靠近它的那個節點
func (c *ConsistentHashBalance) Get(key string) (string, error) {
 if c.IsEmpty() {
  return "", errors.New("node is empty")
 }
 hash := c.hash([]byte(key))

 // 通過二分查找獲取最優節點,第一個"服務器hash"值大於"數據hash"值的就是最優"服務器節點"
 idx := sort.Search(len(c.keys), func(i int) bool { return c.keys[i] >= hash })

 // 如果查找結果 大於 服務器節點哈希數組的最大索引,表示此時該對象哈希值位於最後一個節點之後,那麼放入第一個節點中
 if idx == len(c.keys) {
  idx = 0
 }
 c.mux.RLock()
 defer c.mux.RUnlock()
 return c.hashMap[c.keys[idx]], nil
}

封裝

定義LoadBalance接口

package load_balance

type LoadBalance interface {
 Add(...string) error
 Get(string)(string, error)

}

工廠方法

package load_balance

type LbType int

const (
 LbRandom LbType = iota
 LbRoundRobin
 LbWeightRoundRobin
 LbConsistentHash
)

func LoadBalanceFactory(lbType LbType) LoadBalance {
 switch lbType {
 case LbRandom:
  return &RandomBalance{}
 case LbConsistentHash:
  return NewConsistentHashBalance(10, nil)
 case LbRoundRobin:
  return &RoundRobinBalance{}
 case LbWeightRoundRobin:
  return &WeightRoundRobinBalance{}
 default:
  return &RandomBalance{}
 }
}

到此這篇關於Golang實現四種負載均衡的算法(隨機,輪詢等)的文章就介紹到這瞭,更多相關Golang 負載均衡內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: