cache

package module
v0.17.1 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 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

go-cache

A generic, type-safe caching library for Go with support for local in-memory, Redis-backed, and synchronized two-layer caching — plus distributed leader election.

Features

  • Local cache — in-memory LRU cache with optional TTL and size limits
  • Redis cache — Redis-backed storage with optional PubSub invalidation and OpenTelemetry tracing
  • Synchronized cache — two-layer cache combining local and Redis, with automatic invalidation and optional preloading
  • Leader election — distributed leader election via Redis with fencing tokens and optional PubSub fast failover
  • Generic — fully typed via Go generics; works with any comparable key and any value type
  • Custom cache keys — built-in StringCacheKey and IntCacheKey, or implement your own

Installation

go get github.com/mxcd/go-cache

Cache Keys

Every cache requires a CacheKey that controls how keys are serialized to strings. Two implementations are included:

&cache.StringCacheKey{} // key type: string
&cache.IntCacheKey{}    // key type: int

You can implement the CacheKey[K] interface for custom key types:

type CacheKey[K comparable] interface {
    Marshal(K) string
    Unmarshal(string) (K, error)
    MarshallAll([]K) []string
    UnmarshalAll([]string) ([]K, error)
}

Local Cache

The local cache is a thread-safe, in-memory LRU backed by hashicorp/golang-lru.

Basic Usage
package main

import (
    "fmt"
    "time"

    cache "github.com/mxcd/go-cache"
)

type User struct {
    ID   int
    Name string
}

func main() {
    c := cache.NewLocalCache[string, User](&cache.LocalCacheOptions[string]{
        CacheKey: &cache.StringCacheKey{},
        TTL:      5 * time.Minute, // 0 = no expiration
        Size:     1000,            // 0 = unlimited
    })

    // Store a value
    c.Set("user:42", User{ID: 42, Name: "Alice"})

    // Retrieve a value
    user, ok := c.Get("user:42")
    if ok {
        fmt.Printf("Found: %s\n", user.Name)
    }

    // Check existence without fetching
    if c.Contains("user:42") {
        fmt.Println("key exists")
    }

    // Remove a single entry
    c.Remove("user:42")

    // Remove all entries whose serialized key starts with a prefix
    c.RemovePrefix("user:")

    // List all entries
    entries, _ := c.Load()
    for _, e := range entries {
        fmt.Printf("%s → %v\n", e.Key, e.Value)
    }
}
Options
Field Type Description
CacheKey CacheKey[K] Required. Serializes keys to strings.
TTL time.Duration Entry lifetime. 0 disables expiration.
Size int Maximum number of entries. 0 means unlimited.

Redis Cache

The Redis backend stores values serialized with MessagePack and supports optional PubSub-based cache-event broadcasting and OpenTelemetry tracing out of the box.

Basic Usage
package main

import (
    "context"
    "fmt"
    "time"

    cache "github.com/mxcd/go-cache"
    "github.com/redis/go-redis/v9"
)

type Product struct {
    ID    int
    Title string
    Price float64
}

func main() {
    ctx := context.Background()

    backend, err := cache.NewRedisStorageBackend[string, Product](&cache.RedisStorageBackendOptions[string]{
        RedisOptions: &redis.Options{
            Addr: "localhost:6379",
        },
        CacheKey:  &cache.StringCacheKey{},
        KeyPrefix: "products",   // all keys stored as  products:<key>
        TTL:       10 * time.Minute,
    })
    if err != nil {
        panic(err)
    }
    defer backend.Close()

    // Store a value
    err = backend.Set(ctx, "prod:1", Product{ID: 1, Title: "Widget", Price: 9.99})
    if err != nil {
        panic(err)
    }

    // Retrieve a value
    product, err := backend.Get(ctx, "prod:1")
    if err != nil {
        panic(err)
    }
    fmt.Printf("Found: %s ($%.2f)\n", product.Title, product.Price)

    // Check remaining TTL
    ttl, _ := backend.Ttl(ctx, "prod:1")
    fmt.Printf("Expires in: %s\n", ttl)

    // Check existence
    exists, _ := backend.Contains(ctx, "prod:1")
    fmt.Println("exists:", exists)

    // Remove a single key
    backend.Remove(ctx, "prod:1")

    // Remove all keys matching a prefix (uses Redis SCAN, safe for large keyspaces)
    backend.RemovePrefix(ctx, "prod:")

    // Load all entries
    entries, _ := backend.Load(ctx)
    for _, e := range entries {
        fmt.Printf("%v → %v\n", e.Key, e.Value)
    }
}
PubSub (cross-instance cache invalidation)

