This is the 18th day of my participation in Gwen Challenge

If ❤️ my article is helpful, welcome to like, follow. This is the biggest encouragement for me to continue my technical creation. Coderdao.github. IO /

Golang implements consistent hash load balancing

Personal understanding: consistent hashing algorithm

  • Depending on each serverip:portOn one’s ownKey generation algorithmGenerates a unique key value
  • key => ip:portMake the machine uniquekeyMap machine access addressesip:portSet to aAn ordered circular circleon
  • When the request comes in, the content of the request is generated according to its ownKey generation algorithmAlso generates a requestkey
  • The request ofkeyAn ordered circular circleOn the machine’skeyCyclic contrast,The first oneThe machine’skeylarger-than-requestedkeyIt’s the optimal solution that handles the request
  • If requestedkeyAn ordered circular circleOn the machine’skeyAre big, then byFirst machine on the circleTo deal with
  • An ordered circular circleOn the machine, based on access. Add or delete machine mappings in near real time

Consistent hash load balancing specific coding implementation

Load polling test code

package load_balance

import (
	"fmt"
	"testing"
)

func TestNewConsistentHashBanlance(t *testing.T) {
	rb := NewConsistentHashBanlance(10.nil)
	rb.Add("127.0.0.1:2003") / / 0
	rb.Add("127.0.0.1:2004") / / 1
	rb.Add("127.0.0.1:2005") / / 2
	rb.Add("127.0.0.1:2006") / / 3
	rb.Add("127.0.0.1:2007") / / 4

	//url hash
	fmt.Println(rb.Get("http://127.0.0.1:2002/base/getinfo"))
	fmt.Println(rb.Get("http://127.0.0.1:2002/base/error"))
	fmt.Println(rb.Get("http://127.0.0.1:2002/base/getinfo"))
	fmt.Println(rb.Get("http://127.0.0.1:2002/base/changepwd"))

	//ip hash
	fmt.Println(rb.Get("127.0.0.1"))
	fmt.Println(rb.Get("192.168.0.1"))
	fmt.Println(rb.Get("127.0.0.1"))}Copy the code

The test results

$ go test
2021/06/18 19:17:57 Failed to connect to 127.0. 01.:2181: dial tcp 127.0. 01.:2181: i/o timeout
err zk: could not connect to a server
127.0. 01.:2004 <nil>
127.0. 01.:2005 <nil>
127.0. 01.:2004 <nil>
127.0. 01.:2005 <nil>
127.0. 01.:2007 <nil>
127.0. 01.:2003 <nil>
127.0. 01.:2007 <nil>
Copy the code