redis

package
v0.3.5 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package redis provides Redis client utilities optimized for SaaS applications.

This package wraps github.com/redis/go-redis/v9 to provide connection pooling, health checks, and graceful shutdown with sensible defaults for production workloads.

Features

  • Connection pooling with configurable limits and timeouts
  • Automatic retry logic with exponential backoff during startup
  • Health check function compatible with standard health check interfaces
  • Support for redis:// and rediss:// (TLS) URL schemes
  • Graceful shutdown hook integration with Forge applications

Configuration

All settings are configured via the Config struct:

  • URL — Redis connection URL (required)
  • PoolSize — Maximum number of connections (default: 10)
  • MinIdleConns — Minimum idle connections (default: 5)
  • MaxIdleTime — Maximum connection idle time (default: 10m)
  • MaxActiveTime — Maximum connection lifetime (default: 30m)
  • RetryAttempts — Retry attempts (default: 3)
  • RetryInterval — Retry base interval (default: 5s)
  • ReadTimeout — Read operation timeout (default: 3s)
  • WriteTimeout — Write operation timeout (default: 3s)
  • DialTimeout — Connection dial timeout (default: 5s)

Usage

Basic connection setup with Config:

import (
	"context"
	"log"
	"os"

	"github.com/dmitrymomot/forge/pkg/redis"
)

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

	client, err := redis.Open(ctx, redis.Config{
		URL:      os.Getenv("REDIS_URL"),
		PoolSize: 20,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()
}

Health Checks

The Healthcheck function returns a closure suitable for health check endpoints:

import (
	"net/http"

	goredis "github.com/redis/go-redis/v9"
	"github.com/dmitrymomot/forge/pkg/redis"
)

func healthHandler(client goredis.UniversalClient) http.HandlerFunc {
	healthFn := redis.Healthcheck(client)
	return func(w http.ResponseWriter, r *http.Request) {
		if err := healthFn(r.Context()); err != nil {
			w.WriteHeader(http.StatusServiceUnavailable)
			return
		}
		w.WriteHeader(http.StatusOK)
	}
}

Graceful Shutdown

Use Shutdown with Forge's shutdown hook for graceful client closure:

import (
	"github.com/dmitrymomot/forge"
	"github.com/dmitrymomot/forge/pkg/redis"
)

client := redis.MustOpen(ctx, redis.Config{URL: redisURL})
app := forge.New(forge.AppConfig{})

if err := forge.Run(
	forge.RunConfig{},
	forge.WithFallback(app),
	forge.WithShutdownHook(redis.Shutdown(client)),
); err != nil {
	log.Fatal(err)
}

Error Handling

The package defines sentinel errors for common failure modes:

Errors are wrapped using errors.Join to preserve the original error context.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEmptyConnectionURL = errors.New("redis: empty connection URL")
	ErrFailedToParseURL   = errors.New("redis: failed to parse connection URL")
	ErrConnectionFailed   = errors.New("redis: failed to establish connection")
	ErrHealthcheckFailed  = errors.New("redis: healthcheck failed")
)

Functions

func Healthcheck

func Healthcheck(client redis.UniversalClient) func(context.Context) error

Healthcheck returns a closure that validates Redis connectivity for health endpoints. Compatible with standard health check interfaces that expect func(context.Context) error.

func MustOpen

func MustOpen(ctx context.Context, cfg Config) redis.UniversalClient

MustOpen creates a Redis client or exits on failure. Use for simple applications where startup failure is fatal.

func Open

func Open(ctx context.Context, cfg Config) (redis.UniversalClient, error)

Open creates a Redis client with the given configuration. Supports both redis:// and rediss:// (TLS) URL schemes.

func Shutdown

func Shutdown(client io.Closer) func(ctx context.Context) error

Shutdown returns a function that gracefully closes the Redis client. Use with forge.WithShutdownHook().

Example:

app := forge.New(
    forge.WithShutdownHook(redis.Shutdown(client)),
)

Types

type Config

type Config struct {
	URL           string        `env:"URL,required"`
	PoolSize      int           `env:"POOL_SIZE"       envDefault:"10"`
	MinIdleConns  int           `env:"MIN_IDLE_CONNS"  envDefault:"5"`
	MaxIdleTime   time.Duration `env:"MAX_IDLE_TIME"   envDefault:"10m"`
	MaxActiveTime time.Duration `env:"MAX_ACTIVE_TIME" envDefault:"30m"`
	RetryAttempts int           `env:"RETRY_ATTEMPTS"  envDefault:"3"`
	RetryInterval time.Duration `env:"RETRY_INTERVAL"  envDefault:"5s"`
	ReadTimeout   time.Duration `env:"READ_TIMEOUT"    envDefault:"3s"`
	WriteTimeout  time.Duration `env:"WRITE_TIMEOUT"   envDefault:"3s"`
	DialTimeout   time.Duration `env:"DIAL_TIMEOUT"    envDefault:"5s"`
}

Config holds Redis connection configuration.

Jump to

Keyboard shortcuts

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