The Hasher library implements a hashing algorithm on a given key string or UUID and returns the server to which the request should be sent.
Consistent hashing is one such algorithm that minimizes the number of updates required to associate the request with the appropriate server.
This addresses the common problem of reassigning servers that arises when using the modulo operation.
Installation
go get github.com/kounkou/hasherprovider
Usage
package main
import (
"fmt"
"github.com/kounkou/hasherprovider"
)
const (
CONSISTENT_HASHING = 0
RANDOM_HASHING = 1
UNIFORM_HASHING = 2
)
func main() {
// Create a new HasherProvider object
hasherprovider := hasherprovider.HasherProvider{ }
// Get the consistent hashing function
h, err := hasherprovider.GetHasher(CONSISTENT_HASHING)
// Set replicas entities
h.SetReplicas(1)
if h == nil || err != nil {
fmt.Println("Error getting hasher:", err)
return
}
h.AddNode("server1")
h.AddNode("server2")
h.AddNode("server3")
result, err := h.Hash("9", 0)
if err != nil {
fmt.Println("Error getting hash for some string `9` ", err)
}
if result != "server2" {
fmt.Errorf("Expected replica to be assigned is server2")
return
}
fmt.Println("Success... !")
}
Algorithms
HasherProvider currently supports 3 algorithms. You might want to choose your hashing algorithm based on the following characteristics :