chash

package module
v1.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 4, 2024 License: MIT Imports: 5 Imported by: 3

README

English | 简体中文

chash

Consistent hashing written by Go

What is consistent hashing

Consistent hashing is a hashing technique that performs really well when operated in a dynamic environment where the distributed system scales up and scales down frequently.

Consistent Hashing allows distributing data in such a way that minimize reorganization when nodes are added or removed, hence making the system easier to scale up or down.

The key idea is that it's a distribution scheme that DOES NOT depend directly on the number of servers.

In Consistent Hashing, when the hash table is resized, in general only k / n keys need to be remapped, where k is the total number of keys and n is the total number of servers.

When a new node is added, it takes shares from a few hosts without touching other's shares When a node is removed, its shares are shared by other hosts.

Getting started

With Go module support, simply add the following import

import "github.com/werbenhu/chash"

Simple Usage

Create a group
// Create a group named "db" with 10000 virtual elements for each key
// which internally manages the group using a global singleton chash object.
dbGroup, _ := chash.CreateGroup("db", 10000)

// Insert elements (multiple MySQL servers).
dbGroup.Insert("192.168.1.100:3306", []byte("mysql0-info"))
dbGroup.Insert("192.168.1.101:3306", []byte("mysql1-info"))

// Create a second group.
webGroup, _ := chash.CreateGroup("web", 10000)

// Insert elements (multiple HTTP servers).
webGroup.Insert("192.168.2.100:80", []byte("web0-info"))
webGroup.Insert("192.168.2.101:80", []byte("web1-info"))
// Use an existing group.
dbGroup, err := chash.GetGroup("db")
if err != nil {
    log.Printf("ERROR get group failed, err:%s\n", err.Error())
}

dbGroup.Insert("192.168.1.103:3306", []byte("mysql3-info"))
host, info, err := dbGroup.Match("user-id")
Match a MySQL server for a user ID
// match an element close to where key hashes to in the circle.
host, info, err := dbGroup.Match("user-id")
Delete element from a group
// delete element
dbGroup.Delete("192.168.1.102:3306")
Get all elements of a group
elements := dbGroup.GetElemens()
Using an independent group
// A group created by chash.NewGrou() is not managed by the global chash object
// You need to manage groups yourself if there are more than one group.
group := chash.NewGroup("db", 10000)

group.Insert("192.168.1.100:3306", []byte("mysql0-info"))
group.Insert("192.168.1.101:3306", []byte("mysql1-info"))
host, info, err := group.Match("user-id")

Examples

See the example .

Contributions

Contributions and feedback are both welcomed and encouraged! Open an issue to report a bug, ask a question, or make a feature request.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrGroupNotFound   = err{Code: 10000, Msg: "group not found"}
	ErrGroupExisted    = err{Code: 10001, Msg: "group already existed"}
	ErrNoResultMatched = err{Code: 10002, Msg: "no result matched"}
	ErrKeyExisted      = err{Code: 10003, Msg: "key already existed"}
)

Several global variables that represent common errors that may be returned by the CHash functions.

Functions

func RemoveAllGroup added in v1.0.8

func RemoveAllGroup()

RemoveAllGroup removes all groups from the CHash instance.

func RemoveGroup added in v1.0.3

func RemoveGroup(groupName string)

RemoveGroup removes the specified group from the CHash instance.

func Restore added in v1.0.2

func Restore(data []byte) error

Restore restores the CHash object from serialized data.

func Serialize added in v1.0.2

func Serialize() ([]byte, error)

Serialize serializes the entire CHash object to a byte slice.

Types

type CHash

type CHash struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

CHash a warpper of Consistent hashing

func New

func New() *CHash

func (*CHash) CreateGroup added in v1.0.3

func (c *CHash) CreateGroup(groupName string, replicas int) (*Group, error)

CreateGroup creates a new group with the given name and the number of replicas

func (*CHash) Delete added in v1.0.3

