cache

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: MIT Imports: 15 Imported by: 2 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Compogo Cache 📦

Compogo Cache — это гибкая и расширяемая система кэширования для Go, построенная поверх gocache. Поддерживает множество драйверов (Redis, BigCache, Ristretto и др.) через простую систему регистрации, полностью интегрируется с Compogo и автоматически добавляет Prometheus-метрики.

🚀 Установка

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

import (
    "github.com/Compogo/compogo"
    "github.com/Compogo/cache"
    "github.com/Compogo/cache/redis"  // подключаем Redis-драйвер
)

func main() {
    app := compogo.NewApp("myapp",
        compogo.WithOsSignalCloser(),
        cache.Component,           // базовый компонент кэша
        redis.Component,           // регистрируем Redis-драйвер
        compogo.WithComponents(
            userServiceComponent,
        ),
    )

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

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

type UserService struct {
    cache cache.CacheInterface[[]byte]
}

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

Кэш поддерживает любые бэкенды через систему регистрации:

// Регистрация нового драйвера (в пакете драйвера)
func init() {
    cache.Registration("redis", NewRedisStore)
    cache.Registration("bigcache", NewBigCacheStore)
    cache.Registration("ristretto", NewRistrettoStore)
}
⚙️ Конфигурация через флаги
./myapp \
    --cache.driver=redis \
    --cache.expiration=10m

Если зарегистрирован только один драйвер, он автоматически становится значением по умолчанию.

🔧 Создание своего драйвера
package mydriver

import (
    "github.com/Compogo/compogo/container"
    "github.com/Compogo/cache"
    "github.com/eko/gocache/lib/v4/store"
)

func init() {
    cache.Registration("mydriver", NewMyDriverStore)
}

func NewMyDriverStore(container container.Container) (store.StoreInterface, error) {
    // Достаём зависимости из контейнера
    var config *Config
    container.Invoke(func(cfg *Config) {
        config = cfg
    })
    
    // Создаём и возвращаем store
    return mydriver.NewStore(config), nil
}

Documentation

Index

Constants

View Source
const (
	DriverFieldName     = "cache.driver"
	ExpirationFieldName = "cache.expiration"

	ExpirationDefault = 5 * time.Minute
)

Variables

View Source
var Component = &component.Component{
	Init: component.StepFunc(func(container container.Container) error {
		return container.Provides(
			NewConfig,
			NewCache,
		)
	}),
	BindFlags: component.BindFlags(func(flagSet flag.FlagSet, container container.Container) error {
		return container.Invoke(func(config *Config) {
			allDrivers := drivers.Keys()
			if len(allDrivers) == 1 {
				DriverDefault = allDrivers[0]
			}

			flagSet.StringVar(&config.driver, DriverFieldName, DriverDefault, fmt.Sprintf("cache driver. Available drivers: [%s]", strings.Join(allDrivers, ",")))
			flagSet.DurationVar(&config.Expiration, ExpirationFieldName, ExpirationDefault, "default data retention time")
		})
	}),
	Configuration: component.StepFunc(func(container container.Container) error {
		return container.Invoke(Configuration)
	}),
}

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

  • Registers Config and Cache factory in the DI container
  • Adds command-line flags for driver selection and TTL
  • Validates the selected driver during Configuration phase
  • Sets the default driver automatically if only one is registered

Usage:

compogo.WithComponents(
    cache.Component,
    // ... driver components (redis, bigcache, etc.)
)

Then in your service:

type Service struct {
    cache cache.CacheInterface[[]byte]
}
View Source
var DriverDefault = ""

Functions

func NewCache

func NewCache(config *Config, appConfig *compogo.Config, logger logger.Logger, container container.Container) (cache.CacheInterface[[]byte], error)

NewCache creates a new cache instance with the selected driver. It:

  • Looks up the getter function for the configured driver
  • Creates the underlying store using the getter
  • Wraps it with Prometheus metrics (using the app name as a label)
  • Returns a cache.CacheInterface that can be used throughout the application

The returned cache is generic over []byte, but gocache's cache.CacheInterface can work with any serializable type through marshaling/unmarshaling.

func Registration

func Registration(d Driver, getter Getter)

Registration registers a new cache driver with its factory function. This should be called from driver packages (e.g., redis, bigcache) during init().

Example:

func init() {
	cache.Registration("redis", NewRedisStore)
}

Types

type Config

type Config struct {
	Driver     Driver
	Expiration time.Duration
	// contains filtered or unexported fields
}

func Configuration

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

func NewConfig

func NewConfig() *Config

type Driver

type Driver string

Driver is a type-safe identifier for cache backends. It implements fmt.Stringer for logging and display.

func (Driver) String

func (d Driver) String() string

String returns the driver name as a string.

type Getter

type Getter func(container container.Container) (store.StoreInterface, error)

Getter is a factory function that creates a cache store from a DI container. It receives the container to resolve any dependencies the store might need (configuration, connections, etc.) and returns a store.StoreInterface.

Jump to

Keyboard shortcuts

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