echocache

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2025 License: MIT Imports: 7 Imported by: 0

README

EchoCache

EchoCache is a caching library for Go that provides various cache implementations, including LRU, Redis, and NATS JetStream. It is designed to improve application performance by reducing the load on databases and external services.

Features

  • LRUCache: Implements a Least Recently Used (LRU) cache using hashicorp/golang-lru.
  • LRUExpirableCache: A variant of LRU with support for item expiration.
  • SingleEntryCache: A cache that holds a single value with TTL.
  • RedisCache: Redis-based implementation with persistence and distributed management support.
  • NatsCache: NATS JetStream-based implementation for distributed storage and asynchronous caching.
  • Stale-While-Revalidate: Support for asynchronously reloading stale data to avoid bottlenecks.
  • Automatic concurrency handling: Uses singleflight to prevent duplicate requests for the same key.

Installation

Ensure you have Go installed, then run:

go get github.com/logocomune/echocache

Usage

Example using EchoCache with Memoization
package main

import (
	"context"
	"fmt"
	"github.com/logocomune/echocache"
	"github.com/logocomune/echocache/store"
	"sync"
	"time"
)

// simulateComputation simulates a computation that is memoized and returns the result.
func simulateComputation(ctx context.Context, ec *echocache.EchoCache[string], key string) (string, bool, error) {
	// Define the computation logic inside the RefreshFunc
	return ec.FetchWithCache(ctx, key, func(ctx context.Context) (string, error) {
		time.Sleep(1 * time.Second) // Simulate expensive computation
		return "test1", nil
	})
}

// main demonstrates usage of EchoCache with concurrent memoization.
func main() {
	// Create a new cache instance with an LRU cache of size 2
	cache := echocache.NewEchoCache[string](store.NewLRUCache[string](2))

	// Single-threaded memoize usage
	start := time.Now()
	result, cached, err := simulateComputation(context.TODO(), cache, "test")
	fmt.Println(result, cached, err, time.Since(start))

	// Use a WaitGroup to synchronize goroutines
	wg := sync.WaitGroup{}
	wg.Add(2)

	// Launch two goroutines to simulate concurrent access
	for i := 0; i < 2; i++ {
		go func(id int) {
			defer wg.Done()

			// Each goroutine performs the same memoized computation
			start := time.Now()
			result, cached, err := simulateComputation(context.TODO(), cache, "test")
			fmt.Printf("Goroutine %d: %s, Cached: %v, Error: %v, Time Elapsed: %v\n", id, result, cached, err, time.Since(start))
		}(i)
	}

	// Wait for all goroutines to complete
	wg.Wait()
	fmt.Println("All goroutines completed")
}


License

Distributed under the MIT license.

Documentation

Index

Constants

View Source
const (
	NeverExpire = time.Hour * 24 * 365 * 100
)

NeverExpire represents a duration of 100 years, effectively used to denote a value that should never expire.

Variables

This section is empty.

Functions

This section is empty.

Types

type EchoCache

type EchoCache[T any] struct {
	// contains filtered or unexported fields
}

EchoCache is a generic caching mechanism that integrates singleflight to prevent redundant computations. EchoCache uses a Cacher interface for data storage and retrieval, supporting custom refresh functions for cache misses. EchoCache ensures only one computation per key occurs simultaneously to optimize concurrent operations.

func NewEchoCache added in v1.2.0

func NewEchoCache[T any](cacher store.Cacher[T]) *EchoCache[T]

NewEchoCache creates a new EchoCache instance to enable caching with optional singleflight for concurrent requests.

func (*EchoCache[T]) FetchWithCache added in v1.2.0

func (ec *EchoCache[T]) FetchWithCache(ctx context.Context, key string, refreshFn store.RefreshFunc[T]) (T, bool, error)

FetchWithCache retrieves a cached value by key or computes it using a given refresh function, caching the result for future use. Returns the value, a boolean indicating if it was found or computed, and an error if computation or retrieval fails.

type EchoCacheLazy added in v1.2.0

type EchoCacheLazy[T any] struct {
	// contains filtered or unexported fields
}

EchoCacheLazy is a lazy-refresh cache designed to handle stale-while-revalidate caching with generic type support. It queues refresh tasks to be processed later instead of blocking calls for cache updates. It leverages singleflight to prevent duplicate execution of refresh tasks for the same key. Refresh operations are managed with timeout and cancellation support for efficient processing. This type is suitable for scenarios where background cache updates improve application performance.

func NewLazyEchoCache added in v1.2.0

func NewLazyEchoCache[T any](cacher store.StaleWhileRevalidateCache[T], refreshTimeout time.Duration) *EchoCacheLazy[T]

NewLazyEchoCache initializes a lazy echo cache with a specified stale-while-revalidate cacher and refresh timeout. It starts a background goroutine to handle refresh tasks and returns a pointer to the configured EchoCacheLazy instance.

func (*EchoCacheLazy[T]) FetchWithLazyRefresh added in v1.2.0

func (ec *EchoCacheLazy[T]) FetchWithLazyRefresh(ctx context.Context, key string, refreshFn store.RefreshFunc[T], lazyRefreshInterval time.Duration) (T, bool, error)

FetchWithLazyRefresh retrieves a cached value or computes a new value if missing, scheduling a lazy refresh if needed. It uses a key to fetch a value from the cache and utilizes a provided function to refresh the value when necessary. If the cached value exists but is older than the lazy refresh interval, a refresh task is sent to the queue. If the value is missing or an error occurs during retrieval, a new value is computed immediately. Returns the cached or computed value, a boolean indicating cache hit, and an error if any.

func (*EchoCacheLazy[T]) ShutdownLazyRefresh added in v1.2.0

func (ec *EchoCacheLazy[T]) ShutdownLazyRefresh()

ShutdownLazyRefresh gracefully shuts down the refresh process by canceling the context and closing the task queue.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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