Enable PubSub to have each backend instance receive events published by other instances. This is the foundation for the synchronized cache's automatic invalidation.

backend, err := cache.NewRedisStorageBackend[string, Product](&cache.RedisStorageBackendOptions[string]{
    RedisOptions: &redis.Options{
        Addr: "localhost:6379",
    },
    CacheKey:          &cache.StringCacheKey{},
    KeyPrefix:         "products",
    TTL:               10 * time.Minute,
    PubSub:            true,
    PubSubChannelName: "products-cache-events",
})

// Register a callback that fires whenever any instance publishes a Set/Remove/RemovePrefix event
backend.AddCallback(func(event cache.CacheEvent[string, Product]) {
    switch event.Type {
    case cache.CacheEventSet:
        fmt.Printf("key set: %s\n", event.Entry.Key)
    case cache.CacheEventRemove:
        fmt.Printf("key removed: %s\n", event.Entry.Key)
    case cache.CacheEventRemovePrefix:
        fmt.Printf("prefix removed: %s\n", event.KeyPrefix)
    }
})

The PubSub goroutine reconnects automatically with exponential backoff (100 ms → 10 s) on connection errors. Call backend.Close() to shut it down cleanly.

Options
Field Type Description
RedisOptions *redis.Options Required. Standard go-redis connection options.
CacheKey CacheKey[K] Required. Serializes keys to strings.
KeyPrefix string Namespace prefix for all Redis keys (<prefix>:<key>).
TTL time.Duration Entry lifetime in Redis. 0 means no expiration.
PubSub bool Enable event publishing/subscribing.
PubSubChannelName string Redis channel name. Required when PubSub is true.
ScanCount int64 Hint passed to Redis SCAN per iteration. 0 uses the Redis default.

Synchronized Cache

The synchronized cache combines a local in-memory cache (L1) with a Redis backend (L2). Reads hit L1 first; on a miss the value is fetched from L2 and populated into L1. Writes go to L2 (or L1 first when async), and PubSub events keep all instances' L1 caches in sync.

Basic Usage
package main

import (
    "context"
    "fmt"
    "time"

    cache "github.com/mxcd/go-cache"
    "github.com/redis/go-redis/v9"
)

type Session struct {
    UserID string
    Token  string
}

func main() {
    ctx := context.Background()

    // Build the Redis backend with PubSub enabled
    backend, err := cache.NewRedisStorageBackend[string, Session](&cache.RedisStorageBackendOptions[string]{
        RedisOptions: &redis.Options{
            Addr: "localhost:6379",
        },
        CacheKey:          &cache.StringCacheKey{},
        KeyPrefix:         "sessions",
        TTL:               30 * time.Minute,
        PubSub:            true,
        PubSubChannelName: "session-cache-events",
    })
    if err != nil {
        panic(err)
    }
    defer backend.Close()

    // Wrap it in a synchronized cache
    synced, err := cache.NewSynchronizedCache[string, Session](&cache.SynchronizedCacheOptions[string, Session]{
        CacheKey:       &cache.StringCacheKey{},
        StorageBackend: backend,
        LocalTTL:       5 * time.Minute, // local entries expire sooner than remote
        LocalSize:      500,
        Preload:        true,            // populate local cache from Redis on startup
    })
    if err != nil {
        panic(err)
    }

    // Set — writes to Redis first, then local
    err = synced.Set(ctx, "sess:abc", Session{UserID: "42", Token: "secret"})
    if err != nil {
        panic(err)
    }

    // Get — local hit, no Redis round-trip
    session, ok := synced.Get(ctx, "sess:abc")
    if ok {
        fmt.Printf("Session for user %s\n", session.UserID)
    }

    // Check remaining TTL (always queries Redis)
    ttl, _ := synced.Ttl(ctx, "sess:abc")
    fmt.Printf("Remote TTL: %s\n", ttl)

    // Contains — checks local first, then Redis
    exists, _ := synced.Contains(ctx, "sess:abc")
    fmt.Println("exists:", exists)

    // Remove — deletes from Redis, then local
    synced.Remove(ctx, "sess:abc")

    // RemovePrefix — deletes all matching keys from Redis and local
    synced.RemovePrefix(ctx, "sess:")
}
Async writes

