Help us shape the future of Go! Take the 2026 Go Developer Survey

redis

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package redis provides a Redis integration bundle for Forge applications.

The Redis bundle provides:

  • Redis client connection management with connection pooling
  • Health checks for Redis connectivity and performance
  • Caching interface with TTL support
  • Pub/Sub messaging capabilities
  • Distributed locking utilities
  • Rate limiting support
  • Session storage management

Basic Usage

Add the Redis bundle to your application:

config := redis.Config{
	RedisURL: "redis://localhost:6379/0",
	PoolSize: 10,
	MinIdleConns: 2,
	DialTimeout: 5 * time.Second,
}

bundle := redis.NewBundle(config)

app, err := framework.New(
	framework.WithConfig(&baseConfig),
	framework.WithBundle(bundle),
)

Accessing Redis

The bundle provides a Redis client that can be used for dependency injection:

type CacheService struct {
	redis redis.UniversalClient
}

func NewCacheService(redisClient redis.UniversalClient) *CacheService {
	return &CacheService{redis: redisClient}
}

Caching Operations

The bundle provides a high-level caching interface:

cache := bundle.Cache()

// Set with TTL
err := cache.Set(ctx, "user:123", userData, 1*time.Hour)

// Get with type safety
var user User
err := cache.Get(ctx, "user:123", &user)

Pub/Sub Messaging

pubsub := bundle.PubSub()

// Subscribe to messages
messages := pubsub.Subscribe(ctx, "user.events")

// Publish messages
err := pubsub.Publish(ctx, "user.events", userData)

Health Checks

The bundle automatically provides Redis health checks that verify:

  • Redis connectivity (ping)
  • Memory usage and performance
  • Connection pool health

Index

Constants

This section is empty.

Variables

View Source
var ErrCacheMiss = errors.New("cache miss")

ErrCacheMiss indicates the requested key does not exist in the cache.

Functions

This section is empty.

Types

type Bundle

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

Bundle provides Redis integration for Forge applications.

func NewBundle

func NewBundle(config Config) *Bundle

NewBundle creates a new Redis bundle with the given configuration.

func (*Bundle) Cache

func (b *Bundle) Cache() *CacheService

Cache returns the caching service interface.

func (*Bundle) Client

func (b *Bundle) Client() redis.UniversalClient

Client returns the Redis client. This can be used for dependency injection.

func (*Bundle) Close

func (b *Bundle) Close() error

Close is deprecated. Use Stop() instead for proper lifecycle integration. Maintained for backward compatibility.

func (*Bundle) HealthChecks

func (b *Bundle) HealthChecks() []forgeHealth.Check

HealthChecks returns health checks for the Redis connection.

func (*Bundle) Initialize

func (b *Bundle) Initialize(app *framework.App) error

Initialize sets up the Redis connection and services.

func (*Bundle) Name

func (b *Bundle) Name() string

Name returns the bundle name.

func (*Bundle) NewDistributedLock

func (b *Bundle) NewDistributedLock(key string, ttl time.Duration) *DistributedLock

NewDistributedLock creates a new distributed lock.

func (*Bundle) NewRateLimiter

func (b *Bundle) NewRateLimiter(prefix string) *RateLimiter

NewRateLimiter creates a new Redis-based rate limiter.

func (*Bundle) PubSub

func (b *Bundle) PubSub() *PubSubService

PubSub returns the pub/sub messaging service.

func (*Bundle) Stop

func (b *Bundle) Stop(ctx context.Context) error

Stop implements the Bundle interface for graceful shutdown. Closes the Redis connection respecting the context deadline.

type CacheService

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

CacheService provides high-level caching operations.

func NewCacheService

func NewCacheService(client redis.UniversalClient) *CacheService

NewCacheService creates a new cache service.

func (*CacheService) Delete

func (c *CacheService) Delete(ctx context.Context, keys ...string) error

Delete removes a key from the cache.

func (*CacheService) Exists

func (c *CacheService) Exists(ctx context.Context, keys ...string) (int64, error)

Exists checks if keys exist in the cache.

func (*CacheService) Get

func (c *CacheService) Get(ctx context.Context, key string, dest any) error

Get retrieves a value from the cache and unmarshals it into the provided destination.

func (*CacheService) Set

