Last active
August 29, 2015 14:07
-
-
Save eddking/3557aa0242a09c225f94 to your computer and use it in GitHub Desktop.
A simple example of a hash ring using go.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
jump "github.com/anachronistic/jump-consistent-hash" | |
) | |
type Ring struct { | |
VirtualNodes uint64 | |
RealNodes []string | |
Replication int32 | |
} | |
type Location struct { | |
Key uint64 | |
VirtualNode uint64 | |
RealNodes []string | |
} | |
func (ring *Ring) getVirtualNode(key uint64) uint64 { | |
return key % ring.VirtualNodes | |
} | |
func (ring *Ring) getRealNodes(virtualNode uint64) []string { | |
startIndex := jump.Hash(virtualNode, int32(len(ring.RealNodes))) | |
realNodes := make([]string, ring.Replication) | |
var i int32 | |
for i = 0; i < ring.Replication; i++ { | |
realNodes[i] = ring.RealNodes[(startIndex+i)%int32(len(ring.RealNodes))] | |
} | |
return realNodes | |
} | |
func (ring *Ring) GetKeyLocation(key uint64) Location { | |
virtualNode := ring.getVirtualNode(key) | |
realNodes := ring.getRealNodes(virtualNode) | |
return Location{ | |
key, | |
virtualNode, | |
realNodes, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment