cache

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2024 License: MIT Imports: 7 Imported by: 14

README

Cache

Пакет cache предоставляет абстракцию для работы с кэшем, которая позволяет легко заменять и мокать реализации кэша в приложении.

Установка

go get "gitlab.com/golight/cache"

Пример использования

package main

import (
	"context"
	"gitlab.com/golight/cache"
	"log"
	"time"
)

func main() {
	conf:= cache.Config{
		Address:  "cache",
		Password: "cache",
		Port:     "cache",
	}
	// Создание кэша с помощью пакета cache
	c, err := cache.NewCache(conf, nil)
	if err != nil {
		log.Fatalf("Не удалось создать кэш: %v", err)
	}

	// Установка значения в кэш
	err = c.Set(context.Background(), "my_key", "some value", time.Minute)
	if err != nil {
		log.Printf("Не удалось установить значение: %v", err)
	}

	// Извлечение значения из кэша
	var val string
	err = c.Get(context.Background(), "my_key", &val)
	if err != nil {
		log.Printf("Не удалось получить значение: %v", err)
	}

	// Удаление значения из кэша
	err = c.Delete(context.Background(), false, "my_key")
	if err != nil {
		log.Printf("Не удалось удалить значение: %v", err)
	}
}



Documentation

Overview

Package cache provides service with pluggable cache abstraction

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrCacheMiss is a replacement for implementation defined cache miss error of different providers,
	// such as replacement for redis.Nil which looks meaningless
	ErrCacheMiss = errors.New("cache: key not found")
)

Functions

This section is empty.

Types

type Cacher

type Cacher interface {
	// Get Retrieves the content associated with the given key. decoding it into the given
	// pointer.
	//
	// Returns:
	//   - nil if the value was successfully retrieved and ptrValue set
	//   - ErrCacheMiss if the value was not in the cache
	//   - an implementation specific error otherwise
	Get(ctx context.Context, key string, ptrValue interface{}) error

	// Set the given key/value in the cache, overwriting any existing value
	// associated with that key
	// if broadcasting mode is specified sends related errors to returned channel during cache initialization
	Set(ctx context.Context, key string, value interface{}, expires time.Duration) error

	// Delete deletes the specified keys from the cache
	// if pattern is true, then keys is treated as a pattern and all keys matching the pattern will be deleted
	Delete(ctx context.Context, pattern bool, keys ...string) error

	// KeyExists verifies whether specified key exists in cache; returns true in case key exists and nil error
	KeyExists(ctx context.Context, key string) (bool, error)

	// Expire use this when you want time to live of a key will be updated to the new value
	Expire(ctx context.Context, key string, expiration time.Duration) error
}

Cacher is an interface which abstracts cache providers details for mockability and usability

func NewCache

func NewCache(cacheConfig Config, decoder godecoder.Decoder) (Cacher, error)

NewCache принимает конфигурацию и в зависимости от раздела кэша в конфигурации оборачивает фактическую реализацию кэша

type Config

type Config struct {
	Address  string `env:"CACHE_ADDRESS"`
	Password string `env:"CACHE_PASSWORD"`
	Port     string `env:"CACHE_PORT"`
}

type Error

type Error interface {
	error
	GetCommand() string
}

Error is an interface which helps to communicate cache errors for logging and metrics

type RedisCache

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

RedisCache wraps *redis.Client to meet swappable and mockable Cache interface

func (*RedisCache) Delete

func (c *RedisCache) Delete(ctx context.Context, pattern bool, keys ...string) error

func (*RedisCache) Expire

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

Expire updates TTL for specified key

func (*RedisCache) Get

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

Get retrieves value from Redis and serializes to pointer value

func (*RedisCache) KeyExists

func (c *RedisCache) KeyExists(ctx context.Context, key string) (bool, error)

KeyExists checks whether specified key exists; returns true and nil if key is actually exists

func (*RedisCache) Set

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

Set takes key and value as input and setting Redis cache with this value shares errors to channel in case broadcasting mode is enabled it prevents manual error handling which seems noisy and unnecessary in rdb code

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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