anycache

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2023 License: MIT Imports: 6 Imported by: 0

README

AnyCache

tests codecov

anycache is a Go library that provides lazy caching with the possibility to use different cache storages. It allows you to cache the results of expensive operations and retrieve them quickly on subsequent requests.

Features

  • Lazy caching: cache values only when they are requested, not when they are generated.
  • Multiple cache storages: use Redis, Memcached, or any other cache storage that implements the CacheStorage interface.
  • Cache warming up: pre-populate the cache with values before they got expired.
  • Randomized TTL: add a random factor to the time-to-live (TTL) of cached values to avoid cache stampedes.
  • Serilization: cache JSON-encoded values and decode them automatically on retrieval.

Installation

To use anycache in your Go project, you can install it using go get:

go get github.com/ksysoev/anycache

Usage

Here's an example of how to use anycache to cache the result of a function that generates a random number:

package main

import (
    "fmt"
    "math/rand"
    "time"

    "github.com/redis/go-redis/v9"
    "github.com/ksysoev/anycache"
    "github.com/ksysoev/anycache/storage/redis"
)

func main() {
    redisClient := redis.NewClient(redis.Options{
        Addr: "localhost:6379",
    })

    redisStorage := redisstor.NewRedisCacheStorage(redisClient)

    // Creates anycache with 10% TTL randomization
    cache := anycache.NewCache(redisStorage, WithTTLRandomization(10))

    generator := func() (string, error) {
        randomNumber := rand.Intn(100)
        return fmt.Sprintf("%d", randomNumber), nil
    }

    value, err := cache.Cache(
        "random_number_key", 
        generator, 
        WithTTL(5 * time.Minute), 
        WithWarmUpTTL(1 * time.Minute)
    )

    if err != nil {
        fmt.Printf("Error caching value: %v\n", err)
        return
    }

    fmt.Printf("Cached value: %s\n", value)
}

In this example, we create a Redis cache storage instance using the redis package, and we create a new cache instance using NewCache with the Redis cache storage and some cache options.

We define a cache key, a time-to-live (TTL) duration, a warm-up TTL duration, and a generator function that generates a random number. We also define some cache item options that include the TTL and the warm-up TTL.

We use the Cache method of the cache instance to cache the result of the generator function with the given key and options. If the value is not already cached, the generator function is called to generate the value, and the value is stored in the cache storage with the given key and options. If the value is already cached, it is retrieved from the cache storage.

We print the cached value to the console.

Documentation

Overview

Package anycache provide laze caching with posibility to use diffent cache storages

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithTTLRandomization added in v0.0.3

func WithTTLRandomization(maxShiftPercent uint8) func(*Cache)

WithTTLRandomization sets max shift of TTL in persent

Types

type Cache

type Cache struct {
	Storage CacheStorage
	// contains filtered or unexported fields
}

Cache

func NewCache

func NewCache(storage CacheStorage, opts ...CacheOptions) Cache

NewCache creates a new Cache instance with the provided CacheStorage and CacheOptions. WithTTLRandomization sets max shift of TTL in persent It returns the created Cache instance.

func (*Cache) Cache

func (c *Cache) Cache(key string, generator CacheGenerator, opts ...CacheItemOptions) (string, error)

Cache caches the result of the generator function for the given key. If the key already exists in the cache, the cached value is returned. Otherwise, the generator function is called to generate a new value, which is then cached and returned. The function takes an optional list of CacheItemOptions to customize the caching behavior. WithTTL sets TTL for cache item WithWarmUpTTL sets TTL threshold for cache item to be warmed up

func (*Cache) CacheStruct added in v0.0.3

func (c *Cache) CacheStruct(key string, generator func(context.Context) (any, error), result any, opts ...CacheItemOptions) error

CacheStruct caches the result of a function that returns a struct. The key is used to identify the cached value. The generator function is called to generate the value if it is not already cached. The result parameter is a pointer to the struct that will be populated with the cached value. The opts parameter is optional and can be used to set additional cache item options. WithTTL sets TTL for cache item WithWarmUpTTL sets TTL threshold for cache item to be warmed up Returns an error if there was a problem caching or unmarshalling the value.

func (*Cache) GetWithTTL

func (c *Cache) GetWithTTL(ctx context.Context, key string) (string, time.Duration, error)

type CacheGenerator added in v0.0.4

type CacheGenerator func(ctx context.Context) (string, error)

type CacheItemOptions

type CacheItemOptions func(*CacheReuest)

func WithCtx added in v0.0.4

func WithCtx(ctx context.Context) CacheItemOptions

func WithTTL added in v0.0.3

func WithTTL(ttl time.Duration) CacheItemOptions

WithTTL sets TTL for cache item

func WithWarmUpTTL added in v0.0.3

func WithWarmUpTTL(ttl time.Duration) CacheItemOptions

WithWarmUpTTL sets TTL threshold for cache item to be warmed up

type CacheOptions

type CacheOptions func(*Cache)

type CacheQueue

type CacheQueue struct {
	WarmingUp bool
	// contains filtered or unexported fields
}

type CacheResponse

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

type CacheReuest

type CacheReuest struct {
	TTL       time.Duration
	WarmUpTTL time.Duration
	// contains filtered or unexported fields
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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