cache

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2026 License: MIT Imports: 5 Imported by: 0

README

Generic In-Memory Cache in Go

This repository contains an implementation of an in-memory cache in Go, using the new Go generics feature introduced in Go 1.18.

Features

  • Using Go 1.18 generics.
  • Thread-safe.
  • Auto cleanup of expired items.
  • Supports setting a cache item with a defined expiration duration.
  • Replace, Add, and Get cache items.

Usage

package main

import (
	"time"

	"github.com/go-orz/cache"
)

func main() {
	c := cache.New[string,string](time.Minute)

	c.Set("key", "value", 5*time.Minute)
	v, found := c.Get("key")
	if found {
		println(v)
	}
}

Concurrency

The cache package has built-in concurrency safety. It employs mutual exclusion locks (via sync.RWMutex) to assure multiple goroutines can operate on the data structure safely.

Error Handling

The package defines two error variables that methods can return:

  • ErrKeyAlreadyExists: Returned from the Add method if an attempt is made to add an item with a key that already exists in the cache.
  • ErrKeyNotExists: Returned from the Replace method if an attempt is made to replace an item with a key that doesn't exist.

Documentation

Index

Constants

View Source
const NeverExpired = 0
View Source
const ShardCount = 32

Variables

View Source
var (
	ErrKeyAlreadyExists = errors.New("key already exists")
	ErrKeyNotExists     = errors.New("key doesn't exists")
)

Functions

This section is empty.

Types

type Cache

type Cache[K comparable, V any] interface {
	Set(k K, v V, d time.Duration)
	Add(k K, v V, d time.Duration) error
	Replace(k K, v V, d time.Duration) error
	Get(k K) (V, bool)
	GetWithExpiration(k K) (V, time.Time, bool)
	Keys() []K
	Items() map[K]Item[V]
	Reset()
	ItemCount() int
	DeleteExpired()
	Delete(k K)
	DeleteWithoutCallback(k K)
}

Cache is the interface that represents common cache functionality.

func New

func New[K comparable, V any](cleanupInterval time.Duration, options ...Option[K, V]) Cache[K, V]

New creates a new cache with a given cleanup interval and callbacks for eviction and stopping events.

func NewSharded added in v0.0.3

func NewSharded[K comparable, V any](cleanupInterval time.Duration, options ...Option[K, V]) Cache[K, V]

type Item

type Item[V any] struct {
	Value   V
	Expires time.Time
}

Item represents a cache item that can hold any type.

func (Item[V]) Expired

func (item Item[V]) Expired() bool

Expired checks whether the cache item has expired.

type OnEvicted

type OnEvicted[K comparable, V any] func(K, V)

type OnStopped

type OnStopped func()

type Option

type Option[K comparable, V any] struct {
	OnEvicted OnEvicted[K, V]
	OnStopped OnStopped
}

Jump to

Keyboard shortcuts

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