README

Redis client for Golang

Build Status PkgGoDev Documentation Chat

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 definded 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

See also

Expand ▾ Collapse ▴

Documentation

Overview

    Package redis implements a Redis client.

    Example (CustomCommand)
    Output:
    
    "" redis: nil
    
    Example (CustomCommand2)
    Output:
    
    "" redis: nil
    
    Example (Instrumentation)
    Output:
    
    starting processing: <ping: >
    finished processing: <ping: PONG>
    

    Index

    Examples

    Constants

    View Source
    const KeepTTL = -1

      KeepTTL is an option for Set command to keep key's existing TTL. 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

          Functions

          func SetLogger

          func SetLogger(logger internal.Logging)

          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) 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) String

              func (cmd *BoolSliceCmd) String() string

              func (*BoolSliceCmd) Val

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

              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
                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
                  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
                    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) BLPop

                    func (c Client) BLPop(ctx context.Context, timeout time.Duration, keys ...string) *StringSliceCmd
                    Example
                    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

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

                      func (Client) BZPopMin

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

                        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

                          func (c Client) ClientID(ctx context.Context) *IntCmd

                          func (Client) ClientKill

                          func (c Client) ClientKill(ctx context.Context, ipPort string) *StatusCmd

                          func (Client) ClientKillByFilter

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

                            ClientKillByFilter is new style syntax, while the ClientKill is old

                            CLIENT KILL <option> [value] ... <option> [value]
                            

                            func (Client) ClientList

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

                            func (Client) ClientPause

                            func (c Client) ClientPause(ctx context.Context, dur time.Duration) *BoolCmd

                            func (Client) ClientUnblock

                            func (c Client) ClientUnblock(ctx context.Context, id int64) *IntCmd

                            func (Client) ClientUnblockWithError

                            func (c Client) ClientUnblockWithError(ctx context.Context, id int64) *IntCmd

                            func (Client) Close

                            func (c Client) Close() error

                              Close closes the client, releasing any open resources.

                              It is rare to Close a Client, as the Client is meant to be long-lived and shared between many goroutines.

                              func (Client) ClusterAddSlots

                              func (c Client) ClusterAddSlots(ctx context.Context, slots ...int) *StatusCmd

                              func (Client) ClusterAddSlotsRange

                              func (c Client) ClusterAddSlotsRange(ctx context.Context, min, max int) *StatusCmd

                              func (Client) ClusterCountFailureReports

                              func (c Client) ClusterCountFailureReports(ctx context.Context, nodeID string) *IntCmd

                              func (Client) ClusterCountKeysInSlot

                              func (c Client) ClusterCountKeysInSlot(ctx context.Context, slot int) *IntCmd

                              func (Client) ClusterDelSlots

                              func (c Client) ClusterDelSlots(ctx context.Context, slots ...int) *StatusCmd

                              func (Client) ClusterDelSlotsRange

                              func (c Client) ClusterDelSlotsRange(ctx context.Context, min, max int) *StatusCmd

                              func (Client) ClusterFailover

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

                              func (Client) ClusterForget

                              func (c Client) ClusterForget(ctx context.Context, nodeID string) *StatusCmd

                              func (Client) ClusterGetKeysInSlot

                              func (c Client) ClusterGetKeysInSlot(ctx context.Context, slot int, count int) *StringSliceCmd

                              func (Client) ClusterInfo

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

                              func (Client) ClusterKeySlot

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

                              func (Client) ClusterMeet

                              func (c Client) ClusterMeet(ctx context.Context, host, port string) *StatusCmd

                              func (Client) ClusterNodes

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

                              func (Client) ClusterReplicate

                              func (c Client) ClusterReplicate(ctx context.Context, nodeID string) *StatusCmd

                              func (Client) ClusterResetHard

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

                              func (Client) ClusterResetSoft

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

                              func (Client) ClusterSaveConfig

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

                              func (Client) ClusterSlaves

                              func (c Client) ClusterSlaves(ctx context.Context, nodeID string) *StringSliceCmd

                              func (Client) ClusterSlots

                              func (c Client) ClusterSlots(ctx context.Context) *ClusterSlotsCmd

                              func (Client) Command

                              func (c Client) Command(ctx context.Context) *CommandsInfoCmd

                              func (Client) ConfigGet

                              func (c Client) ConfigGet(ctx context.Context, parameter string) *SliceCmd

                              func (Client) ConfigResetStat

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

                              func (Client) ConfigRewrite

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

                              func (Client) ConfigSet

                              func (c Client) ConfigSet(ctx context.Context, parameter, value string) *StatusCmd

                              func (*Client) Conn

                              func (c *Client) Conn(ctx context.Context) *Conn

                              func (*Client) Context

                              func (c *Client) Context() context.Context

                              func (Client) DBSize

                              func (c Client) DBSize(ctx context.Context) *IntCmd

                              func (Client) DebugObject

                              func (c Client) DebugObject(ctx context.Context, key string) *StringCmd

                              func (Client) Decr

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

                              func (Client) DecrBy

                              func (c Client) DecrBy(ctx context.Context, key string, decrement int64) *IntCmd

                              func (Client) Del

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

                              func (*Client) Do

                              func (c *Client) Do(ctx context.Context, args ...interface{}) *Cmd

                                Do creates a Cmd from the args and processes the cmd.

                                func (Client) Dump

                                func (c Client) Dump(ctx context.Context, key string) *StringCmd

                                func (Client) Echo

                                func (c Client) Echo(ctx context.Context, message interface{}) *StringCmd

                                func (Client) Eval

                                func (c Client) Eval(ctx context.Context, script string, keys []string, args ...interface{}) *Cmd

                                func (Client) EvalSha

                                func (c Client) EvalSha(ctx context.Context, sha1 string, keys []string, args ...interface{}) *Cmd

                                func (Client) Exists

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

                                func (Client) Expire

                                func (c Client) Expire(ctx context.Context, key string, expiration time.Duration) *BoolCmd

                                func (Client) ExpireAt

                                func (c Client) ExpireAt(ctx context.Context, key string, tm time.Time) *BoolCmd

                                func (Client) FlushAll

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

                                func (Client) FlushAllAsync

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

                                func (Client) FlushDB

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

                                func (Client) FlushDBAsync

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

                                func (Client) GeoAdd

                                func (c Client) GeoAdd(ctx context.Context, key string, geoLocation ...*GeoLocation) *IntCmd

                                func (Client) GeoDist

                                func (c Client) GeoDist(
                                	ctx context.Context, key string, member1, member2, unit string,
                                ) *FloatCmd

                                func (Client) GeoHash

                                func (c Client) GeoHash(ctx context.Context, key string, members ...string) *StringSliceCmd

                                func (Client) GeoPos

                                func (c Client) GeoPos(ctx context.Context, key string, members ...string) *GeoPosCmd

                                func (Client) GeoRadius

                                func (c Client) GeoRadius(
                                	ctx context.Context, key string, longitude, latitude float64, query *GeoRadiusQuery,
                                ) *GeoLocationCmd

                                  GeoRadius is a read-only GEORADIUS_RO command.

                                  func (Client) GeoRadiusByMember

                                  func (c Client) GeoRadiusByMember(
                                  	ctx context.Context, key, member string, query *GeoRadiusQuery,
                                  ) *GeoLocationCmd

                                    GeoRadius is a read-only GEORADIUSBYMEMBER_RO command.

                                    func (Client) GeoRadiusByMemberStore

                                    func (c Client) GeoRadiusByMemberStore(
                                    	ctx context.Context, key, member string, query *GeoRadiusQuery,
                                    ) *IntCmd

                                      GeoRadiusByMemberStore is a writing GEORADIUSBYMEMBER command.

                                      func (Client) GeoRadiusStore

                                      func (c Client) GeoRadiusStore(
                                      	ctx context.Context, key string, longitude, latitude float64, query *GeoRadiusQuery,
                                      ) *IntCmd

                                        GeoRadiusStore is a writing GEORADIUS command.

                                        func (Client) Get

                                        func (c Client) Get(ctx context.Context, key string) *StringCmd

                                          Redis `GET key` command. It returns redis.Nil error when key does not exist.

                                          func (Client) GetBit

                                          func (c Client) GetBit(ctx context.Context, key string, offset int64) *IntCmd

                                          func (Client) GetRange

                                          func (c Client) GetRange(ctx context.Context, key string, start, end int64) *StringCmd

                                          func (Client) GetSet

                                          func (c Client) GetSet(ctx context.Context, key string, value interface{}) *StringCmd

                                          func (Client) HDel

                                          func (c Client) HDel(ctx context.Context, key string, fields ...string) *IntCmd

                                          func (Client) HExists

                                          func (c Client) HExists(ctx context.Context, key, field string) *BoolCmd

                                          func (Client) HGet

                                          func (c Client) HGet(ctx context.Context, key, field string) *StringCmd

                                          func (Client) HGetAll

                                          func (c Client) HGetAll(ctx context.Context, key string) *StringStringMapCmd

                                          func (Client) HIncrBy

                                          func (c Client) HIncrBy(ctx context.Context, key, field string, incr int64) *IntCmd

                                          func (Client) HIncrByFloat

                                          func (c Client) HIncrByFloat(ctx context.Context, key, field string, incr float64) *FloatCmd

                                          func (Client) HKeys

                                          func (c Client) HKeys(ctx context.Context, key string) *StringSliceCmd

                                          func (Client) HLen

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

                                          func (Client) HMGet

                                          func (c Client) HMGet(ctx context.Context, key string, fields ...string) *SliceCmd

                                            HMGet returns the values for the specified fields in the hash stored at key. It returns an interface{} to distinguish between empty string and nil value.

                                            func (Client) HMSet

                                            func (c Client) HMSet(ctx context.Context, key string, values ...interface{}) *BoolCmd

                                              HMSet is a deprecated version of HSet left for compatibility with Redis 3.

                                              func (Client) HScan

                                              func (c Client) HScan(ctx context.Context, key string, cursor uint64, match string, count int64) *ScanCmd

                                              func (Client) HSet

                                              func (c Client) HSet(ctx context.Context, key string, values ...interface{}) *IntCmd

                                                HSet accepts values in following formats:

                                                - HSet("myhash", "key1", "value1", "key2", "value2")
                                                - HSet("myhash", []string{"key1", "value1", "key2", "value2"})
                                                - HSet("myhash", map[string]interface{}{"key1": "value1", "key2": "value2"})
                                                

                                                Note that it requires Redis v4 for multiple field/value pairs support.

                                                func (Client) HSetNX

                                                func (c Client) HSetNX(ctx context.Context, key, field string, value interface{}) *BoolCmd

                                                func (Client) HVals

                                                func (c Client) HVals(ctx context.Context, key string) *StringSliceCmd

                                                func (Client) Incr

                                                func (c Client) Incr(ctx context.Context, key string) *IntCmd
                                                Example
                                                Output:
                                                
                                                1
                                                

                                                func (Client) IncrBy

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

                                                func (Client) IncrByFloat

                                                func (c Client) IncrByFloat(ctx context.Context, key string, value float64) *FloatCmd

                                                func (Client) Info

                                                func (c Client) Info(ctx context.Context, section ...string) *StringCmd

                                                func (Client) Keys

                                                func (c Client) Keys(ctx context.Context, pattern string) *StringSliceCmd

                                                func (Client) LIndex

                                                func (c Client) LIndex(ctx context.Context, key string, index int64) *StringCmd

                                                func (Client) LInsert

                                                func (c Client) LInsert(ctx context.Context, key, op string, pivot, value interface{}) *IntCmd

                                                func (Client) LInsertAfter

                                                func (c Client) LInsertAfter(ctx context.Context, key string, pivot, value interface{}) *IntCmd

                                                func (Client) LInsertBefore

                                                func (c Client) LInsertBefore(ctx context.Context, key string, pivot, value interface{}) *IntCmd

                                                func (Client) LLen

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

                                                func (Client) LPop

                                                func (c Client) LPop(ctx context.Context, key string) *StringCmd

                                                func (Client) LPos</