# README

Cache Library

Efficient and Type-safe Redis-based Caching for Go Applications

Go Report Card GoDoc License: MIT

  • Connection pooling for optimal performance
  • Automatic key prefixing to prevent collisions
  • Distributed tracing integration
  • Configurable cache TTLs
  • Bulk operations support
  • JSON serialization helpers
  • Comprehensive error handling

Installation

package main

import (
    "context"
    "log"
    
    "github.com/SolomonAIEngineering/backend-core-library/cacher"
    "github.com/gomodule/redigo/redis"
    "go.uber.org/zap"
)

func main() {
    // Initialize Redis pool with recommended settings
    pool := &redis.Pool{
        MaxIdle:     80,
        MaxActive:   12000,
        IdleTimeout: 240 * time.Second,
        Wait:        true,
        TestOnBorrow: func(c redis.Conn, t time.Time) error {
            _, err := c.Do("PING")
            return err
        },
        Dial: func() (redis.Conn, error) {
            return redis.Dial("tcp", "localhost:6379")
        },
    }

    // Create cache client with all required options
    client, err := cacher.New(
        cacher.WithRedisConn(pool),
        cacher.WithLogger(zap.L()),
        cacher.WithServiceName("my-service"),
        cacher.WithCacheTTLInSeconds(3600),
    )
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()
    
    // Basic write operation
    if err := client.WriteToCache(ctx, "user:123", []byte("data")); err != nil {
        log.Printf("Failed to write to cache: %v", err)
    }
}

Advanced Usage

Type-Safe Cache Keys

The library provides a type-safe way to manage cache keys:

// Define type-safe cache keys
key := cacher.NewCacheKey("user")
userKey := key.Enrich("123") // Results in "user:123"

Batch Operations with Pipeline

Efficiently handle multiple cache operations:

// Write multiple values atomically
data := map[string][]byte{
    "key1": []byte("value1"),
    "key2": []byte("value2"),
}
err := client.WriteManyToCache(ctx, data)

// Read multiple values
values, err := client.GetManyFromCache(ctx, []string{"key1", "key2"})

Custom TTL Support

Set custom TTL for specific cache entries:

err := client.WriteToCacheWithTTL(ctx, "temp-key", []byte("data"), 300) // 5 minutes TTL

Configuration Options

OptionDescriptionRequiredDefault
WithRedisConnRedis connection poolYes-
WithLoggerZap logger instanceYes-
WithServiceNameService name for key prefixingYes-
WithCacheTTLInSecondsDefault TTL for cache entriesYes-
WithIntrumentationClientInstrumentation clientNonil

Best Practices

Connection Pool Management

pool := &redis.Pool{
    MaxIdle:     80,
    MaxActive:   12000,
    IdleTimeout: 240 * time.Second,
    Wait:        true,
    TestOnBorrow: func(c redis.Conn, t time.Time) error {
        _, err := c.Do("PING")
        return err
    },
}
defer pool.Close()

Error Handling

// Always check for errors and implement retries for critical operations
value, err := client.GetFromCache(ctx, key)
if err != nil {
    if errors.Is(err, redis.ErrNil) {
        // Handle cache miss
    } else {
        // Handle other errors
    }
}

Key Management

// Use service name for automatic key prefixing
client, _ := cacher.New(
    cacher.WithServiceName("user-service"),
    // ... other options
)

Contributing

We welcome contributions! Please see our Contributing Guide for details.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support


Built with ❤️ by Solomon AI Engineering

# Functions

New creates a new Redis cache client with the provided options.
NewCacheKey creates a new CacheKey with the given key.
WithCacheTTLInSeconds sets the default time-to-live for cache entries in seconds.
WithIntrumentationClient enables distributed tracing for cache operations.
WithLogger configures the logging instance for the cache client.
WithRedisConn configures the Redis connection pool.
WithServiceName sets the service name used for key prefixing.

# Structs

Client implements a Redis cache client with connection pooling and instrumentation support.

# Type aliases

No description provided by the author
Option defines a function type that configures a Client.