gocache

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2026 License: MIT Imports: 8 Imported by: 0

README

Compogo GoCache 🗃️

Compogo GoCache — это in-memory кэш для Compogo, построенный поверх популярной библиотеки patrickmn/go-cache. Предоставляет полный API оригинальной библиотеки, настраивается через флаги и может использоваться как самостоятельный кэш или как драйвер для централизованной системы кэширования Compogo Cache.

🚀 Установка

go get github.com/Compogo/gocache
📦 Быстрый старт
package main

import (
    "github.com/Compogo/compogo"
    "github.com/Compogo/gocache"
)

func main() {
    app := compogo.NewApp("myapp",
        compogo.WithOsSignalCloser(),
        gocache.Component,  // добавляем in-memory кэш
        compogo.WithComponents(
            userServiceComponent,
        ),
    )

    if err := app.Serve(); err != nil {
        panic(err)
    }
}

// Использование в сервисе
var userServiceComponent = &component.Component{
    Dependencies: component.Components{gocache.Component},
    Execute: component.StepFunc(func(c container.Container) error {
        return c.Invoke(func(cache gocache.Cache) {
            service := &UserService{cache: cache}
            service.Start()
        })
    }),
}

type UserService struct {
    cache gocache.Cache
}

func (s *UserService) GetUser(id int) (*User, error) {
    // Пытаемся достать из кэша
    if data, found := s.cache.Get(fmt.Sprintf("user:%d", id)); found {
        return data.(*User), nil
    }
    
    // Нет в кэше — грузим из БД
    user, err := s.db.LoadUser(id)
    if err != nil {
        return nil, err
    }
    
    // Кладём в кэш
    s.cache.Set(fmt.Sprintf("user:%d", id), user, cache.DefaultExpiration)
    
    return user, nil
}
✨ Возможности
🎯 Полный API go-cache

Интерфейс Cache повторяет все методы оригинальной библиотеки:

// Базовые операции
cache.Set("key", value, 5*time.Minute)
value, found := cache.Get("key")
cache.Delete("key")

// Атомарные инкременты для всех типов
cache.IncrementInt("counter", 1)
cache.DecrementFloat64("metric", 0.5)

// Работа с expiration
value, expTime, found := cache.GetWithExpiration("key")
cache.SetDefault("key", value) // использует TTL по умолчанию

// Очистка
cache.DeleteExpired()
cache.Flush()

// Персистентность
cache.SaveFile("cache.backup")
cache.LoadFile("cache.backup")

// Обработка событий
cache.OnEvicted(func(key string, value interface{}) {
    log.Printf("evicted: %s", key)
})
🔌 Два способа использования
Как самостоятельный кэш:
type Service struct {
    cache gocache.Cache  // через интерфейс
    // или
    raw *goCache.Cache    // напрямую
}
Как драйвер для централизованной системы кэширования:
import (
    "github.com/Compogo/cache"
    "github.com/Compogo/gocache/registration"
)

app := compogo.NewApp("myapp",
    cache.Component,
    gocache.Component,
    registration.Component,  // регистрирует "memory" драйвер
)

// Теперь можно использовать через cache.CacheInterface[[]byte]
// с флагом --cache.driver=memory

Documentation

Index

Constants

View Source
const (
	ExpirationFieldName      = "cache.memory.expiration"
	CleanupIntervalFieldName = "cache.memory.cleanup"

	ExpirationDefault      = 5 * time.Minute
	CleanupIntervalDefault = 10 * time.Minute
)

Variables

View Source
var Component = &component.Component{
	Init: component.StepFunc(func(container container.Container) error {
		return container.Provides(
			NewConfig,
			NewCache,
			func(cache *goCache.Cache) Cache { return cache },
		)
	}),
	BindFlags: component.BindFlags(func(flagSet flag.FlagSet, container container.Container) error {
		return container.Invoke(func(config *Config) {
			flagSet.DurationVar(
				&config.Expiration,
				ExpirationFieldName,
				ExpirationDefault,
				"default data retention time",
			)

			flagSet.DurationVar(
				&config.CleanupInterval,
				CleanupIntervalFieldName,
				CleanupIntervalDefault,
				"period for cleaning the cache from 'rotten' data",
			)
		})
	}),
	Configuration: component.StepFunc(func(container container.Container) error {
		return container.Invoke(Configuration)
	}),
}

