Documentation
¶
Index ¶
- func HealthChecker() health.Checker
- func InitDefault(cfg *Config) error
- type Config
- type RedisClient
- func (c *RedisClient) CleanCache(ctx context.Context, key string) error
- func (c *RedisClient) Close()
- func (c *RedisClient) Del(ctx context.Context, key ...string) (count int64, err error)
- func (c *RedisClient) Exists(ctx context.Context, key ...string) (count int64, err error)
- func (c *RedisClient) Get(ctx context.Context, key string) (value string, err error)
- func (c *RedisClient) GetKeysCount(ctx context.Context, key string) (int, error)
- func (c *RedisClient) Ping(ctx context.Context) (string, error)
- func (c *RedisClient) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) (result string, err error)
- func (c *RedisClient) Unlink(ctx context.Context, key ...string) (count int64, err error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func HealthChecker ¶ added in v0.1.19
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 ¶
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
}
Output:
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()
}
Output:
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()
}
Output:
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()
}
Output:
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:")
}
Output:
func (*RedisClient) Close ¶
func (c *RedisClient) Close()
Close closes the underlying Redis connection if it is open.
func (*RedisClient) Del ¶
Del returns the number of keys deleted. If the key does not exist, count is 0 and err is nil.
func (*RedisClient) Exists ¶
Exists returns the number of keys. If the key does not exist, count is 0 and err is nil.
func (*RedisClient) Get ¶
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 ¶
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:*")
}
Output:
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)
}
Output: