imcache

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2026 License: MIT Imports: 6 Imported by: 0

README

High-Performance In-Memory Cache for Go

A production-ready, high-performance, thread-safe in-memory cache implementation with generics support.

Features

  • High Performance: Sharded design for minimal lock contention
  • Thread-Safe: Safe for concurrent access from multiple goroutines
  • Type-Safe: Full generics support
  • TTL Support: Individual expiration times per key
  • Automatic Cleanup: Background cleanup of expired entries
  • Callbacks: OnEvict, OnHit, OnMiss hooks
  • Size Limits: Optional maximum cache size
  • Graceful Shutdown: Proper cleanup and resource release

Performance

The cache is designed for high performance:

  • Sharded Design: Multiple shards reduce lock contention
  • Optimized Locking: Read-write mutexes for each shard
  • Zero-Allocation: Minimized allocations in hot paths
  • Fast Hashing: FNV-1a hash for key distribution

Installation

go get github.com/chub-es/imcache

Usage

package main

import (
    "fmt"
    "time"
    "github.com/chub-es/imcache"
)

func main() {
    // Создать новый кэш с параметрами по умолчанию
    c := cache.New[string]()
    defer c.Close()
    
    // Установите значение с параметром TTL по умолчанию
    c.Set("greeting", "Hello, World!")
    
    // Установлено пользовательское значение TTL
    c.Set("temp", "This expires", 5*time.Second)
    
    // Получить значение
    if val, err := c.Get("greeting"); err == nil {
        fmt.Println(val)
    }
}

Advanced Usage

With Options
c := cache.New[User](
    cache.WithDefaultTTL[User](10*time.Minute),
    cache.WithCleanupInterval[User](1*time.Minute),
    cache.WithStats[User](),
    cache.WithMaxSize[User](10000),
    cache.WithShards[User](64),
    cache.WithOnEvict[User](func(key string, user User) {
        log.Printf("User %s evicted", user.Name)
    }),
)
Type-Safe Cache
type User struct {
    ID    int
    Name  string
    Email string
}

userCache := cache.New[User]()
userCache.Set("user:123", User{ID: 1, Name: "Petya", Email: "petya@example.com"})

if user, err := userCache.Get("user:1"); err == nil {
    fmt.Printf("Found user: %s", user.Name)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrKeyNotFound возвращается когда ключ не найден в кэше
	ErrKeyNotFound = errors.New("imcache: key not found")

	// ErrKeyExpired возвращается когда ключ найден но истек
	ErrKeyExpired = errors.New("imcache: key expired")

	// ErrCacheClosed возвращается при попытке использовать закрытый кэш
	ErrCacheClosed = errors.New("imcache: cache is closed")

	// ErrInvalidTTL возвращается при указании невалидного TTL
	ErrInvalidTTL = errors.New("imcache: invalid ttl")

	// ErrInvalidKey возвращается при указании пустого ключа
	ErrInvalidKey = errors.New("imcache: invalid key")

	// ErrShardSizeLimit возвращается при записи нового ключа в заполненный шард
	ErrShardSizeLimit = errors.New("imcache: cache shard is full")
)

Functions

This section is empty.

Types

type Cache

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

Cache представляет in-memory кэш с шардированием

func New

func New[T any](opts ...Option[T]) *Cache[T]

New создает новый экземпляр кэша с опциями

func (*Cache[T]) Clear

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

Clear очищает весь кэш

func (*Cache[T]) Close

func (c *Cache[T]) Close() error

Close закрывает кэш и останавливает фоновые процессы

func (*Cache[T]) Contains

func (c *Cache[T]) Contains(key string) bool

Contains проверяет существование ключа

func (*Cache[T]) Delete

func (c *Cache[T]) Delete(key string) error

Delete удаляет значение из кэша

func (*Cache[T]) Expire

func (c *Cache[T]) Expire(key string, ttl time.Duration) bool

Expire устанавливает новое время жизни

func (*Cache[T]) Get

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

Get получает значение из кэша

func (*Cache[T]) Keys

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

Keys возвращает все ключи

func (*Cache[T]) Len

func (c *Cache[T]) Len() int

Len возвращает общее количество элементов

func (*Cache[T]) Range

func (c *Cache[T]) Range(f func(key string, value T) bool)

Range итерируется по всем элементам

func (*Cache[T]) Set

func (c *Cache[T]) Set(key string, value T, ttl ...time.Duration) error

Set добавляет значение в кэш

func (*Cache[T]) TTL

func (c *Cache[T]) TTL(key string) time.Duration

TTL возвращает оставшееся время жизни

type CacheWithContext

type CacheWithContext[T any] struct {
	*Cache[T]
	// contains filtered or unexported fields
}

WithContext создает контекстный кэш с поддержкой отмены

func NewWithContext

func NewWithContext[T any](ctx context.Context, opts ...Option[T]) *CacheWithContext[T]

NewWithContext создает кэш с контекстом

type Config

type Config[T any] struct {
	// DefaultTTL - TTL по умолчанию для новых записей (0 = бесконечно)
	DefaultTTL time.Duration

	// CleanupInterval - интервал автоматической очистки (0 = отключено)
	CleanupInterval time.Duration

	// OnEvict - колбэк вызываемый при удалении записи
	OnEvict func(key string, value T)

	// OnMiss - колбэк вызываемый при промахе кэша
	OnMiss func(key string)

	// OnHit - колбэк вызываемый при попадании в кэш
	OnHit func(key string)

	// EnableStats - включить сбор статистики
	EnableStats bool

	// MaxSize - максимальное количество записей (0 = без ограничений)
	MaxSize int

	// ShardCount - количество шардов для уменьшения блокировок (0 = авто)
	ShardCount int

	// EnableLogging - включить логирование
	EnableLogging bool
}

Config содержит конфигурацию кэша

func DefaultConfig

func DefaultConfig[T any]() Config[T]

DefaultConfig возвращает конфигурацию по умолчанию

type Option

type Option[T any] func(*Config[T])

Option определяет функциональную опцию для конфигурации кэша

func WithCleanupInterval

func WithCleanupInterval[T any](interval time.Duration) Option[T]

WithCleanupInterval устанавливает интервал очистки

func WithDefaultTTL

func WithDefaultTTL[T any](ttl time.Duration) Option[T]

WithDefaultTTL устанавливает TTL по умолчанию

func WithMaxSize

func WithMaxSize[T any](size int) Option[T]

WithMaxSize устанавливает максимальный размер кэша

func WithOnEvict

func WithOnEvict[T any](fn func(key string, value T)) Option[T]

WithOnEvict устанавливает колбэк при удалении

func WithOnHit

func WithOnHit[T any](fn func(key string)) Option[T]

WithOnHit устанавливает колбэк при попадании

func WithOnMiss

func WithOnMiss[T any](fn func(key string)) Option[T]

WithOnMiss устанавливает колбэк при промахе

func WithShards

func WithShards[T any](count int) Option[T]

WithShards устанавливает количество шардов

Jump to

Keyboard shortcuts

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