Component is a ready-to-use Compogo component that provides an in-memory cache. It automatically:

  • Registers Config and Cache in the DI container
  • Adds command-line flags for expiration and cleanup interval
  • Configures the cache during Configuration phase
  • Provides the cache as both *goCache.Cache and Cache interface

Usage:

compogo.WithComponents(
    gocache.Component,
    // ... your service components
)

Then in your service:

type Service struct {
    cache gocache.Cache  // or *goCache.Cache
}

Functions

func NewCache

func NewCache(config *Config, informer logger.Informer) *goCache.Cache

NewCache creates a new in-memory cache instance. It initializes the underlying go-cache with the configured expiration and cleanup interval. The cache starts its cleanup goroutine automatically.

The informer is used to log the configuration for debugging purposes.

Types

type Cache

type Cache interface {
	Set(k string, x interface{}, d time.Duration)
	SetDefault(k string, x interface{})
	Add(k string, x interface{}, d time.Duration) error
	Replace(k string, x interface{}, d time.Duration) error
	Get(k string) (interface{}, bool)
	GetWithExpiration(k string) (interface{}, time.Time, bool)
	Increment(k string, n int64) error
	IncrementFloat(k string, n float64) error
	IncrementInt(k string, n int) (int, error)
	IncrementInt8(k string, n int8) (int8, error)
	IncrementInt16(k string, n int16) (int16, error)
	IncrementInt32(k string, n int32) (int32, error)
	IncrementInt64(k string, n int64) (int64, error)
	IncrementUint(k string, n uint) (uint, error)
	IncrementUintptr(k string, n uintptr) (uintptr, error)
	IncrementUint8(k string, n uint8) (uint8, error)
	IncrementUint16(k string, n uint16) (uint16, error)
	IncrementUint32(k string, n uint32) (uint32, error)
	IncrementUint64(k string, n uint64) (uint64, error)
	IncrementFloat32(k string, n float32) (float32, error)
	IncrementFloat64(k string, n float64) (float64, error)
	Decrement(k string, n int64) error
	DecrementFloat(k string, n float64) error
	DecrementInt(k string, n int) (int, error)
	DecrementInt8(k string, n int8) (int8, error)
	DecrementInt16(k string, n int16) (int16, error)
	DecrementInt32(k string, n int32) (int32, error)
	DecrementInt64(k string, n int64) (int64, error)
	DecrementUint(k string, n uint) (uint, error)
	DecrementUintptr(k string, n uintptr) (uintptr, error)
	DecrementUint8(k string, n uint8) (uint8, error)
	DecrementUint16(k string, n uint16) (uint16, error)
	DecrementUint32(k string, n uint32) (uint32, error)
	DecrementUint64(k string, n uint64) (uint64, error)
	DecrementFloat32(k string, n float32) (float32, error)
	DecrementFloat64(k string, n float64) (float64, error)
	Delete(k string)
	DeleteExpired()
	OnEvicted(f func(string, interface{}))
	Save(w io.Writer) (err error)
	SaveFile(fname string) error
	Load(r io.Reader) error
	LoadFile(fname string) error
	Items() map[string]goCache.Item
	ItemCount() int
	Flush()
}

Cache defines the complete interface for in-memory cache operations. It mirrors the full API of patrickmn/go-cache to provide maximum flexibility.

The interface includes methods for:

  • Basic operations: Set, Get, Delete
  • Atomic increments/decrements for all numeric types
  • Expiration management
  • Persistence (Save/Load to/from files)
  • Event handling (OnEvicted)
  • Cache inspection (Items, ItemCount)

type Config

type Config struct {
	Expiration      time.Duration
	CleanupInterval time.Duration
}

func Configuration

func Configuration(config *Config, configurator configurator.Configurator) *Config

func NewConfig

func NewConfig() *Config

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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