Set RemoteAsync: true to make writes non-blocking. The value is placed into L1 immediately; the Redis write happens in the background. If the background write fails, the L1 entry is rolled back (for Set).

synced, err := cache.NewSynchronizedCache[string, Session](&cache.SynchronizedCacheOptions[string, Session]{
    CacheKey:       &cache.StringCacheKey{},
    StorageBackend: backend,
    LocalTTL:       5 * time.Minute,
    LocalSize:      500,
    RemoteAsync:    true,
    AsyncTimeout:   3 * time.Second, // optional: cap how long the background goroutine may run
})
OpenTelemetry tracing

Pass a *trace.Tracer to automatically create spans for every cache operation:

import "go.opentelemetry.io/otel"

tracer := otel.Tracer("my-service")

synced, err := cache.NewSynchronizedCache[string, Session](&cache.SynchronizedCacheOptions[string, Session]{
    CacheKey:       &cache.StringCacheKey{},
    StorageBackend: backend,
    LocalTTL:       5 * time.Minute,
    LocalSize:      500,
    Tracer:         &tracer,
})

The Redis backend also instruments the underlying Redis client with OpenTelemetry tracing and metrics automatically via redisotel.

Options
Field Type Description
CacheKey CacheKey[K] Required. Serializes keys to strings.
StorageBackend StorageBackend[K,V] Required. The remote backend (e.g. *RedisStorageBackend).
LocalTTL time.Duration TTL for local (L1) entries. Can be shorter than the remote TTL.
LocalSize int Maximum number of entries in the local cache. 0 means unlimited.
RemoteAsync bool Write to local first, then Redis in the background. Rolls back on failure.
AsyncTimeout time.Duration Maximum time for an async background write. 0 means no timeout.
Preload bool Load all remote entries into local cache on startup.
Tracer *trace.Tracer Optional OpenTelemetry tracer for span instrumentation.

Leader Election

Distributed leader election using Redis. Uses atomic Lua scripts for lock acquisition, renewal, and release. Provides monotonically increasing fencing tokens to guard against stale leaders. Optionally uses PubSub for fast failover when a leader resigns.

The leader election accepts a *redis.Client (not *redis.Options) so you can share the same client you already use for caching.

Basic Usage
package main

import (
    "context"
    "fmt"
    "log"
    "os"
    "os/signal"
    "time"

    cache "github.com/mxcd/go-cache"
    "github.com/redis/go-redis/v9"
)

