redis

package module
Version: v8.11.4 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2021 License: BSD-2-Clause Imports: 26 Imported by: 2,319

README

Redis client for Golang

build workflow PkgGoDev Documentation Chat

Other projects you may like:

  • Bun - fast and simple SQL client for PostgreSQL, MySQL, and SQLite.
  • treemux - high-speed, flexible, tree-based HTTP router for Go.

Ecosystem

Features

Installation

go-redis supports 2 last Go versions and requires a Go version with modules support. So make sure to initialize a Go module:

go mod init github.com/my/repo

And then install go-redis/v8 (note v8 in the import; omitting it is a popular mistake):

go get github.com/go-redis/redis/v8

Quickstart

import (
    "context"
    "github.com/go-redis/redis/v8"
)

var ctx = context.Background()

func ExampleClient() {
    rdb := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "", // no password set
        DB:       0,  // use default DB
    })

    err := rdb.Set(ctx, "key", "value", 0).Err()
    if err != nil {
        panic(err)
    }

    val, err := rdb.Get(ctx, "key").Result()
    if err != nil {
        panic(err)
    }
    fmt.Println("key", val)

    val2, err := rdb.Get(ctx, "key2").Result()
    if err == redis.Nil {
        fmt.Println("key2 does not exist")
    } else if err != nil {
        panic(err)
    } else {
        fmt.Println("key2", val2)
    }
    // Output: key value
    // key2 does not exist
}

Look and feel

Some corner cases:

// SET key value EX 10 NX
set, err := rdb.SetNX(ctx, "key", "value", 10*time.Second).Result()

// SET key value keepttl NX
set, err := rdb.SetNX(ctx, "key", "value", redis.KeepTTL).Result()

// SORT list LIMIT 0 2 ASC
vals, err := rdb.Sort(ctx, "list", &redis.Sort{Offset: 0, Count: 2, Order: "ASC"}).Result()

// ZRANGEBYSCORE zset -inf +inf WITHSCORES LIMIT 0 2
vals, err := rdb.ZRangeByScoreWithScores(ctx, "zset", &redis.ZRangeBy{
    Min: "-inf",
    Max: "+inf",
    Offset: 0,
    Count: 2,
}).Result()

// ZINTERSTORE out 2 zset1 zset2 WEIGHTS 2 3 AGGREGATE SUM
vals, err := rdb.ZInterStore(ctx, "out", &redis.ZStore{
    Keys: []string{"zset1", "zset2"},
    Weights: []int64{2, 3}
}).Result()

// EVAL "return {KEYS[1],ARGV[1]}" 1 "key" "hello"
vals, err := rdb.Eval(ctx, "return {KEYS[1],ARGV[1]}", []string{"key"}, "hello").Result()

// custom command
res, err := rdb.Do(ctx, "set", "key", "value").Result()

Run the test

go-redis will start a redis-server and run the test cases.

The paths of redis-server bin file and redis config file are defined in main_test.go:

var (
	redisServerBin, _  = filepath.Abs(filepath.Join("testdata", "redis", "src", "redis-server"))
	redisServerConf, _ = filepath.Abs(filepath.Join("testdata", "redis", "redis.conf"))
)

For local testing, you can change the variables to refer to your local files, or create a soft link to the corresponding folder for redis-server and copy the config file to testdata/redis/:

ln -s /usr/bin/redis-server ./go-redis/testdata/redis/src
cp ./go-redis/testdata/redis.conf ./go-redis/testdata/redis/

Lastly, run:

go test

Contributors

Thanks to all the people who already contributed!

Documentation

Overview

Package redis implements a Redis client.

Example (CustomCommand)
Get := func(ctx context.Context, rdb *redis.Client, key string) *redis.StringCmd {
	cmd := redis.NewStringCmd(ctx, "get", key)
	rdb.Process(ctx, cmd)
	return cmd
}

v, err := Get(ctx, rdb, "key_does_not_exist").Result()
fmt.Printf("%q %s", v, err)
Output:

"" redis: nil
Example (CustomCommand2)
v, err := rdb.Do(ctx, "get", "key_does_not_exist").Text()
fmt.Printf("%q %s", v, err)
Output:

"" redis: nil
Example (Instrumentation)
rdb := redis.NewClient(&redis.Options{
	Addr: ":6379",
})
rdb.AddHook(redisHook{})

