rds

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

README

go-rds

A high-level Redis client library for Go that provides type-safe operations, batch processing, and enhanced Redis data structure support.

Features

  • Type-safe operations: Automatic encoding/decoding for various data types
  • Batch processing: Efficient batch operations with configurable batch sizes
  • Redis data structures: Comprehensive support for Strings, Hashes, Lists, Sets, and Sorted Sets
  • Distributed locking: Built-in Redis lock implementation
  • Stream support: Redis Stream operations for message queuing
  • Cache penetration protection: Mechanisms to prevent cache penetration
  • Connection management: Redis client with version detection and connection pooling

Installation

go get github.com/stephenfire/go-rds

Quick Start

Basic Usage
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/stephenfire/go-rds"
)

func main() {
	ctx := context.Background()
	
	// Connect to Redis
	client, err := rds.ConnectRedis(ctx, "redis://localhost:6379")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	// Set a value
	err = client.Set(ctx, "mykey", "Hello, Redis!", 10*time.Minute)
	if err != nil {
		log.Fatal(err)
	}

	// Get a value
	value, exists, err := client.Get(ctx, "mykey", reflect.TypeOf(""))
	if err != nil {
		log.Fatal(err)
	}
	if exists {
		fmt.Println("Value:", value.(string))
	}
}
String Operations
// Create a string reader/writer
stringRW := rds.NewRedisString[string, string](
	client.C(),
	rds.RedisStringEncoder,
	rds.RedisStringDecoder,
	rds.RedisStringEncoder,
	rds.RedisStringDecoder,
)

// Set multiple values
err := stringRW.Sets(ctx, map[string]string{
	"key1": "value1",
	"key2": "value2",
	"key3": "value3",
})

// Get multiple values
notCached, cached, err := stringRW.Gets(ctx, "key1", "key2", "key3")
Hash Operations
// Create a hash reader/writer
hasher := rds.NewRedisHasher[string, int64](
	client.C(),
	rds.RedisStringEncoder, rds.RedisStringDecoder,
	rds.RedisInt64Encoder, rds.RedisInt64Decoder,
)

// Set hash values
err := hasher.HSetsMap(ctx, "user:scores", map[string]int64{
	"user1": 100,
	"user2": 200,
	"user3": 300,
})

// Get hash values
notCached, cached, err := hasher.HGets(ctx, "user:scores", "user1", "user2")
Sorted Set Operations
// Create a sorted set for ID scores
zset := rds.NewIdScoreZSet(client.C())

// Add scores to sorted set
scores := []*rds.IdScore{
	{Id: 1, Score: 100},
	{Id: 2, Score: 200},
	{Id: 3, Score: 300},
}

count, err := zset.ZAdd(ctx, "leaderboard", scores...)

// Query top 10 scores
args := &rds.ZArgs{}
args.WithKey("leaderboard").ByScore().Range(0, 1000).Paginate(0, 10).Rev()
topScores, err := zset.ZRangeWithScores(ctx, args)
Distributed Locking
// Create a Redis lock
locker := redislock.New(client.C())
redisLock := rds.NewRedisLock(client.C(), locker, "my-lock", "lock-value", 30*time.Second)

// Acquire lock
lockingValue, err := redisLock.Fetch(ctx)
if err != nil {
	log.Fatal("Failed to acquire lock")
}

// Do critical work
fmt.Println("Lock acquired, doing critical work...")

// Release lock
err = redisLock.Release()
if err != nil {
	log.Fatal("Failed to release lock")
}
Stream Operations
// Initialize stream group
err := client.InitStreamGroup(ctx, "mystream", "mygroup")

// Push messages to stream
messages := []map[string]interface{}{
	{"field1": "value1", "field2": 123},
	{"field1": "value2", "field2": 456},
}

err = client.QueuePushMaxLen(ctx, "mystream", 1000, messages...)

// Read messages from stream
msgs, err := client.QueueReadGroup(ctx, "mystream", "mygroup", "worker1", 5*time.Second, 10)

Configuration

Connection Options
// Custom connection with specific timeouts
opts, err := redis.ParseURL("redis://localhost:6379")
if err != nil {
	log.Fatal(err)
}
opts.ReadTimeout = 2 * time.Second
opts.WriteTimeout = 5 * time.Second

client := redis.NewClient(opts)
redisClient := &rds.RedisClient{Client: client}
Batch Size Configuration
// Configure batch sizes for different operations
const (
	ModelsBatchSize = 100  // For hash operations
	BatchSize       = 500  // For sorted set operations
)

Advanced Usage

