cashing

package module
v0.0.0-...-791dbf8 Latest Latest
Warning

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

Go to latest
Published: May 9, 2023 License: MIT Imports: 5 Imported by: 0

README

cashing

Consistency hashing library for Go applications

Installation

go get -u github.com/dcfranca/cashing

Usage

Create a new hash ring with 3 replicas (virtual nodes) and the default hash function The NodeType must implement the Stringer interface

	type NodeType string

	func (nt NodeType) String() string {
		return string(nt)
	}

	hashRing := NewHashRing[NodeType](3, nil)

Add 3 nodes to it

	hashRing.AddNode("node1")
	hashRing.AddNode("node2")
	hashRing.AddNode("node3")

Get the node to store your data, it returns a pointer to your NodeType

	key := "foobar"
	node := hashRing.GetNode(key)

Remove a node

    err := hashRing.RemoveNode("node2")
    if err != nil {
        fmt.Println("node not found")
    }

Use a custom hash function

	customHashFunction := func(key string) uint32 {
		hash := uint32(0)
		for _, char := range key {
			hash += uint32(char)
		}
		numTimesHashCalled++
		return hash
	}

	hashRing := NewHashRing[NodeType](1, customHashFunction)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type HashRing

type HashRing[T fmt.Stringer] struct {
	// contains filtered or unexported fields
}

func NewHashRing

func NewHashRing[T fmt.Stringer](replicas int, hash hashFunction) *HashRing[T]

Instantiate a new Hash Ring You can define your own hash function or pass nil to use the default one: sha1

func (*HashRing[T]) AddNode

func (hr *HashRing[T]) AddNode(node T)

Add a node to the hash ring The node parameter is a defined node type (must implement Stringer interface)

func (*HashRing[T]) GetNode

func (hr *HashRing[T]) GetNode(key string) *T

Get the node associated with the key

func (*HashRing[T]) RemoveNode

func (hr *HashRing[T]) RemoveNode(node T) error

Remove a node from the hash ring Returns an error in case the node is not found The node parameter is a defined node type (must implement Stringer interface)

Jump to

Keyboard shortcuts

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