redis

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package redis wraps go-redis with cache-aside, a fiber.Storage adapter, pub/sub, and bulk/atomic helpers.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParseRedisOptions

func ParseRedisOptions(redisURL string) (*redis.Options, error)

ParseRedisOptions parses a redis:// URL into options.

func Remember

func Remember[T any](ctx context.Context, r *Redis, key string, ttl time.Duration, loader func() (T, error)) (T, error)

Remember returns the cached value for key, or runs loader on a cache miss, stores its result with ttl, and returns it. A failure to store the loaded value does not fail the call.

Types

type Client

type Client = redis.Client

Client is re-exported from go-redis so callers need not import that package directly.

type Redis

type Redis struct {
	Client *Client
}

Redis wraps a go-redis client with JSON (de)serialization helpers.

func New

func New(client *Client) *Redis

New creates a new Redis wrapper.

func (*Redis) Decr added in v0.6.0

func (r *Redis) Decr(ctx context.Context, key string) (int64, error)

Decr atomically decrements the integer value of key by one and returns the new value.

func (*Redis) Delete

func (r *Redis) Delete(ctx context.Context, keys ...string) error

Delete removes the given keys. It is a no-op (returns nil) when no keys are given.

func (*Redis) Exists

func (r *Redis) Exists(ctx context.Context, key string) (bool, error)

Exists reports whether key is present.

func (*Redis) Expire

func (r *Redis) Expire(ctx context.Context, key string, ttl time.Duration) (bool, error)

Expire sets a time-to-live on key. The returned bool reports whether the key existed (and therefore whether the TTL was applied).

func (*Redis) Get

func (r *Redis) Get(ctx context.Context, key string, dest any) error

Get reads key and JSON-decodes it into dest. Returns an error on cache miss.

func (*Redis) GetSet added in v0.6.0

func (r *Redis) GetSet(ctx context.Context, key string, value any) (string, error)

GetSet JSON-encodes value, stores it under key, and returns the previous raw value. The returned string is empty (with a redis.Nil error) when key did not exist.

func (*Redis) Incr added in v0.6.0

func (r *Redis) Incr(ctx context.Context, key string) (int64, error)

Incr atomically increments the integer value of key by one and returns the new value.

func (*Redis) MGet added in v0.6.0

func (r *Redis) MGet(ctx context.Context, keys ...string) (map[string]string, error)

MGet returns the raw stored value for each key that exists, keyed by key. Missing keys are omitted. Callers unmarshal the raw values themselves.

func (*Redis) MSet added in v0.6.0

func (r *Redis) MSet(ctx context.Context, pairs map[string]any, ttl time.Duration) error

MSet JSON-encodes and stores each pair. When ttl > 0 it is applied to every key. Executed in a single pipeline round-trip.

func (*Redis) Publish added in v0.4.0

func (r *Redis) Publish(ctx context.Context, channel string, value any) error

Publish JSON-encodes value and publishes it to channel.

func (*Redis) Set

func (r *Redis) Set(ctx context.Context, key string, value any, expiration time.Duration) error

Set JSON-encodes value and stores it under key with the given expiration.

func (*Redis) SetNX added in v0.6.0

func (r *Redis) SetNX(ctx context.Context, key string, value any, ttl time.Duration) (bool, error)

SetNX JSON-encodes value and sets it only if key does not already exist. It reports whether the key was set.

func (*Redis) TTL

func (r *Redis) TTL(ctx context.Context, key string) (time.Duration, error)

TTL returns the remaining lifetime of key. Following go-redis semantics, a missing key yields a negative duration (-2) and a key without an expiry yields -1.

type Storage added in v0.4.0

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

Storage adapts a go-redis client to the fiber.Storage interface (used by the rate limiter and other Fiber middleware). Keys are namespaced with a prefix so Reset is scoped and entries never collide with application cache keys.

func NewStorage added in v0.4.0

func NewStorage(client *Client, opts ...StorageOption) *Storage

NewStorage adapts client to fiber.Storage.

Example

NewStorage adapts a go-redis client to fiber.Storage, e.g. for a multi-instance rate limiter. miniredis stands in for real Redis here.

package main

import (
	"fmt"
	"time"

	"github.com/alicebob/miniredis/v2"
	fibrredis "github.com/rahmadafandi/fibr/redis"

	goredis "github.com/redis/go-redis/v9"
)

func main() {
	mr, _ := miniredis.Run()
	defer mr.Close()

	client := goredis.NewClient(&goredis.Options{Addr: mr.Addr()})
	store := fibrredis.NewStorage(client, fibrredis.WithPrefix("ratelimit:"))

	_ = store.Set("1.2.3.4", []byte("1"), time.Minute)
	v, _ := store.Get("1.2.3.4")

	fmt.Println(string(v))
}
Output:
1

func (*Storage) Close added in v0.4.0

func (s *Storage) Close() error

Close closes the underlying go-redis client. Call it only if this Storage owns the client; do not close a client shared with other consumers here.

func (*Storage) Delete added in v0.4.0

func (s *Storage) Delete(key string) error

Delete removes key.

func (*Storage) Get added in v0.4.0

func (s *Storage) Get(key string) ([]byte, error)

Get returns the value for key, or (nil, nil) if it is missing.

func (*Storage) Reset added in v0.4.0

func (s *Storage) Reset() error

Reset deletes every key under the prefix (not the whole database). It deletes in batches so a large key space does not build one giant DEL.

func (*Storage) Set added in v0.4.0

func (s *Storage) Set(key string, val []byte, exp time.Duration) error

Set stores val under key with the given expiration (0 means no expiry). An empty key or value is a no-op, matching fiber's storage adapters (nil and []byte{} are treated alike).

type StorageOption added in v0.4.0

type StorageOption func(*Storage)

StorageOption configures a Storage.

func WithPrefix added in v0.4.0

func WithPrefix(prefix string) StorageOption

WithPrefix sets the key namespace (default "fiber:storage:").

type Subscription added in v0.4.0

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

Subscription is an active subscription. Close stops the background goroutine and unsubscribes.

func Subscribe added in v0.4.0

func Subscribe[T any](ctx context.Context, r *Redis, channel string, handler func(context.Context, T) error) (*Subscription, error)

Subscribe subscribes to channel and invokes handler for each message (payload JSON-decoded into T) in a background goroutine, until ctx is cancelled or the returned Subscription is closed. Decode and handler errors are logged; a bad message is skipped without ending the subscription.

Example

Publish an event on one instance; every instance subscribed to the channel runs its handler with the decoded payload (e.g. to bust a local cache).

package main

import (
	"context"

	fibrredis "github.com/rahmadafandi/fibr/redis"
	goredis "github.com/redis/go-redis/v9"
)

func main() {
	r := fibrredis.New(goredis.NewClient(&goredis.Options{Addr: "localhost:6379"}))
	ctx := context.Background()

	type invalidate struct {
		Key string `json:"key"`
	}

	sub, err := fibrredis.Subscribe[invalidate](ctx, r, "cache:invalidate", func(_ context.Context, e invalidate) error {
		// drop e.Key from a local cache here
		return nil
	})
	if err != nil {
		return
	}
	defer sub.Close()

	_ = r.Publish(ctx, "cache:invalidate", invalidate{Key: "user:1"})
}

func (*Subscription) Close added in v0.4.0

func (s *Subscription) Close() error

Close stops the subscription and releases its connection.

Jump to

Keyboard shortcuts

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