redis

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: May 17, 2026 License: MIT Imports: 10 Imported by: 0

README

redis — Redis client with distributed locking

import "github.com/downsized-devs/sdk-go/redis"

Stability: Stable — see STABILITY.md

Wraps go-redis/redis and bsm/redislock. Supports TLS, exposes a CRC16 helper for cluster slot routing.

Features

  • Get / SetEX with default TTL fallback
  • Distributed lock: Lock / LockRelease
  • Del, FlushAll, FlushAllAsync, FlushDB, FlushDBAsync, Ping
  • Optional TLS with private CA / mTLS
  • CRC16(s) for cluster slot hashing

Installation

go get github.com/downsized-devs/sdk-go/redis

Quick Start

import (
    "context"
    "time"

    "github.com/downsized-devs/sdk-go/logger"
    "github.com/downsized-devs/sdk-go/redis"
)

log := logger.Init(logger.Config{Level: "info"})
rdb := redis.Init(redis.Config{
    Address:    "localhost:6379",
    DefaultTTL: 5 * time.Minute,
}, log)

ctx := context.Background()
_ = rdb.SetEX(ctx, "hello", "world", time.Minute)
val, _ := rdb.Get(ctx, "hello")

API Reference

Construction
func Init(cfg Config, log logger.Interface) Interface
Interface
Method Signature Notes
Get (ctx, key string) (string, error) Returns redis.Nil on miss.
SetEX (ctx, key, val string, ttl time.Duration) error 0 ttl → Config.DefaultTTL.
Del (ctx, key string) error
Lock (ctx, key string, expTime time.Duration) (*redislock.Lock, error) redis.ErrNotObtained if contended.
LockRelease (ctx, lock *redislock.Lock) error Pair every Lock.
FlushAll/FlushAllAsync (ctx) error Wipes every database.
FlushDB/FlushDBAsync (ctx) error Wipes selected database.
Ping (ctx) error Liveness check.
GetDefaultTTL (ctx) time.Duration
Top-level helpers
Symbol Purpose
Nil Sentinel for Get miss; same as go-redis/redis.Nil.
ErrNotObtained Returned by Lock when contended.
CRC16(s string) uint16 CRC16-XMODEM, used for cluster slot routing.

Configuration

Field Type Required Default Description
Address string yes host:port.
Password string no ""
DB int no 0 DB index.
DefaultTTL time.Duration no 0 Used when SetEX ttl is 0.
TLS.Enabled bool no false
TLS.CA/Cert/Key string conditional Required for private CA / mTLS.

Examples

Cache-aside
val, err := rdb.Get(ctx, "user:"+id)
if errors.Is(err, redis.Nil) {
    user, err := repo.LoadUser(ctx, id)
    if err != nil { return nil, err }
    _ = rdb.SetEX(ctx, "user:"+id, user.Marshal(), 5*time.Minute)
    return user, nil
}
Distributed lock around a cron task
lock, err := rdb.Lock(ctx, "cron:nightly-rollup", 10*time.Minute)
if errors.Is(err, redis.ErrNotObtained) {
    return nil // another instance has it
}
if err != nil { return err }
defer rdb.LockRelease(ctx, lock)

return doRollup(ctx)

Error Handling

Error Action
redis.Nil Treat as miss; reload from origin.
redis.ErrNotObtained Skip work or back off.
Coded errors Inspect with errors.GetCode(err).

Dependencies

  • Internal: codes, errors, logger
  • External: github.com/go-redis/redis/v8, github.com/bsm/redislock

Testing

go test ./redis/...

Two test files; unit test runs without a live Redis.

Contributing

See CONTRIBUTING.md. New multi-key methods should be verified with CRC16 to ensure all keys hash to the same cluster slot.

  • sql — primary store; pair for cache-aside.
  • scheduler — uses Redis locks to coordinate cron across replicas.
  • instrument — register Redis hit/miss metrics.

Documentation

Index

Constants

View Source
const (
	Nil = redis.Nil //nolint: errname
)

Variables

View Source
var ErrNotObtained = redislock.ErrNotObtained

Functions

func CRC16

func CRC16(s string) uint16

Redis CRC16 is a hash function used by Redis to calculate the hash slot for keys in a Redis cluster. The algorithm is based on the CRC16-CCITT polynomial and uses a lookup table to quickly calculate the CRC.

Types

type Config

type Config struct {
	Protocol   string
	Host       string
	Port       string
	Username   string
	Password   string
	DefaultTTL time.Duration
	TLS        TLSConfig
}

type Interface

type Interface interface {
	Get(ctx context.Context, key string) (string, error)
	SetEX(ctx context.Context, key string, val string, expTime time.Duration) error
	Lock(ctx context.Context, key string, expTime time.Duration) (*redislock.Lock, error)
	LockRelease(ctx context.Context, lock *redislock.Lock) error
	Del(ctx context.Context, key string) error
	FlushAll(ctx context.Context) error
	FlushAllAsync(ctx context.Context) error
	FlushDB(ctx context.Context) error
	FlushDBAsync(ctx context.Context) error
	GetDefaultTTL(ctx context.Context) time.Duration
	Ping(ctx context.Context) error
}

func Init

func Init(cfg Config, log logger.Interface) Interface

type Locker

type Locker *redislock.Lock

type TLSConfig

type TLSConfig struct {
	Enabled            bool
	InsecureSkipVerify bool
}

Jump to

Keyboard shortcuts

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