cache

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

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

Go to latest
Published: Jun 21, 2025 License: MIT Imports: 3 Imported by: 2

README

LRU Cache in golang

go get https://github.com/dhyanio/go-lru
const (
  cacheCapabity  = 10
  cacheTTL       = 5 * time.Second
)

var evictFunc = func(key string, value []byte) {
  fmt.Printf("Evicted: %s -> %s\n", key, value)
}

cacheOpts := cache.CacheOpts{
  Capacity: cacheCapabity,
  TTL:      cacheTTL,
  OnEvict:  evictFunc,
}
cc := cache.NewCache(cacheOpts)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache struct {
	CacheOpts
	// contains filtered or unexported fields
}

Cache is an in-memory key-value store with a fixed capacity and TTL

func NewCache

func NewCache(opts CacheOpts) *Cache

NewCache creates a new cache with the specified capacity, TTL, and eviction callback

func (*Cache) Get

func (c *Cache) Get(key []byte) ([]byte, error)

Get retrieves an item from the cache and updates its usage

func (*Cache) Has

func (c *Cache) Has(key []byte) bool

Has checks if a key exists in the cache

func (*Cache) Put

func (c *Cache) Put(key, value []byte) error

Put inserts an item into the cache and updates its usage

func (*Cache) Stats

func (c *Cache) Stats() (hits, misses, evictions int)

Stats returns the cache hit, miss, and eviction counts

type CacheOpts

type CacheOpts struct {
	Capacity int
	TTL      time.Duration
	OnEvict  func(key string, value []byte)
}

CacheOpts contains the configuration options for a cache

type Cacher

type Cacher interface {
	// Put stores the given value in the cache with the specified key and
	// expiration duration. It returns an error if the operation fails.
	Put(key []byte, value []byte, duration time.Duration) error

	// Has checks if the given key exists in the cache. It returns true if
	// the key is found, otherwise false.
	Has(key []byte) bool

	// Get retrieves the value associated with the given key from the cache.
	// It returns the value and an error if the operation fails or the key
	// does not exist.
	Get(key []byte) ([]byte, error)
}

Cacher is an interface that defines methods for a cache system. It includes methods to put data into the cache, check for the existence of data, and retrieve data from the cache.

Jump to

Keyboard shortcuts

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