cache

package
v0.0.0-...-8be54c4 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2025 License: Apache-2.0 Imports: 5 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCacheMiss = fmt.Errorf("cache miss")
)

Errors

Functions

This section is empty.

Types

type Cache

type Cache interface {
	Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
	Get(ctx context.Context, key string, dest interface{}) error
	Delete(ctx context.Context, keys ...string) error
	Exists(ctx context.Context, key string) (bool, error)
	SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) (bool, error)
	Increment(ctx context.Context, key string) (int64, error)
	IncrementBy(ctx context.Context, key string, value int64) (int64, error)
	Expire(ctx context.Context, key string, expiration time.Duration) error
	TTL(ctx context.Context, key string) (time.Duration, error)
	FlushAll(ctx context.Context) error
	Health(ctx context.Context) error
}

Cache интерфейс для кэширования

type CacheDecorator

type CacheDecorator struct {
	// contains filtered or unexported fields
}

CacheDecorator декоратор для добавления кэширования к сервисам

func NewCacheDecorator

func NewCacheDecorator(cache Cache, prefix string, ttl time.Duration) *CacheDecorator

NewCacheDecorator создает новый декоратор кэширования

func (*CacheDecorator) GetOrSet

func (cd *CacheDecorator) GetOrSet(ctx context.Context, key string, dest interface{}, fn func() (interface{}, error)) error

GetOrSet получает значение из кэша или вызывает функцию для получения данных

type Config

type Config struct {
	Host         string `yaml:"host" env:"REDIS_HOST" env-default:"localhost"`
	Port         int    `yaml:"port" env:"REDIS_PORT" env-default:"6379"`
	Password     string `yaml:"password" env:"REDIS_PASSWORD" env-default:""`
	Database     int    `yaml:"database" env:"REDIS_DB" env-default:"0"`
	PoolSize     int    `yaml:"pool_size" env:"REDIS_POOL_SIZE" env-default:"10"`
	MinIdleConns int    `yaml:"min_idle_conns" env:"REDIS_MIN_IDLE_CONNS" env-default:"5"`
	MaxRetries   int    `yaml:"max_retries" env:"REDIS_MAX_RETRIES" env-default:"3"`
	DialTimeout  int    `yaml:"dial_timeout" env:"REDIS_DIAL_TIMEOUT" env-default:"5"`   // seconds
	ReadTimeout  int    `yaml:"read_timeout" env:"REDIS_READ_TIMEOUT" env-default:"3"`   // seconds
	WriteTimeout int    `yaml:"write_timeout" env:"REDIS_WRITE_TIMEOUT" env-default:"3"` // seconds
}

Config конфигурация Redis

type Pipeline

type Pipeline interface {
	Set(key string, value interface{}, expiration time.Duration) error
	Get(key string) (string, error)
	Delete(keys ...string) error
	Exec(ctx context.Context) error
}

Pipeline для батчевых операций

type RedisCache

type RedisCache struct {
	// contains filtered or unexported fields
}

RedisCache реализация Cache с использованием Redis

func NewRedisCache

func NewRedisCache(config Config, prefix string) (*RedisCache, error)

NewRedisCache создает новый экземпляр Redis cache

func (*RedisCache) Close

func (r *RedisCache) Close() error

Close закрывает соединение с Redis

func (*RedisCache) Delete

func (r *RedisCache) Delete(ctx context.Context, keys ...string) error

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

func (*RedisCache) Exists

func (r *RedisCache) Exists(ctx context.Context, key string) (bool, error)

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

func (*RedisCache) Expire

func (r *RedisCache) Expire(ctx context.Context, key string, expiration time.Duration) error

Expire устанавливает время жизни для ключа

func (*RedisCache) FlushAll

func (r *RedisCache) FlushAll(ctx context.Context) error

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

func (*RedisCache) Get

func (r *RedisCache) Get(ctx context.Context, key string, dest interface{}) error

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

func (*RedisCache) GetStats

func (r *RedisCache) GetStats(ctx context.Context) (map[string]interface{}, error)

GetStats возвращает статистику Redis

func (*RedisCache) Health

func (r *RedisCache) Health(ctx context.Context) error

Health проверяет состояние Redis

func (*RedisCache) Increment

func (r *RedisCache) Increment(ctx context.Context, key string) (int64, error)

Increment увеличивает числовое значение на 1

func (*RedisCache) IncrementBy

func (r *RedisCache) IncrementBy(ctx context.Context, key string, value int64) (int64, error)

IncrementBy увеличивает числовое значение на указанное число

func (*RedisCache) InvalidatePattern

func (r *RedisCache) InvalidatePattern(ctx context.Context, pattern string) error

InvalidatePattern удаляет ключи по паттерну (осторожно использовать в продакшене)

func (*RedisCache) NewPipeline

func (r *RedisCache) NewPipeline() Pipeline

NewPipeline создает новый pipeline

func (*RedisCache) Set

func (r *RedisCache) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error

Set сохраняет значение в кэш

func (*RedisCache) SetNX

func (r *RedisCache) SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) (bool, error)

SetNX устанавливает значение только если ключ не существует

func (*RedisCache) TTL

func (r *RedisCache) TTL(ctx context.Context, key string) (time.Duration, error)

TTL возвращает время жизни ключа

type RedisPipeline

type RedisPipeline struct {
	// contains filtered or unexported fields
}

RedisPipeline реализация Pipeline для Redis

func (*RedisPipeline) Delete

func (p *RedisPipeline) Delete(keys ...string) error

Delete добавляет команду DEL в pipeline

func (*RedisPipeline) Exec

func (p *RedisPipeline) Exec(ctx context.Context) error

Exec выполняет все команды в pipeline

func (*RedisPipeline) Get

func (p *RedisPipeline) Get(key string) (string, error)

Get добавляет команду GET в pipeline

func (*RedisPipeline) Set

func (p *RedisPipeline) Set(key string, value interface{}, expiration time.Duration) error

Set добавляет команду SET в pipeline

Jump to

Keyboard shortcuts

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