func main() {
    client := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
    })
    defer client.Close()

    le, err := cache.NewLeaderElection(cache.LeaderElectionOptions{
        Client:        client,
        LockKey:       "myapp:leader",
        LeaseDuration: 10 * time.Second,
        OnElected: func(ctx context.Context) {
            fmt.Println("I am the leader now")
            // ctx is cancelled when leadership is lost — use it to gate leader work
            <-ctx.Done()
            fmt.Println("Leadership lost, stopping leader work")
        },
        OnDemoted: func() {
            fmt.Println("No longer the leader")
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    defer stop()

    if err := le.Start(ctx); err != nil {
        log.Fatal(err)
    }

    <-ctx.Done()
    le.Stop()
}
Fencing Tokens

Every election produces a monotonically increasing epoch. Use it to guard operations that must only be performed by the current leader:

token := le.FencingToken() // 0 if not leader
if token > 0 {
    // pass token to downstream systems so they can reject stale writes
    processWork(token, payload)
}
PubSub Fast Failover

Without PubSub, followers discover a vacant lock on their next retry tick (RetryInterval, default LeaseDuration/2). With PubSub, the resigning leader announces its departure and followers attempt acquisition immediately (plus a small jitter to avoid thundering herd).

le, err := cache.NewLeaderElection(cache.LeaderElectionOptions{
    Client:        client,
    LockKey:       "myapp:leader",
    LeaseDuration: 10 * time.Second,
    PubSubChannel: "myapp:leader:events", // enables fast failover
    OnElected: func(ctx context.Context) {
        // ...
    },
})
Options
Field Type Description
Client *redis.Client Required. A shared go-redis client.
LockKey string Required. Redis key for the leader lock.
LeaseDuration time.Duration Required. How long the lock is held before expiry. Recommended 10–15 s.
InstanceID string Unique ID for this participant. Generated automatically if empty.
RenewInterval time.Duration How often the leader renews its lease. Default: LeaseDuration / 3.
RetryInterval time.Duration How often followers attempt acquisition. Default: LeaseDuration / 2.
OnElected func(context.Context) Called (in a new goroutine) when elected. The context is cancelled when leadership is lost.
OnDemoted func() Called synchronously when leadership is lost.
PubSubChannel string Redis PubSub channel for fast failover. Empty disables PubSub.
How It Works
  1. Acquire — atomic Lua script: SET lock NX PX, INCR epoch, overwrite lock with instanceID:epoch.
  2. Renew — atomic Lua script: verify lock value matches, then PEXPIRE.
  3. Release — atomic Lua script: verify lock value matches, then DEL.
  4. Failover — if the leader crashes, the lock expires after LeaseDuration and the next follower retry acquires it. With PubSub, graceful resignations trigger near-instant failover.
  5. Split-brain protection — after 3 consecutive renewal failures, the leader demotes itself proactively rather than waiting for the lease to expire.

Implementing a Custom Storage Backend

Implement the StorageBackend[K, V] interface to plug in any storage layer:

type StorageBackend[K comparable, V any] interface {
    Get(context.Context, K) (*V, error)
    Ttl(context.Context, K) (time.Duration, error)
    Set(context.Context, K, V) error
    Remove(context.Context, K) error
    RemovePrefix(context.Context, string) error
    Contains(context.Context, K) (bool, error)
    Load(context.Context) ([]CacheEntry[K, V], error)
    AddCallback(func(CacheEvent[K, V]))
}

Pass your implementation as StorageBackend in SynchronizedCacheOptions to use it as the remote layer.


License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CacheEntry

type CacheEntry[K comparable, V any] struct {
	Key   K
	Value *V
}

type CacheEvent

type CacheEvent[K comparable, V any] struct {
	Entry     *CacheEntry[K, V]
	Type      CacheEventType
	KeyPrefix string
}

type CacheEventType

type CacheEventType int
const (
	CacheEventSet CacheEventType = iota
	CacheEventRemove
	CacheEventRemovePrefix
)

type CacheKey

type CacheKey[K comparable] interface {
	Marshal(K) string
	Unmarshal(string) (K, error)
	MarshallAll([]K) []string
	UnmarshalAll([]string) ([]K, error)
}

type IntCacheKey

type IntCacheKey struct {
}

func (*IntCacheKey) Marshal

func (k *IntCacheKey) Marshal(key int) string

func (*IntCacheKey) MarshallAll

func (k *IntCacheKey) MarshallAll(keys []int) []string

func (*IntCacheKey) Unmarshal

func (k *IntCacheKey) Unmarshal(data string) (int, error)

func (*IntCacheKey) UnmarshalAll

func (k *IntCacheKey) UnmarshalAll(data []string) ([]int, error)

type LeaderElection added in v0.16.0

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

LeaderElection manages distributed leader election via Redis.

func NewLeaderElection added in v0.16.0

func NewLeaderElection(opts LeaderElectionOptions) (*LeaderElection, error)

NewLeaderElection creates a new leader election instance. Call Start to begin participating in the election.

func (*LeaderElection) FencingToken added in v0.16.0

func (le *LeaderElection) FencingToken() int64

FencingToken returns the current monotonically increasing epoch. Returns 0 if this instance is not the leader. Use this to guard operations that should only be performed by the current leader.

func (*LeaderElection) IsLeader added in v0.16.0

func (le *LeaderElection) IsLeader() bool

IsLeader returns whether this instance currently holds the leader lock.

func (*LeaderElection) Start added in v0.16.0

func (le *LeaderElection) Start(ctx context.Context) error

Start begins the election loop. It is non-blocking and returns immediately. The election loop runs until the provided context is cancelled or Stop is called.

func (*LeaderElection) Stop added in v0.16.0

func (le *LeaderElection) Stop() error

Stop gracefully resigns leadership (if held) and stops the election loop. It blocks until shutdown is complete. The Redis client is not closed — the caller owns it. Calling Stop multiple times is safe.

type LeaderElectionOptions added in v0.16.0

type LeaderElectionOptions struct {
	// Client is a pre-existing go-redis client. Required.
	Client *redis.Client

	// LockKey is the Redis key used for the leader lock. Required.
	LockKey string

	// InstanceID uniquely identifies this participant.
	// If empty, a random ID is generated.
	InstanceID string

	// LeaseDuration is how long the lock is held before expiry.
	// Must be positive. Recommended: 10-15s.
	LeaseDuration time.Duration

	// RenewInterval is how often the leader renews its lease.
	// If zero, defaults to LeaseDuration/3.
	RenewInterval time.Duration

	// RetryInterval is how often non-leaders attempt acquisition.
	// If zero, defaults to LeaseDuration/2.
	RetryInterval time.Duration

	// OnElected is called when this instance becomes leader.
	// The provided context is cancelled when leadership is lost.
	// Called in a new goroutine — safe to block.
	OnElected func(ctx context.Context)

	// OnDemoted is called when this instance loses leadership.
	OnDemoted func()

	// PubSubChannel enables fast failover via Redis PubSub.
	// If empty, PubSub is disabled and failover relies on lease expiry + polling.
	PubSubChannel string
}

LeaderElectionOptions configures a leader election instance.

type LocalCache

type LocalCache[K comparable, V any] struct {
	Options  *LocalCacheOptions[K]
	Cache    *lru.LRU[string, *CacheEntry[K, V]]
	CacheKey CacheKey[K]
}

func NewLocalCache

func NewLocalCache[K comparable, V any](options *LocalCacheOptions[K]) *LocalCache[K, V]

func (*LocalCache[K, V]) Contains

func (c *LocalCache[K, V]) Contains(key K) bool

func (*LocalCache[K, V]) Get

func (c *LocalCache[K, V]) Get(key K) (*V, bool)

func (*LocalCache[K, V]) Load

func (c *LocalCache[K, V]) Load() ([]CacheEntry[K, V], error)

func (*LocalCache[K, V]) Remove

func (c *LocalCache[K, V]) Remove(key K) bool

func (*LocalCache[K, V]) RemovePrefix

func (c *LocalCache[K, V]) RemovePrefix(prefix string)

func (*LocalCache[K, V]) Set

func (c *LocalCache[K, V]) Set(key K, value V)

type LocalCacheOptions

type LocalCacheOptions[K comparable] struct {
	TTL      time.Duration
	Size     int
	CacheKey CacheKey[K]
}

Options passed to NewLocalCache

Ttl: Time to live for each entry in the cache. Set to 0 to disable expiration Size: Maximum number of entries in the cache. Set to 0 for unlimited size

func (*LocalCacheOptions[K]) GetCacheKey

func (o *LocalCacheOptions[K]) GetCacheKey() CacheKey[K]

func (*LocalCacheOptions[K]) GetSize

func (o *LocalCacheOptions[K]) GetSize() int

func (*LocalCacheOptions[K]) GetTtl

func (o *LocalCacheOptions[K]) GetTtl() time.Duration

type RedisStorageBackend

type RedisStorageBackend[K comparable, V any] struct {
	Options *RedisStorageBackendOptions[K]
	Client  *redis.Client
	// contains filtered or unexported fields
}

func NewRedisStorageBackend

func NewRedisStorageBackend[K comparable, V any](options *RedisStorageBackendOptions[K]) (*RedisStorageBackend[K, V], error)

func (*RedisStorageBackend[K, V]) AddCallback

func (b *RedisStorageBackend[K, V]) AddCallback(callback func(CacheEvent[K, V]))

func (*RedisStorageBackend[K, V]) Close

func (b *RedisStorageBackend[K, V]) Close() error

func (*RedisStorageBackend[K, V]) Contains

func (b *RedisStorageBackend[K, V]) Contains(ctx context.Context, key K) (bool, error)

func (*RedisStorageBackend[K, V]) Get

func (b *RedisStorageBackend[K, V]) Get(ctx context.Context, key K) (*V, error)

func (*RedisStorageBackend[K, V]) GetStringKey

func (b *RedisStorageBackend[K, V]) GetStringKey(key K) string

func (*RedisStorageBackend[K, V]) Load

func (b *RedisStorageBackend[K, V]) Load(ctx context.Context) ([]CacheEntry[K, V], error)

func (*RedisStorageBackend[K, V]) PublishEvent

func (b *RedisStorageBackend[K, V]) PublishEvent(ctx context.Context, event *CacheEvent[K, V]) error

func (*RedisStorageBackend[K, V]) Remove

func (b *RedisStorageBackend[K, V]) Remove(ctx context.Context, key K) error

func (*RedisStorageBackend[K, V]) RemovePrefix

func (b *RedisStorageBackend[K, V]) RemovePrefix(ctx context.Context, keyPrefix string) error

func (*RedisStorageBackend[K, V]) Set

func (b *RedisStorageBackend[K, V]) Set(ctx context.Context, key K, value V) error

func (*RedisStorageBackend[K, V]) Ttl

func (b *RedisStorageBackend[K, V]) Ttl(ctx context.Context, key K) (time.Duration, error)

type RedisStorageBackendOptions

type RedisStorageBackendOptions[K comparable] struct {
	RedisOptions      *redis.Options
	TTL               time.Duration
	CacheKey          CacheKey[K]
	KeyPrefix         string
	PubSub            bool
	PubSubChannelName string
	ScanCount         int64
}

func (*RedisStorageBackendOptions[K]) GetScanCount

func (o *RedisStorageBackendOptions[K]) GetScanCount() int64

type StorageBackend

type StorageBackend[K comparable, V any] interface {
	Get(context.Context, K) (*V, error)
	Ttl(context.Context, K) (time.Duration, error)
	Set(context.Context, K, V) error
	Remove(context.Context, K) error
	RemovePrefix(context.Context, string) error
	Contains(context.Context, K) (bool, error)
	Load(context.Context) ([]CacheEntry[K, V], error)
	AddCallback(func(CacheEvent[K, V]))
}

type StringCacheKey

type StringCacheKey struct {
}

func (*StringCacheKey) Marshal

func (k *StringCacheKey) Marshal(key string) string

func (*StringCacheKey) MarshallAll

func (k *StringCacheKey) MarshallAll(keys []string) []string

func (*StringCacheKey) Unmarshal

func (k *StringCacheKey) Unmarshal(data string) (string, error)

func (*StringCacheKey) UnmarshalAll

func (k *StringCacheKey) UnmarshalAll(data []string) ([]string, error)

type Stringer

type Stringer interface {
	String() string
}

type SynchronizedCache

type SynchronizedCache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func NewSynchronizedCache

func NewSynchronizedCache[K comparable, V any](options *SynchronizedCacheOptions[K, V]) (*SynchronizedCache[K, V], error)

func (*SynchronizedCache[K, V]) Contains

func (c *SynchronizedCache[K, V]) Contains(ctx context.Context, key K) (bool, error)

func (*SynchronizedCache[K, V]) Get

func (c *SynchronizedCache[K, V]) Get(ctx context.Context, key K) (*V, bool)

func (*SynchronizedCache[K, V]) Remove

func (c *SynchronizedCache[K, V]) Remove(ctx context.Context, key K) error

func (*SynchronizedCache[K, V]) RemovePrefix

func (c *SynchronizedCache[K, V]) RemovePrefix(ctx context.Context, prefix string) error

func (*SynchronizedCache[K, V]) Set

func (c *SynchronizedCache[K, V]) Set(ctx context.Context, key K, value V) error

func (*SynchronizedCache[K, V]) Ttl

func (c *SynchronizedCache[K, V]) Ttl(ctx context.Context, key K) (time.Duration, error)

type SynchronizedCacheOptions

type SynchronizedCacheOptions[K comparable, V any] struct {
	LocalTTL       time.Duration
	LocalSize      int
	CacheKey       CacheKey[K]
	StorageBackend StorageBackend[K, V]
	RemoteAsync    bool
	Preload        bool
	Tracer         *trace.Tracer
	AsyncTimeout   time.Duration
}

Directories

Path Synopsis
Package lru provides a thread-safe, fixed-size LRU cache with optional per-entry TTL expiration.
Package lru provides a thread-safe, fixed-size LRU cache with optional per-entry TTL expiration.

Jump to

Keyboard shortcuts

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