rdb.Ping(ctx)
Output:

starting processing: <ping: >
finished processing: <ping: PONG>

Index

Examples

Constants

View Source
const KeepTTL = -1

KeepTTL is a Redis KEEPTTL option to keep existing TTL, it requires your redis-server version >= 6.0, otherwise you will receive an error: (error) ERR syntax error. For example:

rdb.Set(ctx, key, value, redis.KeepTTL)
View Source
const Nil = proto.Nil

Nil reply returned by Redis when key does not exist.

View Source
const TxFailedErr = proto.RedisError("redis: transaction failed")

TxFailedErr transaction redis failed.

Variables

View Source
var ErrClosed = pool.ErrClosed

ErrClosed performs any operation on the closed client will return this error.

Functions

func SetLogger

func SetLogger(logger internal.Logging)

func Version added in v8.11.3

func Version() string

Version is the current release version.

Types

type BitCount

type BitCount struct {
	Start, End int64
}

type BoolCmd

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

func NewBoolCmd

func NewBoolCmd(ctx context.Context, args ...interface{}) *BoolCmd

func NewBoolResult

func NewBoolResult(val bool, err error) *BoolCmd

NewBoolResult returns a BoolCmd initialised with val and err for testing.

func (*BoolCmd) Args

func (cmd *BoolCmd) Args() []interface{}

func (*BoolCmd) Err

func (cmd *BoolCmd) Err() error

func (*BoolCmd) FullName

func (cmd *BoolCmd) FullName() string

func (*BoolCmd) Name

func (cmd *BoolCmd) Name() string

func (*BoolCmd) Result

func (cmd *BoolCmd) Result() (bool, error)

func (*BoolCmd) SetErr

func (cmd *BoolCmd) SetErr(e error)

func (*BoolCmd) SetVal added in v8.11.4

func (cmd *BoolCmd) SetVal(val bool)

func (*BoolCmd) String

func (cmd *BoolCmd) String() string

func (*BoolCmd) Val

func (cmd *BoolCmd) Val() bool

type BoolSliceCmd

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

func NewBoolSliceCmd

func NewBoolSliceCmd(ctx context.Context, args ...interface{}) *BoolSliceCmd

func NewBoolSliceResult

func NewBoolSliceResult(val []bool, err error) *BoolSliceCmd

NewBoolSliceResult returns a BoolSliceCmd initialised with val and err for testing.

func (*BoolSliceCmd) Args

func (cmd *BoolSliceCmd) Args() []interface{}

func (*BoolSliceCmd) Err

func (cmd *BoolSliceCmd) Err() error

func (*BoolSliceCmd) FullName

func (cmd *BoolSliceCmd) FullName() string

func (*BoolSliceCmd) Name

func (cmd *BoolSliceCmd) Name() string

func (*BoolSliceCmd) Result

func (cmd *BoolSliceCmd) Result() ([]bool, error)

func (*BoolSliceCmd) SetErr

func (cmd *BoolSliceCmd) SetErr(e error)

func (*BoolSliceCmd) SetVal added in v8.11.4

func (cmd *BoolSliceCmd) SetVal(val []bool)

func (*BoolSliceCmd) String

func (cmd *BoolSliceCmd) String() string

func (*BoolSliceCmd) Val

func (cmd *BoolSliceCmd) Val() []bool

type ChannelOption added in v8.9.0

type ChannelOption func(c *channel)

func WithChannelHealthCheckInterval added in v8.9.0

func WithChannelHealthCheckInterval(d time.Duration) ChannelOption

WithChannelHealthCheckInterval specifies the health check interval. PubSub will ping Redis Server if it does not receive any messages within the interval. To disable health check, use zero interval.

The default is 3 seconds.

func WithChannelSendTimeout added in v8.9.0

func WithChannelSendTimeout(d time.Duration) ChannelOption

WithChannelSendTimeout specifies the channel send timeout after which the message is dropped.

The default is 60 seconds.

func WithChannelSize added in v8.9.0

func WithChannelSize(size int) ChannelOption

WithChannelSize specifies the Go chan size that is used to buffer incoming messages.

The default is 100 messages.

type Client

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

Client is a Redis client representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines.