Custom Type Encoding/Decoding
type User struct {
	ID    int64  `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
}

// Custom encoder
func userEncoder(u User) (string, error) {
	return rds.RedisEncode(u)
}

// Custom decoder  
func userDecoder(s string) (User, error) {
	var u User
	err := rds.RedisDecode(reflect.TypeOf(u), s, &u)
	return u, err
}

// Use custom types
userHasher := rds.NewRedisHasher[int64, User](
	client.C(),
	rds.RedisInt64Encoder, rds.RedisInt64Decoder,
	userEncoder, userDecoder,
)
Cache Penetration Protection
// Using HGetsAndSetsIfNA to prevent cache penetration
flagField := int64(-1) // Special flag field
placeholderUser := User{ID: -1, Name: "", Email: ""}

users, err := userHasher.HGetsAndSetsIfNA(ctx, "users:cache", 
	func(ctx context.Context) (map[int64]User, error) {
		// Load all users from database
		return loadAllUsersFromDB(ctx)
	}, 
	flagField, 
	userID1, userID2, userID3,
)

Error Handling

// Check for Redis nil errors
value, exists, err := client.Get(ctx, "nonexistent", reflect.TypeOf(""))
if err != nil {
	if rds.IsRedisNil(err) {
		fmt.Println("Key does not exist")
	} else {
		log.Fatal(err)
	}
}

Performance Considerations

  • Use appropriate batch sizes for your workload
  • Consider using pipeline for multiple operations
  • Monitor memory usage for large datasets
  • Use connection pooling for high-throughput applications

License

Apache License 2.0 - See LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

For support and questions, please open an issue on GitHub.

Documentation

Index

Constants

View Source
const (
	ModelsBatchSize = 100
	BatchSize       = 500

	TypeKeyNone   = "none"
	TypeKeyStream = "stream"

	RdbStatusOK         = "OK"
	ErrBUSYGROUPKeyword = "BUSYGROUP"

	// DefaultStartScore zset default score range
	DefaultStartScore = "0"
	DefaultStopScore  = "+inf"

	StringPlaceHolder = "_"
	IdPlaceHolder     = 0
	NegIdPlaceHolder  = -1

	// HashExpireMinVersion min version of redis-server starting support HExpire
	HashExpireMinVersion = common.Version(7004000)
)
View Source
const (
	RedisTimeout      = 10 * time.Second
	RedisReadTimeout  = 2 * time.Second
	RedisWriteTimeout = 5 * time.Second
)

Variables

View Source
var (
	ErrInvalidValue    = errors.New("rds: invalid value object")
	ErrExpectingString = errors.New("rds: expecting string")
)
View Source
var EmptyZ = redis.Z{Score: -1, Member: "0"}

Functions

func Float64ToInt64

func Float64ToInt64(f float64) (int64, error)

func IdScoreToZ

func IdScoreToZ(is *IdScore) (redis.Z, bool, error)

func Int64ToFloat64

func Int64ToFloat64(i int64) (float64, error)

func IsRedisNil

func IsRedisNil(err error) bool

func IsRedisNoGroup

func IsRedisNoGroup(err error) bool

func MapKV

func MapKV[K comparable, V any, T KeyValuer[K, V]](values []T) map[K]V

func NewTimeZ

func NewTimeZ(id int64, ts time.Time) redis.Z

func NewZ

func NewZ(member string, score int64) redis.Z

func RedisDecode

func RedisDecode(typ reflect.Type, strVal string) (any, error)

func RedisEncode

func RedisEncode(value any) (string, error)

func RedisInt64Decoder

func RedisInt64Decoder(s string) (int64, error)

func RedisInt64Encoder

func RedisInt64Encoder(s int64) (string, error)

func RedisInt64SliceDecoder

func RedisInt64SliceDecoder(s string) ([]int64, error)

func RedisInt64SliceEncoder

func RedisInt64SliceEncoder(s []int64) (string, error)

func RedisStringDecoder

func RedisStringDecoder(s string) (string, error)

func RedisStringEncoder

func RedisStringEncoder(s string) (string, error)

func RedisStringSliceDecoder

func RedisStringSliceDecoder(s string) ([]string, error)

func RedisStringSliceEncoder

func RedisStringSliceEncoder(s []string) (string, error)

func RedisUint64Decoder

func RedisUint64Decoder(s string) (uint64, error)

func RedisUint64Encoder

func RedisUint64Encoder(s uint64) (string, error)

func RedisValueDecode

func RedisValueDecode[T any](val any, decoder func(string) (T, error)) (exist bool, t T, err error)

func TypeDecoder

func TypeDecoder[T any](typ reflect.Type, strVal string) (t T, err error)

func TypeEncoder

func TypeEncoder[T any](value T) (string, error)

Types

type BatchIterator

type BatchIterator[T any] struct {
	// contains filtered or unexported fields
}

func NewBatchIterator

func NewBatchIterator[T any](ts []T, size ...int) *BatchIterator[T]

func (*BatchIterator[T]) Current

func (b *BatchIterator[T]) Current() []T

func (*BatchIterator[T]) HasNext

func (b *BatchIterator[T]) HasNext() bool

func (*BatchIterator[T]) Next

func (b *BatchIterator[T]) Next() []T

func (*BatchIterator[T]) String

func (b *BatchIterator[T]) String() string

type IdScore

type IdScore struct {
	Id    int64
	Score int64
}

func ZToIdScore

func ZToIdScore(z redis.Z) (*IdScore, error)

func (*IdScore) ScoreTime

func (i *IdScore) ScoreTime() tools.Time

type IsNil

type IsNil[T any] func(T) bool

type KeyValuer

type KeyValuer[K comparable, V any] interface {
	Key() K
	Value() V
}

func ConvertKV

func ConvertKV[K comparable, V any, T KeyValuer[K, V]](values []T) []KeyValuer[K, V]

type MapLoader

type MapLoader[K comparable, V any] func(ctx context.Context, ks ...K) (map[K]V, error)

type RedisAtomicPointer

type RedisAtomicPointer[T any] struct {
	// contains filtered or unexported fields
}

func NewAtomicPointer

func NewAtomicPointer[T any](newT func(client *RedisClient, batchSize ...int) *T) *RedisAtomicPointer[T]

func (*RedisAtomicPointer[T]) Get

func (a *RedisAtomicPointer[T]) Get(client *RedisClient, batchSize ...int) *T

type RedisBatchValue

type RedisBatchValue[V any] struct {
	// contains filtered or unexported fields
}

type RedisClient

type RedisClient struct {
	*redis.Client
	// contains filtered or unexported fields
}

func ConnectRedis

func ConnectRedis(ctx context.Context, url string) (*RedisClient, error)

func (*RedisClient) C

func (c *RedisClient) C() *redis.Client

func (*RedisClient) Del

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

func (*RedisClient) Exist

func (c *RedisClient) Exist(ctx context.Context, key string) bool

func (*RedisClient) Get

func (c *RedisClient) Get(ctx context.Context, key string, typ reflect.Type) (any, bool, error)

func (*RedisClient) GetIds

func (c *RedisClient) GetIds(ctx context.Context, key string) ([]int64, bool, error)

func (*RedisClient) GetStringWithNil

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

func (*RedisClient) GetValues

func (c *RedisClient) GetValues(ctx context.Context, typ reflect.Type,
	keys ...string) (hitList []bool, values any, errr error)

GetValues returns hitList: same length as the input keys, indicates whether each key hit the cache values: array of decoded values or nil (not hit or cached nil)

func (*RedisClient) HDel

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

func (*RedisClient) HDels

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

func (*RedisClient) HGet

func (c *RedisClient) HGet(ctx context.Context, key, field string, typ reflect.Type) (any, bool, error)

func (*RedisClient) HGets

func (c *RedisClient) HGets(ctx context.Context, key string, typ reflect.Type,
	fields ...string) (hitList []bool, cached any, err error)

HGets returns cached as map[string]anyOftyp

func (*RedisClient) HGetsAll

func (c *RedisClient) HGetsAll(ctx context.Context, key string, typ reflect.Type) (any, error)

HGetsAll returns map[string]anyOftyp

func (*RedisClient) HSet

func (c *RedisClient) HSet(ctx context.Context, key, field string, value any) error

func (*RedisClient) HSetMap

func (c *RedisClient) HSetMap(ctx context.Context, key string, m map[string]any) error

func (*RedisClient) HSets

func (c *RedisClient) HSets(ctx context.Context, key string, fieldValues ...any) error

func (*RedisClient) HSetsOnce

func (c *RedisClient) HSetsOnce(ctx context.Context, key string, fieldValues ...any) error

func (*RedisClient) InitStreamGroup

func (c *RedisClient) InitStreamGroup(ctx context.Context, streamName string, groupName string) error

InitStreamGroup workers should call this at start procedure

func (*RedisClient) QueueAck

func (c *RedisClient) QueueAck(ctx context.Context, stream, group string, ids ...string) error

func (*RedisClient) QueuePush

func (c *RedisClient) QueuePush(ctx context.Context, stream string, minId string, values ...map[string]interface{}) error

func (*RedisClient) QueuePushMaxLen

func (c *RedisClient) QueuePushMaxLen(ctx context.Context, stream string, maxLen int64, values ...map[string]any) error

func (*RedisClient) QueueRead

func (c *RedisClient) QueueRead(ctx context.Context, stream string, timeout time.Duration,
	count int64, startId ...string) ([]redis.XMessage, error)

func (*RedisClient) QueueReadGroup

func (c *RedisClient) QueueReadGroup(ctx context.Context, stream, group, worker string,
	timeout time.Duration, count int64) ([]redis.XMessage, error)

func (*RedisClient) ResetZSet

func (c *RedisClient) ResetZSet(ctx context.Context, key string, zs ...redis.Z) error

func (*RedisClient) Set

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

func (*RedisClient) SetValues

func (c *RedisClient) SetValues(ctx context.Context, pairs ...any) error

func (*RedisClient) SetZSet

func (c *RedisClient) SetZSet(ctx context.Context, key string, zs ...redis.Z) error

func (*RedisClient) String

func (c *RedisClient) String() string

func (*RedisClient) Version

func (c *RedisClient) Version() common.Version

func (*RedisClient) ZScoreByPaddedIds

func (c *RedisClient) ZScoreByPaddedIds(ctx context.Context, key string, paddedIds ...string) (map[int64]int64, error)

type RedisDecoder

type RedisDecoder[T any] func(r string) (T, error)

func NewTypeDecoder

func NewTypeDecoder[T any](typ reflect.Type) RedisDecoder[T]

type RedisEncoder

type RedisEncoder[T any] func(t T) (string, error)

RedisEncoder returns "" means ignoring

type RedisFloatDecoder

type RedisFloatDecoder[S any] func(f float64) (S, error)

RedisFloatDecoder decoder for ZSet score

type RedisFloatEncoder

type RedisFloatEncoder[S any] func(v S) (float64, error)

RedisFloatEncoder encoder for ZSet score

type RedisHasher

type RedisHasher[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func NewHashReader

func NewHashReader[K comparable, V any](client redis.Cmdable, fieldEncoder RedisEncoder[K],
	fieldDecoder RedisDecoder[K], valueDecoder RedisDecoder[V]) *RedisHasher[K, V]

func NewRedisHasher

func NewRedisHasher[K comparable, V any](
	client redis.Cmdable,
	fieldEncoder RedisEncoder[K], fieldDecoder RedisDecoder[K],
	valueEncoder RedisEncoder[V], valueDecoder RedisDecoder[V]) *RedisHasher[K, V]

func NewStringInt64Hasher

func NewStringInt64Hasher(c redis.Cmdable) *RedisHasher[string, int64]

func (*RedisHasher[K, V]) FieldDecoder

func (t *RedisHasher[K, V]) FieldDecoder(decoder RedisDecoder[K]) *RedisHasher[K, V]

func (*RedisHasher[K, V]) FieldEncoder

func (t *RedisHasher[K, V]) FieldEncoder(encoder RedisEncoder[K]) *RedisHasher[K, V]

func (*RedisHasher[K, V]) HDel

func (t *RedisHasher[K, V]) HDel(ctx context.Context, key string, fields ...K) (int64, error)

func (*RedisHasher[K, V]) HDelFieldString

func (t *RedisHasher[K, V]) HDelFieldString(ctx context.Context, key string, fieldStrings ...string) (int64, error)

func (*RedisHasher[K, V]) HExists

func (t *RedisHasher[K, V]) HExists(ctx context.Context, key string, field K) (bool, error)

func (*RedisHasher[K, V]) HExpire

func (t *RedisHasher[K, V]) HExpire(ctx context.Context, key string, seconds int64, fields ...K) ([]bool, error)

func (*RedisHasher[K, V]) HGet

func (t *RedisHasher[K, V]) HGet(ctx context.Context, key string, field K) (hit bool, value V, err error)

func (*RedisHasher[K, V]) HGetAll

func (t *RedisHasher[K, V]) HGetAll(ctx context.Context, key string) (map[K]V, error)

func (*RedisHasher[K, V]) HGetAllAndSetIfNA

func (t *RedisHasher[K, V]) HGetAllAndSetIfNA(ctx context.Context, key string,
	allLoader func(ctx context.Context) (map[K]V, error), flagField K) (map[K]V, error)

func (*RedisHasher[K, V]) HGetAndSet

func (t *RedisHasher[K, V]) HGetAndSet(ctx context.Context, key string,
	dbLoader func(cctx context.Context, kks ...K) (map[K]V, error), k K) (v V, err error)

func (*RedisHasher[K, V]) HGetAndSetIfNA

func (t *RedisHasher[K, V]) HGetAndSetIfNA(ctx context.Context, key string,
	allLoader func(ctx context.Context) (map[K]V, error), flagField K, k K) (v V, err error)

func (*RedisHasher[K, V]) HGetByFieldString

func (t *RedisHasher[K, V]) HGetByFieldString(ctx context.Context, key string, fieldString string) (hit bool, value V, err error)

func (*RedisHasher[K, V]) HGetByFieldStrings

func (t *RedisHasher[K, V]) HGetByFieldStrings(ctx context.Context, key string, fieldStrings ...string) (hitList []bool, cached map[K]V, err error)

func (*RedisHasher[K, V]) HGets

func (t *RedisHasher[K, V]) HGets(ctx context.Context, key string, fields ...K) (notcached []K, cached map[K]V, err error)

func (*RedisHasher[K, V]) HGetsAndSets

func (t *RedisHasher[K, V]) HGetsAndSets(ctx context.Context, key string,
	dbLoader func(cctx context.Context, kks ...K) (map[K]V, error), ks ...K) (map[K]V, error)

HGetsAndSets read data from hashes:key using ks as the fields. If any fields do not exist, use dbLoader to read the corresponding data from the database and store it in the cache. Note that dbLoader should not return an error if the corresponding data does not exist in the database.

func (*RedisHasher[K, V]) HGetsAndSetsIfNA

func (t *RedisHasher[K, V]) HGetsAndSetsIfNA(ctx context.Context, key string,
	allLoader func(ctx context.Context) (map[K]V, error), flagField K, kks ...K) (map[K]V, error)

HGetsAndSetsIfNA 检查key是否存在,如果不存在则通过allLoader获取所有key的数据并保存 redis的hash无法存储0个field,所以当使用hash存储对象时,如果不做特殊处理,将无法缓存不存在的key(如:数据库中不存在)。 此时通过使用在field中增加一个特殊值flag(不会与真实filed重复),用来保证没有其他field时也可以使得key在redis中。 而flag对应的值则是V的缺省值。 读取时,可以通过HMGet每次都将flag读取出来,一旦flag不存在,就说明key不存在。如果flag存在,而可以说明被读取的field是否真实存在。

func (*RedisHasher[K, V]) HKeys

func (t *RedisHasher[K, V]) HKeys(ctx context.Context, key string) ([]K, error)

func (*RedisHasher[K, V]) HKeysAndSetIfNA

func (t *RedisHasher[K, V]) HKeysAndSetIfNA(ctx context.Context, key string,
	allLoader func(ctx context.Context) (map[K]V, error), flagField K) (fields []K, err error)

func (*RedisHasher[K, V]) HMustSets

func (t *RedisHasher[K, V]) HMustSets(ctx context.Context, key string, values []KeyValuer[K, V],
	mustFields []K, placeholderVal V) error

func (*RedisHasher[K, V]) HMustSetsMap

func (t *RedisHasher[K, V]) HMustSetsMap(ctx context.Context, key string, valueMap map[K]V,
	mustFields []K, placeholderVal V) error

func (*RedisHasher[K, V]) HSet

func (t *RedisHasher[K, V]) HSet(ctx context.Context, key string, field K, value V) error

func (*RedisHasher[K, V]) HSets

func (t *RedisHasher[K, V]) HSets(ctx context.Context, key string, values []KeyValuer[K, V]) error

func (*RedisHasher[K, V]) HSetsMap

func (t *RedisHasher[K, V]) HSetsMap(ctx context.Context, key string, valueMap map[K]V) error

func (*RedisHasher[K, V]) ValueDecoder

func (t *RedisHasher[K, V]) ValueDecoder(decoder RedisDecoder[V]) *RedisHasher[K, V]

func (*RedisHasher[K, V]) ValueEncoder

func (t *RedisHasher[K, V]) ValueEncoder(encoder RedisEncoder[V]) *RedisHasher[K, V]

type RedisKey

type RedisKey[K comparable] struct {
	// contains filtered or unexported fields
}

func (*RedisKey[K]) Dels

func (rk *RedisKey[K]) Dels(ctx context.Context, ks ...K) error

func (*RedisKey[K]) Exist

func (rk *RedisKey[K]) Exist(ctx context.Context, k K) bool

func (*RedisKey[K]) Key

func (rk *RedisKey[K]) Key(k K) (key string, err error)

func (*RedisKey[K]) Keys

func (rk *RedisKey[K]) Keys(ks ...K) (keys []string, err error)

type RedisList

type RedisList[V any] struct {
	RedisBatchValue[V]
	// contains filtered or unexported fields
}

func (*RedisList[V]) LRange

func (l *RedisList[V]) LRange(ctx context.Context, key string, start, stop int64) ([]V, error)

func (*RedisList[V]) RPush

func (l *RedisList[V]) RPush(ctx context.Context, key string, vs ...V) (int64, error)

func (*RedisList[V]) WithBatchSize

func (l *RedisList[V]) WithBatchSize(size int) *RedisList[V]

type RedisLock

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

func NewRedisLock

func NewRedisLock(client *redis.Client, locker *redislock.Client, key, value string, ttl time.Duration) *RedisLock

func (*RedisLock) Fetch

func (l *RedisLock) Fetch(cctx context.Context) (lockingValue string, err error)

func (*RedisLock) FetchOrRefresh

func (l *RedisLock) FetchOrRefresh(cctx context.Context) (lockingValue string, err error)

func (*RedisLock) Refresh

func (l *RedisLock) Refresh(cctx context.Context) (err error)

func (*RedisLock) Release

func (l *RedisLock) Release() (err error)

func (*RedisLock) String

func (l *RedisLock) String() string

type RedisMSZSet

type RedisMSZSet[M comparable, S any] struct {
	// contains filtered or unexported fields
}

func NewIDZSet

func NewIDZSet(client redis.Cmdable) *RedisMSZSet[int64, int64]

func NewMSZSet

func NewMSZSet[M comparable, S any](client redis.Cmdable, memberEncoder RedisEncoder[M], memberDecoder RedisDecoder[M],
	scoreEncoder RedisFloatEncoder[S], scoreDecoder RedisFloatDecoder[S], batchSize ...int) *RedisMSZSet[M, S]

func (*RedisMSZSet[M, S]) WithBatchSize added in v0.1.1

func (ms *RedisMSZSet[M, S]) WithBatchSize(batchSize int) *RedisMSZSet[M, S]

func (*RedisMSZSet[M, S]) ZAdd added in v0.1.1

func (ms *RedisMSZSet[M, S]) ZAdd(ctx context.Context, key string, msmap map[M]S) (int64, error)

func (*RedisMSZSet[M, S]) ZCount

func (ms *RedisMSZSet[M, S]) ZCount(ctx context.Context, key string, min, max string) (count int64, err error)

func (*RedisMSZSet[M, S]) ZIncrBy

func (ms *RedisMSZSet[M, S]) ZIncrBy(ctx context.Context, key string, incrBy float64, m M) (s S, err error)

func (*RedisMSZSet[M, S]) ZMScore

func (ms *RedisMSZSet[M, S]) ZMScore(ctx context.Context, key string, inputs ...M) (map[M]S, error)

func (*RedisMSZSet[M, S]) ZRangeArgs

func (ms *RedisMSZSet[M, S]) ZRangeArgs(ctx context.Context, args *ZArgs, placeHolder ...M) ([]M, error)

func (*RedisMSZSet[M, S]) ZScore

func (ms *RedisMSZSet[M, S]) ZScore(ctx context.Context, key string, m M) (s S, err error)

type RedisMsg

type RedisMsg map[string]interface{}

func (RedisMsg) ID

func (m RedisMsg) ID(key string, nilIsOk ...bool) (tools.ID, error)

func (RedisMsg) Int64

func (m RedisMsg) Int64(key string, nilIsOk ...bool) (i int64, err error)

func (RedisMsg) IsEmpty

func (m RedisMsg) IsEmpty() bool

func (RedisMsg) IsStopSignal

func (m RedisMsg) IsStopSignal() bool

func (RedisMsg) Map

func (m RedisMsg) Map() map[string]interface{}

func (RedisMsg) StopSignal

func (m RedisMsg) StopSignal() RedisMsg

func (RedisMsg) String

func (m RedisMsg) String(key string, nilIsOk ...bool) (string, error)

type RedisSet

type RedisSet[V any] struct {
	RedisBatchValue[V]
	// contains filtered or unexported fields
}

func NewRedisSet

func NewRedisSet[V any](client redis.Cmdable, encoder RedisEncoder[V], decoder RedisDecoder[V]) *RedisSet[V]

func (*RedisSet[V]) SAdd

func (s *RedisSet[V]) SAdd(ctx context.Context, key string, vs ...V) (int64, error)

func (*RedisSet[V]) SAddWithEmpty

func (s *RedisSet[V]) SAddWithEmpty(ctx context.Context, key string, emptyValue V, vs ...V) (int64, error)

func (*RedisSet[V]) SIsMember

func (s *RedisSet[V]) SIsMember(ctx context.Context, key string, v V) (bool, error)

func (*RedisSet[V]) SRem

func (s *RedisSet[V]) SRem(ctx context.Context, key string, vs ...V) (int64, error)

func (*RedisSet[V]) WithBatchSize

func (s *RedisSet[V]) WithBatchSize(size int) *RedisSet[V]

type RedisString

type RedisString[K comparable, V any] struct {
	RedisKey[K]
	// contains filtered or unexported fields
}

func NewRedisString

func NewRedisString[K comparable, V any](client redis.Cmdable, keyEncoder RedisEncoder[K],
	valueEncoder RedisEncoder[V], valueDecoder RedisDecoder[V]) *RedisString[K, V]

func NewStringReader

func NewStringReader[K comparable, V any](client redis.Cmdable, keyEncoder RedisEncoder[K],
	valueDecoder RedisDecoder[V]) *RedisString[K, V]

func NewStringWriter

func NewStringWriter[K comparable, V any](client redis.Cmdable, keyEncoder RedisEncoder[K],
	valueEncoder RedisEncoder[V]) *RedisString[K, V]

func (*RedisString[K, V]) Client

func (s *RedisString[K, V]) Client(client redis.Cmdable) *RedisString[K, V]

func (*RedisString[K, V]) Get

func (s *RedisString[K, V]) Get(ctx context.Context, k K) (exist bool, t V, err error)

func (*RedisString[K, V]) GetAndSet

func (s *RedisString[K, V]) GetAndSet(ctx context.Context,
	dbLoader func(cctx context.Context, kks ...K) (map[K]V, error), k K) (v V, err error)

func (*RedisString[K, V]) Gets

func (s *RedisString[K, V]) Gets(ctx context.Context, ks ...K) (notcached []K, cached map[K]V, err error)

func (*RedisString[K, V]) GetsAndSets

func (s *RedisString[K, V]) GetsAndSets(ctx context.Context,
	dbLoader MapLoader[K, V], ks ...K) (map[K]V, error)

func (*RedisString[K, V]) KeyEncoder

func (s *RedisString[K, V]) KeyEncoder(encoder RedisEncoder[K]) *RedisString[K, V]

func (*RedisString[K, V]) Set

func (s *RedisString[K, V]) Set(ctx context.Context, k K, v V, expire ...time.Duration) error

func (*RedisString[K, V]) Sets

func (s *RedisString[K, V]) Sets(ctx context.Context, values map[K]V) error

func (*RedisString[K, V]) ValueDecoder

func (s *RedisString[K, V]) ValueDecoder(decoder RedisDecoder[V]) *RedisString[K, V]

func (*RedisString[K, V]) ValueEncoder

func (s *RedisString[K, V]) ValueEncoder(encoder RedisEncoder[V]) *RedisString[K, V]

type RedisZDecoder

type RedisZDecoder[Z any] func(z redis.Z) (v Z, err error)

type RedisZEncoder

type RedisZEncoder[Z any] func(v Z) (z redis.Z, ok bool, err error)

RedisZEncoder returns ok==false means ignoring the value

type RedisZSet

type RedisZSet[Z any] struct {
	// contains filtered or unexported fields
}

func NewIdScoreZSet

func NewIdScoreZSet(client redis.Cmdable, batchSize ...int) *RedisZSet[*IdScore]

func NewRedisZSet

func NewRedisZSet[Z any](client redis.Cmdable, encoder RedisZEncoder[Z],
	decoder RedisZDecoder[Z], batchSize ...int) *RedisZSet[Z]

func (*RedisZSet[Z]) BZPopMin

func (zs *RedisZSet[Z]) BZPopMin(ctx context.Context, timeout time.Duration, key string) ([]Z, error)

BZPopMin 为了体现zset中没有数据,超时返回时的redis.Nil错误,统一返回slice,可以用nil表示没有返回值的情况

func (*RedisZSet[Z]) WithBatchSize

func (zs *RedisZSet[Z]) WithBatchSize(size int) *RedisZSet[Z]

func (*RedisZSet[Z]) ZAdd

func (zs *RedisZSet[Z]) ZAdd(ctx context.Context, key string, vs ...Z) (int64, error)

func (*RedisZSet[Z]) ZAddCall

func (zs *RedisZSet[Z]) ZAddCall(op func(client redis.Cmdable, vals ...redis.Z) (int64, error), vs ...Z) (int64, error)

func (*RedisZSet[Z]) ZAddNX

func (zs *RedisZSet[Z]) ZAddNX(ctx context.Context, key string, vs ...Z) (int64, error)

func (*RedisZSet[Z]) ZAddNXWithEmpty

func (zs *RedisZSet[Z]) ZAddNXWithEmpty(ctx context.Context, key string, emptyValue Z, vs ...Z) (int64, error)

func (*RedisZSet[Z]) ZAddWithEmpty

func (zs *RedisZSet[Z]) ZAddWithEmpty(ctx context.Context, key string, emptyValue Z, vs ...Z) (int64, error)

func (*RedisZSet[Z]) ZCard

func (zs *RedisZSet[Z]) ZCard(ctx context.Context, key string) (int64, error)

func (*RedisZSet[Z]) ZCount

func (zs *RedisZSet[Z]) ZCount(ctx context.Context, key string, min, max string) (int64, error)

func (*RedisZSet[Z]) ZPopMin

func (zs *RedisZSet[Z]) ZPopMin(ctx context.Context, key string, count ...int64) ([]Z, error)

func (*RedisZSet[Z]) ZRangeWithScores

func (zs *RedisZSet[Z]) ZRangeWithScores(ctx context.Context, args *ZArgs) ([]Z, error)

type Z

type Z redis.Z

func (Z) IdAndValue

func (z Z) IdAndValue() (int64, int64, error)

func (Z) IsEmpty

func (z Z) IsEmpty() bool

func (Z) KeyID

func (z Z) KeyID() (tools.ID, error)

func (Z) KeyStr

func (z Z) KeyStr() (string, error)

func (Z) ScoreInt

func (z Z) ScoreInt() int64

func (Z) Z

func (z Z) Z() redis.Z

type ZArgs

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

func NewZArgs added in v0.1.1

func NewZArgs(key string) *ZArgs

func (*ZArgs) ByIndex

func (a *ZArgs) ByIndex() *ZArgs

func (*ZArgs) ByLEX

func (a *ZArgs) ByLEX() *ZArgs

func (*ZArgs) ByScore

func (a *ZArgs) ByScore() *ZArgs

func (*ZArgs) Fw

func (a *ZArgs) Fw() *ZArgs

func (*ZArgs) MaxString

func (a *ZArgs) MaxString() string

func (*ZArgs) MinString

func (a *ZArgs) MinString() string

func (*ZArgs) Paginate

func (a *ZArgs) Paginate(begin, size int64) *ZArgs

func (*ZArgs) Range

func (a *ZArgs) Range(min, max any) *ZArgs

Range min 永远是小值,max 是大值,当REV为true时,区间为 (max, min)

func (*ZArgs) Redis

func (a *ZArgs) Redis() redis.ZRangeArgs

func (*ZArgs) Rev

func (a *ZArgs) Rev() *ZArgs

func (*ZArgs) String

func (a *ZArgs) String() string

func (*ZArgs) WithKey

func (a *ZArgs) WithKey(key string) *ZArgs

type ZB

type ZB struct {
	V        any
	AsScore  bool // true for score range, false for lexicographical range
	Excluded bool
}

ZB boundary for SCORE or LEX range for ZRange

func ZForScore

func ZForScore() *ZB

func (*ZB) Boundary

func (b *ZB) Boundary(isMin bool) string

func (*ZB) Exclude

func (b *ZB) Exclude() *ZB

func (*ZB) ForLex

func (b *ZB) ForLex() *ZB

func (*ZB) ForScore

func (b *ZB) ForScore() *ZB

func (*ZB) Include

func (b *ZB) Include() *ZB

func (*ZB) Infinite

func (b *ZB) Infinite() *ZB

func (*ZB) Max

func (b *ZB) Max() string

func (*ZB) Min

func (b *ZB) Min() string

func (*ZB) Val

func (b *ZB) Val(v any) *ZB

type Zs

type Zs[T any] []redis.Z

func (Zs[T]) Decode

func (zs Zs[T]) Decode(decoder RedisZDecoder[T]) ([]T, error)

func (Zs[T]) Encode

func (zs Zs[T]) Encode(encoder RedisZEncoder[T], ts ...T) (Zs[T], error)

func (Zs[T]) Slice

func (zs Zs[T]) Slice() []redis.Z

Jump to

Keyboard shortcuts

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