func (c *CHash) Delete(groupName string, key string) error

Delete removes a key from a group

func (*CHash) GetGroup added in v1.0.3

func (c *CHash) GetGroup(groupName string) (*Group, error)

GetGroup retrieves a group by name

func (*CHash) Insert added in v1.0.3

func (c *CHash) Insert(groupName string, key string, payload []byte) error

Insert inserts a new key-value pair into a group

func (*CHash) Match

func (c *CHash) Match(groupName string, key string) (string, []byte, error)

Match returns the key-value pair closest to the given key in a group

func (*CHash) RemoveAllGroup added in v1.0.7

func (c *CHash) RemoveAllGroup()

RemoveAllGroup removes all groups

func (*CHash) RemoveGroup added in v1.0.3

func (c *CHash) RemoveGroup(groupName string)

RemoveGroup removes a group by name

func (*CHash) Restore

func (c *CHash) Restore(data []byte) error

Restore deserializes a JSON representation of the CHash structure

func (*CHash) Serialize

func (c *CHash) Serialize() ([]byte, error)

Serialize serializes the CHash structure to JSON

type Circle added in v1.0.4

type Circle []uint32

func (Circle) Len added in v1.0.4

func (idx Circle) Len() int

Len returns the length of the circle.

func (Circle) Less added in v1.0.4

func (idx Circle) Less(i, j int) bool

Less compares the elements at positions i and j in the slice and returns true if the element at position i is less than the element at position j.

func (Circle) Match added in v1.0.4

func (idx Circle) Match(target uint32) (int, bool)

Match returns the index of the element in the slice that is closest to target. If target is greater than all elements in the slice, it returns the last index; if target is less than all elements in the slice, it returns the last index.

func (Circle) Search added in v1.0.4

func (idx Circle) Search(target uint32) (int, bool)

Search searches for the index of target in the sorted slice. It returns the index and true if target is found, or 0 and false otherwise.

func (Circle) Sort added in v1.0.4

func (idx Circle) Sort()

Sort sorts the elements in the slice in ascending order.

func (Circle) Swap added in v1.0.4

func (idx Circle) Swap(i, j int)

Swap swaps the elements at positions i and j in the circle.

type Element added in v1.0.4

type Element struct {
	Key     string `json:"key"`
	Payload []byte `json:"payload"`
}

Element represents a single element to be stored in the cache

type Group added in v1.0.3

type Group struct {
	sync.RWMutex
	Name             string              `json:"name"`
	NumberOfReplicas int                 `json:"numberOfReplicas"`
	Elements         map[string]*Element `json:"elements"`
	// contains filtered or unexported fields
}

Group represents a group of elements to be stored in the cache

func CreateGroup added in v1.0.3

func CreateGroup(groupName string, replicas int) (*Group, error)

CreateGroup creates a new group in the CHash instance and returns a pointer to the Group object. If the group already exists, it returns an error.

func GetGroup added in v1.0.3

func GetGroup(groupName string) (*Group, error)

GetGroup retrieves the specified group from the CHash instance.

func NewGroup added in v1.0.3

func NewGroup(name string, replicas int) *Group

NewGroup creates a new cache group with the given name and number of replicas

func (*Group) Delete added in v1.0.3

func (b *Group) Delete(key string)

Delete removes an element from the group

func (*Group) GetElements added in v1.0.5

func (b *Group) GetElements() []*Element

GetElements get all elements from the group

func (*Group) Init added in v1.0.3

func (b *Group) Init()

Init initializes the group's elements, circle, and rows maps

func (*Group) Insert added in v1.0.3

func (b *Group) Insert(key string, payload []byte) error

Insert adds a new element to the group

func (*Group) Match added in v1.0.3

func (b *Group) Match(key string) (string, []byte, error)

Match returns the key-value pair closest to the given key in a group

func (*Group) Upsert added in v1.0.6

func (b *Group) Upsert(key string, payload []byte) error

Upsert adds or updates an element in the group

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL