redis

package
v0.1.21 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func HealthChecker added in v0.1.19

func HealthChecker() health.Checker

HealthChecker returns a health.Checker that verifies Redis connectivity by pinging the default client. The returned Checker reports health.StatusUnhealthy when no client has been initialised or when the ping fails; health.StatusHealthy when reachable.

Example

ExampleHealthChecker shows how to wire HealthChecker into a health.Check call for a /health HTTP endpoint. In test environments with no reachable Redis server, the Checker reports StatusUnhealthy.

package main

import (
	"context"
	"fmt"

	"github.com/phcp-tech/common-library-golang/health"
	"github.com/phcp-tech/common-library-golang/redis"
)

func main() {
	results := health.Check(context.Background(), redis.HealthChecker())
	fmt.Println(results[0].Name)
	fmt.Println(results[0].Status == health.StatusUnhealthy) // true — no reachable Redis
}
Output:
redis
true

func InitDefault

func InitDefault(cfg *Config) error

InitDefault initialises the package-level default Redis client singleton using the provided configuration. It is safe to call multiple times; only the first call takes effect. InitDefault initialises the package-level default Redis client singleton using the provided configuration. It is safe to call multiple times; only the first call takes effect.

Example

ExampleInitDefault shows the singleton pattern: call InitDefault once at application startup. Subsequent calls are silently ignored (sync.Once).

package main

import (
	"github.com/phcp-tech/common-library-golang/redis"
)

func main() {
	if err := redis.InitDefault(&redis.Config{
		Clusters: []string{"127.0.0.1:6379"},
	}); err != nil {
		// handle error
		return
	}
	_ = redis.Default() // *RedisClient, ready to use
}

Types

type Config

type Config struct {
	Clusters     []string // Redis node addresses; more than one address enables cluster mode
	DB           int      // database index (ignored in cluster mode)
	Password     string   // authentication password
	PoolSize     int      // max socket connections per node; default: 100
	MinIdleConns int      // minimum idle connections to maintain; default: 5
}

Config holds connection and pool settings for a Redis client. The caller is responsible for reading values from env (or any other source) at the composition root so this package has no dependency on env. Zero-value int fields fall back to the package defaults above.

type RedisClient

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

RedisClient wraps a go-redis universal client and provides a simplified API for common Redis operations, supporting both standalone and cluster modes.

func Default

func Default() *RedisClient

Default returns a default singleton instance of the Redis client. If you want to use any other instance, please call NewRedisClient.

func NewRedisClient

func NewRedisClient(conf *Config) *RedisClient

NewRedisClient creates a new RedisClient using the provided configuration. Zero-value PoolSize and MinIdleConns fall back to the package defaults.

Example

ExampleNewRedisClient shows how to create a standalone Redis client. The caller is responsible for reading configuration from env (or any other source) at the composition root — this package has no dependency on env.

package main

import (
	"github.com/phcp-tech/common-library-golang/redis"
)

func main() {
	cli := redis.NewRedisClient(&redis.Config{
		Clusters: []string{"127.0.0.1:6379"},
		DB:       0,
		Password: "",
	})
	defer cli.Close()
}
Example (Cluster)

ExampleNewRedisClient_cluster shows how to connect to a Redis cluster. Providing more than one address automatically enables cluster mode.

package main

import (
	"github.com/phcp-tech/common-library-golang/redis"
)

func main() {
	cli := redis.NewRedisClient(&redis.Config{
		Clusters: []string{
			"127.0.0.1:7000",
			"127.0.0.1:7001",
			"127.0.0.1:7002",
		},
		PoolSize:     200,
		MinIdleConns: 10,
	})
	defer cli.Close()
}
Example (CustomPool)

ExampleNewRedisClient_customPool shows how to override the default connection pool settings. Zero-value fields fall back to package defaults (PoolSize=100, MinIdleConns=5).

package main

import (
	"github.com/phcp-tech/common-library-golang/redis"
)

func main() {
	cli := redis.NewRedisClient(&redis.Config{
		Clusters:     []string{"127.0.0.1:6379"},
		PoolSize:     50,
		MinIdleConns: 2,
	})
	defer cli.Close()
}

func (*RedisClient) CleanCache

func (c *RedisClient) CleanCache(ctx context.Context, key string) error

CleanCache removes all keys whose names begin with the given prefix. It uses SCAN to iterate without blocking and Unlink for async deletion. Both standalone and cluster deployments are handled automatically.

Example

ExampleRedisClient_CleanCache shows how to remove all keys that share a common prefix. Useful for invalidating a group of cached entries at once.

package main

import (
	"context"

	"github.com/phcp-tech/common-library-golang/redis"
)

func main() {
	cli := redis.NewRedisClient(&redis.Config{
		Clusters: []string{"127.0.0.1:6379"},
	})
	defer cli.Close()

	// Remove all keys whose names start with "user:42:".
	_ = cli.CleanCache(context.Background(), "user:42:")
}

func (*RedisClient) Close

func (c *RedisClient) Close()

Close closes the underlying Redis connection if it is open.

func (*RedisClient) Del

func (c *RedisClient) Del(ctx context.Context, key ...string) (count int64, err error)

Del returns the number of keys deleted. If the key does not exist, count is 0 and err is nil.

func (*RedisClient) Exists

func (c *RedisClient) Exists(ctx context.Context, key ...string) (count int64, err error)

Exists returns the number of keys. If the key does not exist, count is 0 and err is nil.

func (*RedisClient) Get

func (c *RedisClient) Get(ctx context.Context, key string) (value string, err error)

Get returns the value for the key, or an error if the key does not exist. The error will be redis.Nil with message "redis: nil".

func (*RedisClient) GetKeysCount

func (c *RedisClient) GetKeysCount(ctx context.Context, key string) (int, error)

GetKeysCount returns the total number of keys matching the given pattern across all Redis nodes. It automatically handles both standalone and cluster deployments.

Example

ExampleRedisClient_GetKeysCount shows how to count all keys matching a pattern across all Redis nodes (standalone or cluster).

package main

import (
	"context"

	"github.com/phcp-tech/common-library-golang/redis"
)

func main() {
	cli := redis.NewRedisClient(&redis.Config{
		Clusters: []string{"127.0.0.1:6379"},
	})
	defer cli.Close()

	_, _ = cli.GetKeysCount(context.Background(), "session:*")
}

func (*RedisClient) Ping

func (c *RedisClient) Ping(ctx context.Context) (string, error)

Ping checks connectivity to the Redis server and returns "PONG" on success, or an error if the client is not initialised or the server is unreachable.

func (*RedisClient) Set

func (c *RedisClient) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) (result string, err error)

Set returns "OK" on success, or an error if the operation fails

Example

ExampleRedisClient_Set shows how to store a key-value pair with an optional TTL. Pass 0 as the expiration to store the key without expiry.

package main

import (
	"context"

	"time"

	"github.com/phcp-tech/common-library-golang/redis"
)

func main() {
	cli := redis.NewRedisClient(&redis.Config{
		Clusters: []string{"127.0.0.1:6379"},
	})
	defer cli.Close()

	ctx := context.Background()

	// Store without TTL.
	_, _ = cli.Set(ctx, "greeting", "hello", 0)

	// Store with 5-minute TTL.
	_, _ = cli.Set(ctx, "session:abc", "data", 5*time.Minute)
}
func (c *RedisClient) Unlink(ctx context.Context, key ...string) (count int64, err error)

Unlink returns the number of keys unlinked. If the key does not exist, count is 0 and err is nil. Unlike Del, Unlink performs asynchronous deletion in a separate thread, making it non-blocking for large keys.

Directories

Path Synopsis
Package component provides Redis lifecycle integration for bootstrap.
Package component provides Redis lifecycle integration for bootstrap.

Jump to

Keyboard shortcuts

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