func (c *CacheService) Set(ctx context.Context, key string, value any, ttl time.Duration) error

Set stores a value in the cache with the specified TTL.

func (*CacheService) TTL

func (c *CacheService) TTL(ctx context.Context, key string) (time.Duration, error)

TTL returns the time to live for a key.

type Config

type Config struct {
	// RedisURL is the Redis connection string.
	// Examples:
	//   "redis://localhost:6379/0"
	//   "redis://user:password@localhost:6379/0"
	//   "rediss://user:password@redis.example.com:6380/0" (TLS)
	RedisURL string

	// Connection pool configuration
	PoolSize     int           // Maximum number of socket connections (default: 10)
	MinIdleConns int           // Minimum number of idle connections (default: 2)
	MaxIdleTime  time.Duration // Maximum amount of time a connection may be idle (default: 30 minutes)
	MaxConnAge   time.Duration // Maximum amount of time a connection may be reused (default: 1 hour)
	PoolTimeout  time.Duration // Amount of time client waits for connection (default: 4 seconds)

	// Timeouts
	DialTimeout  time.Duration // Timeout for establishing new connections (default: 5 seconds)
	ReadTimeout  time.Duration // Timeout for socket reads (default: 3 seconds)
	WriteTimeout time.Duration // Timeout for socket writes (default: 3 seconds)

	// TLS configuration (for rediss:// URLs)
	TLSConfig *tls.Config

	// Health check configuration
	HealthCheckTimeout time.Duration // Timeout for health check operations (default: 5 seconds)

	// Database selection (can be overridden by URL)
	Database int // Redis database number (default: 0)
}

Config contains Redis-specific configuration options.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible defaults.

func (*Config) SanitizedRedisURL

func (c *Config) SanitizedRedisURL() string

SanitizedRedisURL returns a sanitized version of the Redis URL for logging. This removes sensitive credentials while preserving connection information.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the Redis configuration.

type DistributedLock

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

DistributedLock provides Redis-based distributed locking.

func (*DistributedLock) TryLock

func (l *DistributedLock) TryLock(ctx context.Context) (bool, error)

TryLock attempts to acquire the distributed lock.

func (*DistributedLock) Unlock

func (l *DistributedLock) Unlock(ctx context.Context) error

Unlock releases the distributed lock.

type PubSubService

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

PubSubService provides pub/sub messaging capabilities.

func NewPubSubService

func NewPubSubService(client redis.UniversalClient) *PubSubService

NewPubSubService creates a new pub/sub service.

func (*PubSubService) PSubscribe

func (p *PubSubService) PSubscribe(ctx context.Context, patterns ...string) *Subscription

PSubscribe subscribes to channels matching patterns and returns a managed subscription.

func (*PubSubService) Publish

func (p *PubSubService) Publish(ctx context.Context, channel string, message any) error

Publish publishes a message to the specified channel.

func (*PubSubService) Subscribe

func (p *PubSubService) Subscribe(ctx context.Context, channels ...string) *Subscription

Subscribe subscribes to one or more channels and returns a managed subscription.

type RateLimiter

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

RateLimiter provides Redis-based rate limiting using sliding window.

func (*RateLimiter) Allow

func (r *RateLimiter) Allow(ctx context.Context, key string, limit int, window time.Duration) (bool, error)

Allow checks if a request is allowed under the rate limit using atomic Lua script.

type RedisHealthCheck

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

RedisHealthCheck implements health checking for Redis connections.

func (*RedisHealthCheck) Liveness

func (c *RedisHealthCheck) Liveness(ctx context.Context) error

Liveness performs a basic connectivity check.

func (*RedisHealthCheck) Name

func (c *RedisHealthCheck) Name() string

Name returns the health check name.

func (*RedisHealthCheck) Readiness

func (c *RedisHealthCheck) Readiness(ctx context.Context) error

Readiness performs a basic connectivity check.

type Subscription

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

Subscription represents a managed Redis subscription with proper cleanup.

func (*Subscription) Close

func (s *Subscription) Close() error

Close properly closes the subscription and cleans up resources.

func (*Subscription) Messages

func (s *Subscription) Messages() <-chan *redis.Message

Messages returns the channel for receiving messages.

Jump to

Keyboard shortcuts

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