cohashing

package module
v0.0.0-...-4b18d82 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2024 License: MIT Imports: 6 Imported by: 0

README

cohashing

implement consistent hashing using golang

options

// Options represents the options for the hash ring
type Options struct {
	// Number of replicas for each node
	Replicas int

	// Hash function to use
	Hash hash.Hash
}

example

go get github.com/ISSuh/cohashing

use default hash(sha1)

pakcage (
    cohashing "github.com/ISSuh/cohashing"
)

type node struct {
    ID string
    IP string
}

func main() {
	ring := New[node]()

	n1 := node{ID: "node1", IP: "xxx.xxx.xxx.xxx"}
	n2 := node{ID: "node2", IP: "xxx.xxx.xxx.xxx"}

	ring.Put(n1.ID, n1)
	ring.Put(n2.ID, n2)

	node := ring.Locate("object-id")

    ...

    ring.Delete("node1")
}

set replicae nums or use user selected hash

pakcage (
    cohashing "github.com/ISSuh/cohashing"
)

type node struct {
    ID string
    IP string
}

func main() {
	hasher := sha256.New()
	option := Options{
		Replicas: 100,
		Hash:     hasher,
	}

	ring := NewWithOptions[node](option)

	n1 := node{ID: "node1", IP: "xxx.xxx.xxx.xxx"}
	n2 := node{ID: "node2", IP: "xxx.xxx.xxx.xxx"}

	ring.Put(n1.ID, n1)
	ring.Put(n2.ID, n2)

	node := ring.Locate("object-id")

    ...

    ring.Delete("node1")
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Options

type Options struct {
	// Number of replicas for each node
	Replicas int

	// Hash function to use
	Hash hash.Hash
}

Options represents the options for the hash ring

type Ring

type Ring[T any] struct {
	// contains filtered or unexported fields
}

Ring represents the consistent hash ring

func New

func New[T any]() *Ring[T]

Creates a new Ring with default options

func NewWithOptions

func NewWithOptions[T any](options Options) *Ring[T]

Creates a new Ring with options

func (*Ring[T]) AllItems

func (r *Ring[T]) AllItems() []T

AllItems returns all the items in the ring

func (*Ring[T]) Delete

func (r *Ring[T]) Delete(id string)

Delete a node from the hash ring

func (*Ring[T]) Len

func (r *Ring[T]) Len() int

Len returns the number of items in the ring

func (*Ring[T]) Locate

func (r *Ring[T]) Locate(id string) T

Get returns the nearby node for a given key

func (*Ring[T]) Put

func (r *Ring[T]) Put(id string, item T)

Put a node in the hash ring

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