Example
err := rdb.Set(ctx, "key", "value", 0).Err()
if err != nil {
	panic(err)
}

val, err := rdb.Get(ctx, "key").Result()
if err != nil {
	panic(err)
}
fmt.Println("key", val)

val2, err := rdb.Get(ctx, "missing_key").Result()
if err == redis.Nil {
	fmt.Println("missing_key does not exist")
} else if err != nil {
	panic(err)
} else {
	fmt.Println("missing_key", val2)
}
Output:

key value
missing_key does not exist

func NewClient

func NewClient(opt *Options) *Client

NewClient returns a client to the Redis Server specified by Options.

Example
rdb := redis.NewClient(&redis.Options{
	Addr:     "localhost:6379", // use default Addr
	Password: "",               // no password set
	DB:       0,                // use default DB
})

pong, err := rdb.Ping(ctx).Result()
fmt.Println(pong, err)
Output:

PONG <nil>

func NewFailoverClient

func NewFailoverClient(failoverOpt *FailoverOptions) *Client

NewFailoverClient returns a Redis client that uses Redis Sentinel for automatic failover. It's safe for concurrent use by multiple goroutines.

Example
// See http://redis.io/topics/sentinel for instructions how to
// setup Redis Sentinel.
rdb := redis.NewFailoverClient(&redis.FailoverOptions{
	MasterName:    "master",
	SentinelAddrs: []string{":26379"},
})
rdb.Ping(ctx)
Output:

func (*Client) AddHook

func (hs *Client) AddHook(hook Hook)

func (Client) Append

func (c Client) Append(ctx context.Context, key, value string) *IntCmd

func (Client) BLMove added in v8.11.4

func (c Client) BLMove(
	ctx context.Context, source, destination, srcpos, destpos string, timeout time.Duration,
) *StringCmd

func (Client) BLPop

func (c Client) BLPop(ctx context.Context, timeout time.Duration, keys ...string) *StringSliceCmd
Example
if err := rdb.RPush(ctx, "queue", "message").Err(); err != nil {
	panic(err)
}

// use `rdb.BLPop(0, "queue")` for infinite waiting time
result, err := rdb.BLPop(ctx, 1*time.Second, "queue").Result()
if err != nil {
	panic(err)
}

fmt.Println(result[0], result[1])
Output:

queue message

func (Client) BRPop

func (c Client) BRPop(ctx context.Context, timeout time.Duration, keys ...string) *StringSliceCmd

func (Client) BRPopLPush

func (c Client) BRPopLPush(ctx context.Context, source, destination string, timeout time.Duration) *StringCmd

func (Client) BZPopMax

func (c Client) BZPopMax(ctx context.Context, timeout time.Duration, keys ...string) *ZWithKeyCmd

BZPopMax Redis `BZPOPMAX key [key ...] timeout` command.

func (Client) BZPopMin

func (c Client) BZPopMin(ctx context.Context, timeout time.Duration, keys ...string) *ZWithKeyCmd

BZPopMin Redis `BZPOPMIN key [key ...] timeout` command.

func (Client) BgRewriteAOF

func (c Client) BgRewriteAOF(ctx context.Context) *StatusCmd

func (Client) BgSave

func (c Client) BgSave(ctx context.Context) *StatusCmd

func (Client) BitCount

func (c Client) BitCount(ctx context.Context, key string, bitCount *BitCount) *IntCmd

func (Client) BitField

func (c Client) BitField(ctx context.Context, key string, args ...interface{}) *IntSliceCmd

func (Client) BitOpAnd

func (c Client) BitOpAnd(ctx context.Context, destKey string, keys ...string) *IntCmd

func (Client) BitOpNot

func (c Client) BitOpNot(ctx context.Context, destKey string, key string) *IntCmd

func (Client) BitOpOr

func (c Client) BitOpOr(ctx context.Context, destKey string, keys ...string) *IntCmd

func (Client) BitOpXor

func (c Client) BitOpXor(ctx context.Context, destKey string, keys ...string) *IntCmd

func (Client) BitPos

func (c Client) BitPos(ctx context.Context, key string, bit int64, pos ...int64) *IntCmd

func (Client) ClientGetName

func (c Client) ClientGetName(ctx context.Context) *StringCmd

ClientGetName returns the name of the connection.

func (Client) ClientID