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 server
ip:port
On one’s ownKey generation algorithm
Generates a unique key value key => ip:port
Make the machine uniquekey
Map machine access addressesip:port
Set to aAn ordered circular circle
on- When the request comes in, the content of the request is generated according to its own
Key generation algorithm
Also generates a requestkey
- The request of
key
和An ordered circular circle
On the machine’skey
Cyclic contrast,The first oneThe machine’skey
larger-than-requestedkey
It’s the optimal solution that handles the request - If requested
key
比An ordered circular circle
On the machine’skey
Are big, then byFirst machine on the circle
To deal with An ordered circular circle
On 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