memory_cache

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2024 License: MIT Imports: 9 Imported by: 0

README

Memory Cache

This is a simple memory cache manager.

It achieves thread safety through sync.RWMutex and automatically cleans up expired data using time.Ticker.

Features

  1. Thread-safe
  2. Support generics
  3. Expiration and auto cleanup
  4. Lightweight

API

// public functions
func NewMemoryCache[T any](optFuncs ...CacheOptionsFunc) *MemoryCache[T]

// option functions
func WithExpiration(expiration time.Duration) CacheOptionsFunc // global and peer item
func WithMaxSize(maxSize int) CacheOptionsFunc // global only
func WithLogger(log Logger) CacheOptionsFunc // global only
func WithCleanupInterval(interval time.Duration) CacheOptionsFunc // global only

// cache manager methods
Get(key string) (_ *T, ok bool)
Take(key string) (_ *T, ok bool)
Set(key string, value T, optionFunc ...CacheOptionsFunc) (err error)
Update(key string, updater func(value T) T, optionFunc ...CacheOptionsFunc) (ok bool)
Upsert(key string, updater func(value *T) *T, optionFunc ...CacheOptionsFunc) (err error)
Has(key string) (ok bool)
Delete(key string)
Clear()
Size() int
IsEmpty() bool
Keys() []string
Iterator() iter.Seq2[string, T] // for k, v := range cache.Iterator()

Examples

package main

import (
  "fmt"
  "log"
  "os"
  "time"

  memory_cache "github.com/hungtcs/memory-cache"
)

func main() {
  cache := memory_cache.NewMemoryCache[string](
    memory_cache.WithLogger(log.New(os.Stdout, "[MEMORY_CACHE] ", log.Ldate|log.Ltime|log.Lmsgprefix)), // set logger
    memory_cache.WithMaxSize(3),                   // may cause ErrCacheFull error
    memory_cache.WithCleanupInterval(time.Second), // set cleanup interval
    memory_cache.WithExpiration(time.Second*3),    // set default expiration
  )
  defer cache.Close()

  cache.Set("1", "a")
  cache.Set("2", "b")
  cache.Set("3", "c", memory_cache.WithExpiration(time.Second*10))
  cache.Set("4", "d") // error cache is full

  time.Sleep(time.Second * 5) // 1 and 2 is expired

  // only 3 is available
  fmt.Println("cache size: ", cache.Size())
  for key, val := range cache.Iterator() {
    fmt.Printf("key=%q value=%q\n", key, val)
  }
}

You can run this example on Go Playground https://goplay.tools/snippet/RMsIhR99d6y.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCacheFull   = fmt.Errorf("cache is full")
	ErrCacheClosed = fmt.Errorf("cache is closed")
)

Functions

func IsZeroValue

func IsZeroValue(v any) bool

func Pointer

func Pointer[T any](v T) *T

func SafeCall

func SafeCall(fn func()) (err error)

Types

type CacheItem

type CacheItem[T any] struct {
	Value     T
	ExpiresAt time.Time
}

func (*CacheItem[T]) IsExpired

func (c *CacheItem[T]) IsExpired() bool

type CacheItemOptions

type CacheItemOptions struct {
	Expiration time.Duration // default 0, nit expire
}

type CacheOptions

type CacheOptions struct {
	Logger          Logger
	MaxSize         int           // default 0, not limit
	Expiration      time.Duration // default 0, nit expire
	CleanupInterval time.Duration // default 30s
}

type CacheOptionsFunc

type CacheOptionsFunc func(options *CacheOptions)

func WithCleanupInterval

func WithCleanupInterval(interval time.Duration) CacheOptionsFunc

Set cleanup interval, only working with new function

func WithExpiration

func WithExpiration(expiration time.Duration) CacheOptionsFunc

Set expiration time, which can be used globally or set separately during Set

func WithLogger

func WithLogger(log Logger) CacheOptionsFunc

Set logger, only working with new function

func WithMaxSize

func WithMaxSize(maxSize int) CacheOptionsFunc

Set cache max size, only working with new function

type Logger

type Logger interface {
	Printf(format string, v ...interface{})
}

type MemoryCache

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

func NewMemoryCache

func NewMemoryCache[T any](optFuncs ...CacheOptionsFunc) *MemoryCache[T]

NewMemoryCache returns a new MemoryCache. Support options:

  • WithLogger
  • WithMaxSize
  • WithExpiration
  • WithCleanupInterval

func (*MemoryCache[T]) Clear

func (c *MemoryCache[T]) Clear()

Clear the cache, remove all items

func (*MemoryCache[T]) Close

func (c *MemoryCache[T]) Close()

stop ticker and clear all data

func (*MemoryCache[T]) Delete

func (c *MemoryCache[T]) Delete(key string)

Delete the value for the given key

func (*MemoryCache[T]) Get

func (c *MemoryCache[T]) Get(key string) (_ *T, ok bool)

Get returns the value for the given key, or nil if not found

func (*MemoryCache[T]) Has

func (c *MemoryCache[T]) Has(key string) (ok bool)

Has returns true if the cache contains the given key

func (*MemoryCache[T]) IsEmpty

func (c *MemoryCache[T]) IsEmpty() bool

IsEmpty returns true if the cache is empty

func (*MemoryCache[T]) Iterator

func (c *MemoryCache[T]) Iterator() iter.Seq2[string, T]

for go range loop

func (*MemoryCache[T]) Keys

func (c *MemoryCache[T]) Keys() []string

Keys returns all the keys in the cache.

func (*MemoryCache[T]) Set

func (c *MemoryCache[T]) Set(key string, value T, optionFunc ...CacheOptionsFunc) (err error)

Set the value for the given key

func (*MemoryCache[T]) Size

func (c *MemoryCache[T]) Size() int

Size returns the number of items in the cache

func (*MemoryCache[T]) Take

func (c *MemoryCache[T]) Take(key string) (_ *T, ok bool)

Take returns the value for the given key, and remove it from cache if it exists

func (*MemoryCache[T]) Update

func (c *MemoryCache[T]) Update(key string, updater func(value T) T, optionFunc ...CacheOptionsFunc) (ok bool)

Update the value for the given key, do nothing if the key does not exist

func (*MemoryCache[T]) Upsert

func (c *MemoryCache[T]) Upsert(key string, updater func(value *T) *T, optionFunc ...CacheOptionsFunc) (err error)

Upsert the value for the given key, create a new value if the key does not exist. Do nothing is updater returns nil

Jump to

Keyboard shortcuts

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