import "github.com/go-redis/redis"
Package redis implements a Redis client.
Code:
Get := func(redisdb *redis.Client, key string) *redis.StringCmd {
cmd := redis.NewStringCmd("get", key)
redisdb.Process(cmd)
return cmd
}
v, err := Get(redisdb, "key_does_not_exist").Result()
fmt.Printf("%q %s", v, err)
Output:
"" redis: nil
Code:
v, err := redisdb.Do("get", "key_does_not_exist").String()
fmt.Printf("%q %s", v, err)
Output:
"" redis: nil
Code:
redisdb := redis.NewClient(&redis.Options{
Addr: ":6379",
})
redisdb.WrapProcess(func(old func(cmd redis.Cmder) error) func(cmd redis.Cmder) error {
return func(cmd redis.Cmder) error {
fmt.Printf("starting processing: <%s>\n", cmd)
err := old(cmd)
fmt.Printf("finished processing: <%s>\n", cmd)
return err
}
})
redisdb.Ping()
Output:
starting processing: <ping: > finished processing: <ping: PONG>
cluster.go cluster_commands.go command.go commands.go doc.go iterator.go options.go pipeline.go pubsub.go redis.go result.go ring.go script.go sentinel.go tx.go universal.go
Nil reply Redis returns when key does not exist.
const TxFailedErr = proto.RedisError("redis: transaction failed")
TxFailedErr transaction redis failed.
type BoolCmd struct {
// contains filtered or unexported fields
}NewBoolResult returns a BoolCmd initialised with val and err for testing
func (cmd *BoolCmd) Args() []interface{}type BoolSliceCmd struct {
// contains filtered or unexported fields
}func NewBoolSliceCmd(args ...interface{}) *BoolSliceCmdfunc NewBoolSliceResult(val []bool, err error) *BoolSliceCmd
NewBoolSliceResult returns a BoolSliceCmd initialised with val and err for testing
func (cmd *BoolSliceCmd) Args() []interface{}func (cmd *BoolSliceCmd) Result() ([]bool, error)
func (cmd *BoolSliceCmd) String() string
func (cmd *BoolSliceCmd) Val() []bool
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.
Code:
err := redisdb.Set("key", "value", 0).Err()
if err != nil {
panic(err)
}
val, err := redisdb.Get("key").Result()
if err != nil {
panic(err)
}
fmt.Println("key", val)
val2, err := redisdb.Get("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
NewClient returns a client to the Redis Server specified by Options.
Code:
redisdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
pong, err := redisdb.Ping().Result()
fmt.Println(pong, err)
Output:
PONG <nil>
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.
Code:
// See http://redis.io/topics/sentinel for instructions how to
// setup Redis Sentinel.
redisdb := redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: "master",
SentinelAddrs: []string{":26379"},
})
redisdb.Ping()
func (c *Client) BLPop(timeout time.Duration, keys ...string) *StringSliceCmd
Code:
if err := redisdb.RPush("queue", "message").Err(); err != nil {
panic(err)
}
// use `redisdb.BLPop(0, "queue")` for infinite waiting time
result, err := redisdb.BLPop(1*time.Second, "queue").Result()
if err != nil {
panic(err)
}
fmt.Println(result[0], result[1])
Output:
queue message
func (c *Client) BRPop(timeout time.Duration, keys ...string) *StringSliceCmd
ClientGetName returns the name of the connection.
ClientKillByFilter is new style synx, while the ClientKill is old CLIENT KILL <option> [value] ... <option> [value]
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 (c *Client) ClusterSlaves(nodeID string) *StringSliceCmd
func (c *Client) ClusterSlots() *ClusterSlotsCmd
func (c *Client) Command() *CommandsInfoCmd
Deperecated. Use DBSize instead.
Do creates a Cmd from the args and processes the cmd.
Deprecated. Use FlushDB instead.
func (c *Client) GeoAdd(key string, geoLocation ...*GeoLocation) *IntCmd
func (c *Client) GeoHash(key string, members ...string) *StringSliceCmd
func (c *Client) GeoRadius(key string, longitude, latitude float64, query *GeoRadiusQuery) *GeoLocationCmd
func (c *Client) GeoRadiusByMember(key, member string, query *GeoRadiusQuery) *GeoLocationCmd
func (c *Client) GeoRadiusByMemberRO(key, member string, query *GeoRadiusQuery) *GeoLocationCmd
func (c *Client) GeoRadiusRO(key string, longitude, latitude float64, query *GeoRadiusQuery) *GeoLocationCmd
Redis `GET key` command. It returns redis.Nil error when key does not exist.
func (c *Client) HGetAll(key string) *StringStringMapCmd
func (c *Client) HKeys(key string) *StringSliceCmd
func (c *Client) HVals(key string) *StringSliceCmd
Code:
result, err := redisdb.Incr("counter").Result()
if err != nil {
panic(err)
}
fmt.Println(result)
Output:
1
func (c *Client) Keys(pattern string) *StringSliceCmd
func (c *Client) LRange(key string, start, stop int64) *StringSliceCmd
func (c *Client) ObjectIdleTime(key string) *DurationCmd
Options returns read-only Options that were used to create the client.
PSubscribe subscribes the client to the given patterns. Patterns can be omitted to create empty subscription.
func (c *Client) PTTL(key string) *DurationCmd
Code:
pipe := redisdb.Pipeline()
incr := pipe.Incr("pipeline_counter")
pipe.Expire("pipeline_counter", time.Hour)
// Execute
//
// INCR pipeline_counter
// EXPIRE pipeline_counts 3600
//
// using one redisdb-server roundtrip.
_, err := pipe.Exec()
fmt.Println(incr.Val(), err)
Output:
1 <nil>
Code:
var incr *redis.IntCmd
_, err := redisdb.Pipelined(func(pipe redis.Pipeliner) error {
incr = pipe.Incr("pipelined_counter")
pipe.Expire("pipelined_counter", time.Hour)
return nil
})
fmt.Println(incr.Val(), err)
Output:
1 <nil>
PoolStats returns connection pool stats.
func (c *Client) PubSubChannels(pattern string) *StringSliceCmd
func (c *Client) PubSubNumSub(channels ...string) *StringIntMapCmd
Publish posts the message to the channel.
func (c *Client) SDiff(keys ...string) *StringSliceCmd
func (c *Client) SInter(keys ...string) *StringSliceCmd
func (c *Client) SMembers(key string) *StringSliceCmd
Redis `SMEMBERS key` command output as a slice
func (c *Client) SMembersMap(key string) *StringStructMapCmd
Redis `SMEMBERS key` command output as a map
Redis `SPOP key` command.
func (c *Client) SPopN(key string, count int64) *StringSliceCmd
Redis `SPOP key count` command.
Redis `SRANDMEMBER key` command.
func (c *Client) SRandMemberN(key string, count int64) *StringSliceCmd
Redis `SRANDMEMBER key count` command.
func (c *Client) SUnion(keys ...string) *StringSliceCmd
Code:
redisdb.FlushDB()
for i := 0; i < 33; i++ {
err := redisdb.Set(fmt.Sprintf("key%d", i), "value", 0).Err()
if err != nil {
panic(err)
}
}
var cursor uint64
var n int
for {
var keys []string
var err error
keys, cursor, err = redisdb.Scan(cursor, "key*", 10).Result()
if err != nil {
panic(err)
}
n += len(keys)
if cursor == 0 {
break
}
}
fmt.Printf("found %d keys\n", n)
Output:
found 33 keys
func (c *Client) ScriptExists(hashes ...string) *BoolSliceCmd
Redis `SET key value [expiration]` command.
Use expiration for `SETEX`-like behavior. Zero expiration means the key has no expiration time.
Code:
// Last argument is expiration. Zero means the key has no // expiration time. err := redisdb.Set("key", "value", 0).Err() if err != nil { panic(err) } // key2 will expire in an hour. err = redisdb.Set("key2", "value", time.Hour).Err() if err != nil { panic(err) }
Redis `SET key value [expiration] NX` command.
Zero expiration means the key has no expiration time.
Redis `SET key value [expiration] XX` command.
Zero expiration means the key has no expiration time.
func (c *Client) SlowLog()
func (c *Client) Sort(key string, sort *Sort) *StringSliceCmd
Subscribe subscribes the client to the specified channels. Channels can be omitted to create empty subscription.
func (c *Client) Sync()
func (c *Client) TTL(key string) *DurationCmd
TxPipeline acts like Pipeline, but wraps queued commands with MULTI/EXEC.
Code:
pipe := redisdb.TxPipeline()
incr := pipe.Incr("tx_pipeline_counter")
pipe.Expire("tx_pipeline_counter", time.Hour)
// Execute
//
// MULTI
// INCR pipeline_counter
// EXPIRE pipeline_counts 3600
// EXEC
//
// using one redisdb-server roundtrip.
_, err := pipe.Exec()
fmt.Println(incr.Val(), err)
Output:
1 <nil>
Code:
var incr *redis.IntCmd
_, err := redisdb.TxPipelined(func(pipe redis.Pipeliner) error {
incr = pipe.Incr("tx_pipelined_counter")
pipe.Expire("tx_pipelined_counter", time.Hour)
return nil
})
fmt.Println(incr.Val(), err)
Output:
1 <nil>
Watch prepares a transcaction and marks the keys to be watched for conditional execution if there are any keys.
The transaction is automatically closed when the fn exits.
Code:
var incr func(string) error
// Transactionally increments key using GET and SET commands.
incr = func(key string) error {
err := redisdb.Watch(func(tx *redis.Tx) error {
n, err := tx.Get(key).Int64()
if err != nil && err != redis.Nil {
return err
}
_, err = tx.Pipelined(func(pipe redis.Pipeliner) error {
pipe.Set(key, strconv.FormatInt(n+1, 10), 0)
return nil
})
return err
}, key)
if err == redis.TxFailedErr {
return incr(key)
}
return err
}
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
err := incr("counter3")
if err != nil {
panic(err)
}
}()
}
wg.Wait()
n, err := redisdb.Get("counter3").Int64()
fmt.Println(n, err)
Output:
100 <nil>
WrapProcess wraps function that processes Redis commands.
func (c *Client) WrapProcessPipeline(
fn func(oldProcess func([]Cmder) error) func([]Cmder) error,
)func (c *Client) XClaim(a *XClaimArgs) *XMessageSliceCmd
func (c *Client) XClaimJustID(a *XClaimArgs) *StringSliceCmd
func (c *Client) XPending(stream, group string) *XPendingCmd
func (c *Client) XPendingExt(a *XPendingExtArgs) *XPendingExtCmd
func (c *Client) XRange(stream, start, stop string) *XMessageSliceCmd
func (c *Client) XRangeN(stream, start, stop string, count int64) *XMessageSliceCmd
func (c *Client) XRead(a *XReadArgs) *XStreamSliceCmd
func (c *Client) XReadGroup(a *XReadGroupArgs) *XStreamSliceCmd
func (c *Client) XReadStreams(streams ...string) *XStreamSliceCmd
func (c *Client) XRevRange(stream, start, stop string) *XMessageSliceCmd
func (c *Client) XRevRangeN(stream, start, stop string, count int64) *XMessageSliceCmd
Redis `ZADD key score member [score member ...]` command.
Redis `ZADD key CH score member [score member ...]` command.
Redis `ZADD key NX score member [score member ...]` command.
Redis `ZADD key NX CH score member [score member ...]` command.
Redis `ZADD key XX score member [score member ...]` command.
Redis `ZADD key XX CH score member [score member ...]` command.
Redis `ZADD key INCR score member` command.
Redis `ZADD key NX INCR score member` command.
Redis `ZADD key XX INCR score member` command.
func (c *Client) ZRange(key string, start, stop int64) *StringSliceCmd
func (c *Client) ZRangeByLex(key string, opt ZRangeBy) *StringSliceCmd
func (c *Client) ZRangeByScore(key string, opt ZRangeBy) *StringSliceCmd
func (c *Client) ZRevRange(key string, start, stop int64) *StringSliceCmd
func (c *Client) ZRevRangeByLex(key string, opt ZRangeBy) *StringSliceCmd
func (c *Client) ZRevRangeByScore(key string, opt ZRangeBy) *StringSliceCmd
type ClusterClient struct {
// contains filtered or unexported fields
}ClusterClient is a Redis Cluster client representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines.
func NewClusterClient(opt *ClusterOptions) *ClusterClient
NewClusterClient returns a Redis Cluster client as described in http://redis.io/topics/cluster-spec.
Code:
// See http://redis.io/topics/cluster-tutorial for instructions
// how to setup Redis Cluster.
redisdb := redis.NewClusterClient(&redis.ClusterOptions{
Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
})
redisdb.Ping()
Following example creates a cluster from 2 master nodes and 2 slave nodes without using cluster mode or Redis Sentinel.
Code:
// clusterSlots returns cluster slots information. // It can use service like ZooKeeper to maintain configuration information // and Cluster.ReloadState to manually trigger state reloading. clusterSlots := func() ([]redis.ClusterSlot, error) { slots := []redis.ClusterSlot{ // First node with 1 master and 1 slave. { Start: 0, End: 8191, Nodes: []redis.ClusterNode{{ Addr: ":7000", // master }, { Addr: ":8000", // 1st slave }}, }, // Second node with 1 master and 1 slave. { Start: 8192, End: 16383, Nodes: []redis.ClusterNode{{ Addr: ":7001", // master }, { Addr: ":8001", // 1st slave }}, }, } return slots, nil } redisdb := redis.NewClusterClient(&redis.ClusterOptions{ ClusterSlots: clusterSlots, RouteRandomly: true, }) redisdb.Ping() // ReloadState reloads cluster state. It calls ClusterSlots func // to get cluster slots information. err := redisdb.ReloadState() if err != nil { panic(err) }
func (c *ClusterClient) BLPop(timeout time.Duration, keys ...string) *StringSliceCmd
func (c *ClusterClient) BRPop(timeout time.Duration, keys ...string) *StringSliceCmd
ClientGetName returns the name of the connection.
ClientKillByFilter is new style synx, while the ClientKill is old CLIENT KILL <option> [value] ... <option> [value]
func (c *ClusterClient) Close() error
Close closes the cluster client, releasing any open resources.
It is rare to Close a ClusterClient, as the ClusterClient is meant to be long-lived and shared between many goroutines.
func (c *ClusterClient) ClusterSlaves(nodeID string) *StringSliceCmd
func (c *ClusterClient) ClusterSlots() *ClusterSlotsCmd
func (c *ClusterClient) Command() *CommandsInfoCmd
func (c *ClusterClient) Context() context.Context
func (c *ClusterClient) DBSize() *IntCmd
Deperecated. Use DBSize instead.
func (c *ClusterClient) Do(args ...interface{}) *Cmd
Do creates a Cmd from the args and processes the cmd.
Deprecated. Use FlushDB instead.
func (c *ClusterClient) ForEachMaster(fn func(client *Client) error) error
ForEachMaster concurrently calls the fn on each master node in the cluster. It returns the first error if any.
func (c *ClusterClient) ForEachNode(fn func(client *Client) error) error
ForEachNode concurrently calls the fn on each known node in the cluster. It returns the first error if any.
func (c *ClusterClient) ForEachSlave(fn func(client *Client) error) error
ForEachSlave concurrently calls the fn on each slave node in the cluster. It returns the first error if any.
func (c *ClusterClient) GeoAdd(key string, geoLocation ...*GeoLocation) *IntCmd
func (c *ClusterClient) GeoHash(key string, members ...string) *StringSliceCmd
func (c *ClusterClient) GeoRadius(key string, longitude, latitude float64, query *GeoRadiusQuery) *GeoLocationCmd
func (c *ClusterClient) GeoRadiusByMember(key, member string, query *GeoRadiusQuery) *GeoLocationCmd
func (c *ClusterClient) GeoRadiusByMemberRO(key, member string, query *GeoRadiusQuery) *GeoLocationCmd
func (c *ClusterClient) GeoRadiusRO(key string, longitude, latitude float64, query *GeoRadiusQuery) *GeoLocationCmd
Redis `GET key` command. It returns redis.Nil error when key does not exist.
func (c *ClusterClient) HGetAll(key string) *StringStringMapCmd
func (c *ClusterClient) HKeys(key string) *StringSliceCmd
func (c *ClusterClient) HVals(key string) *StringSliceCmd
func (c *ClusterClient) Keys(pattern string) *StringSliceCmd
func (c *ClusterClient) LRange(key string, start, stop int64) *StringSliceCmd
func (c *ClusterClient) Migrate(host, port, key string, db int64, timeout time.Duration) *StatusCmd
func (c *ClusterClient) ObjectIdleTime(key string) *DurationCmd
func (c *ClusterClient) Options() *ClusterOptions
Options returns read-only Options that were used to create the client.
func (c *ClusterClient) PSubscribe(channels ...string) *PubSub
PSubscribe subscribes the client to the given patterns. Patterns can be omitted to create empty subscription.
func (c *ClusterClient) PTTL(key string) *DurationCmd
func (c *ClusterClient) Pipeline() Pipeliner
func (c *ClusterClient) PoolStats() *PoolStats
PoolStats returns accumulated connection pool stats.
func (c *ClusterClient) Process(cmd Cmder) error
func (c *ClusterClient) PubSubChannels(pattern string) *StringSliceCmd
func (c *ClusterClient) PubSubNumSub(channels ...string) *StringIntMapCmd
Publish posts the message to the channel.
func (c *ClusterClient) ReloadState() error
ReloadState reloads cluster state. It calls ClusterSlots func to get cluster slots information.
func (c *ClusterClient) SDiff(keys ...string) *StringSliceCmd
func (c *ClusterClient) SInter(keys ...string) *StringSliceCmd
func (c *ClusterClient) SMembers(key string) *StringSliceCmd
Redis `SMEMBERS key` command output as a slice
func (c *ClusterClient) SMembersMap(key string) *StringStructMapCmd
Redis `SMEMBERS key` command output as a map
Redis `SPOP key` command.
func (c *ClusterClient) SPopN(key string, count int64) *StringSliceCmd
Redis `SPOP key count` command.
Redis `SRANDMEMBER key` command.
func (c *ClusterClient) SRandMemberN(key string, count int64) *StringSliceCmd
Redis `SRANDMEMBER key count` command.
func (c *ClusterClient) SUnion(keys ...string) *StringSliceCmd
func (c *ClusterClient) ScriptExists(hashes ...string) *BoolSliceCmd
Redis `SET key value [expiration]` command.
Use expiration for `SETEX`-like behavior. Zero expiration means the key has no expiration time.
Redis `SET key value [expiration] NX` command.
Zero expiration means the key has no expiration time.
Redis `SET key value [expiration] XX` command.
Zero expiration means the key has no expiration time.
func (c *ClusterClient) SlowLog()
func (c *ClusterClient) Sort(key string, sort *Sort) *StringSliceCmd
func (c *ClusterClient) Subscribe(channels ...string) *PubSub
Subscribe subscribes the client to the specified channels. Channels can be omitted to create empty subscription.
func (c *ClusterClient) Sync()
func (c *ClusterClient) TTL(key string) *DurationCmd
func (c *ClusterClient) TxPipeline() Pipeliner
TxPipeline acts like Pipeline, but wraps queued commands with MULTI/EXEC.
func (c *ClusterClient) WithContext(ctx context.Context) *ClusterClient
func (c *ClusterClient) WrapProcessPipeline( fn func(oldProcess func([]Cmder) error) func([]Cmder) error, )
func (c *ClusterClient) XClaim(a *XClaimArgs) *XMessageSliceCmd
func (c *ClusterClient) XClaimJustID(a *XClaimArgs) *StringSliceCmd
func (c *ClusterClient) XPending(stream, group string) *XPendingCmd
func (c *ClusterClient) XPendingExt(a *XPendingExtArgs) *XPendingExtCmd
func (c *ClusterClient) XRange(stream, start, stop string) *XMessageSliceCmd
func (c *ClusterClient) XRangeN(stream, start, stop string, count int64) *XMessageSliceCmd
func (c *ClusterClient) XRead(a *XReadArgs) *XStreamSliceCmd
func (c *ClusterClient) XReadGroup(a *XReadGroupArgs) *XStreamSliceCmd
func (c *ClusterClient) XReadStreams(streams ...string) *XStreamSliceCmd
func (c *ClusterClient) XRevRange(stream, start, stop string) *XMessageSliceCmd
func (c *ClusterClient) XRevRangeN(stream, start, stop string, count int64) *XMessageSliceCmd
Redis `ZADD key score member [score member ...]` command.
Redis `ZADD key CH score member [score member ...]` command.
Redis `ZADD key NX score member [score member ...]` command.
Redis `ZADD key NX CH score member [score member ...]` command.
Redis `ZADD key XX score member [score member ...]` command.
Redis `ZADD key XX CH score member [score member ...]` command.
Redis `ZADD key INCR score member` command.
Redis `ZADD key NX INCR score member` command.
Redis `ZADD key XX INCR score member` command.
func (c *ClusterClient) ZRange(key string, start, stop int64) *StringSliceCmd
func (c *ClusterClient) ZRangeByLex(key string, opt ZRangeBy) *StringSliceCmd
func (c *ClusterClient) ZRangeByScore(key string, opt ZRangeBy) *StringSliceCmd
func (c *ClusterClient) ZRevRange(key string, start, stop int64) *StringSliceCmd
func (c *ClusterClient) ZRevRangeByLex(key string, opt ZRangeBy) *StringSliceCmd
func (c *ClusterClient) ZRevRangeByScore(key string, opt ZRangeBy) *StringSliceCmd
type ClusterOptions struct {
// A seed list of host:port addresses of cluster nodes.
Addrs []string
// The maximum number of retries before giving up. Command is retried
// on network errors and MOVED/ASK redirects.
// Default is 8 retries.
MaxRedirects int
// Enables read-only commands on slave nodes.
ReadOnly bool
// Allows routing read-only commands to the closest master or slave node.
// It automatically enables ReadOnly.
RouteByLatency bool
// Allows routing read-only commands to the random master or slave node.
// It automatically enables ReadOnly.
RouteRandomly bool
// Optional function that returns cluster slots information.
// It is useful to manually create cluster of standalone Redis servers
// and load-balance read/write operations between master and slaves.
// It can use service like ZooKeeper to maintain configuration information
// and Cluster.ReloadState to manually trigger state reloading.
ClusterSlots func() ([]ClusterSlot, error)
OnConnect func(*Conn) error
Password string
MaxRetries int
MinRetryBackoff time.Duration
MaxRetryBackoff time.Duration
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
// PoolSize applies per cluster node and not for the whole cluster.
PoolSize int
MinIdleConns int
MaxConnAge time.Duration
PoolTimeout time.Duration
IdleTimeout time.Duration
IdleCheckFrequency time.Duration
TLSConfig *tls.Config
}ClusterOptions are used to configure a cluster client and should be passed to NewClusterClient.
type ClusterSlot struct {
Start int
End int
Nodes []ClusterNode
}type ClusterSlotsCmd struct {
// contains filtered or unexported fields
}func NewClusterSlotsCmd(args ...interface{}) *ClusterSlotsCmdfunc NewClusterSlotsCmdResult(val []ClusterSlot, err error) *ClusterSlotsCmd
NewClusterSlotsCmdResult returns a ClusterSlotsCmd initialised with val and err for testing
func (cmd *ClusterSlotsCmd) Args() []interface{}func (cmd *ClusterSlotsCmd) Result() ([]ClusterSlot, error)
func (cmd *ClusterSlotsCmd) String() string
func (cmd *ClusterSlotsCmd) Val() []ClusterSlot
type Cmd struct {
// contains filtered or unexported fields
}NewCmdResult returns a Cmd initialised with val and err for testing
func (cmd *Cmd) Args() []interface{}type Cmdable interface {
Pipeline() Pipeliner
Pipelined(fn func(Pipeliner) error) ([]Cmder, error)
TxPipelined(fn func(Pipeliner) error) ([]Cmder, error)
TxPipeline() Pipeliner
Command() *CommandsInfoCmd
ClientGetName() *StringCmd
Echo(message interface{}) *StringCmd
Ping() *StatusCmd
Quit() *StatusCmd
Del(keys ...string) *IntCmd
Unlink(keys ...string) *IntCmd
Dump(key string) *StringCmd
Exists(keys ...string) *IntCmd
Expire(key string, expiration time.Duration) *BoolCmd
ExpireAt(key string, tm time.Time) *BoolCmd
Keys(pattern string) *StringSliceCmd
Migrate(host, port, key string, db int64, timeout time.Duration) *StatusCmd
Move(key string, db int64) *BoolCmd
ObjectRefCount(key string) *IntCmd
ObjectEncoding(key string) *StringCmd
ObjectIdleTime(key string) *DurationCmd
Persist(key string) *BoolCmd
PExpire(key string, expiration time.Duration) *BoolCmd
PExpireAt(key string, tm time.Time) *BoolCmd
PTTL(key string) *DurationCmd
RandomKey() *StringCmd
Rename(key, newkey string) *StatusCmd
RenameNX(key, newkey string) *BoolCmd
Restore(key string, ttl time.Duration, value string) *StatusCmd
RestoreReplace(key string, ttl time.Duration, value string) *StatusCmd
Sort(key string, sort *Sort) *StringSliceCmd
SortStore(key, store string, sort *Sort) *IntCmd
SortInterfaces(key string, sort *Sort) *SliceCmd
Touch(keys ...string) *IntCmd
TTL(key string) *DurationCmd
Type(key string) *StatusCmd
Scan(cursor uint64, match string, count int64) *ScanCmd
SScan(key string, cursor uint64, match string, count int64) *ScanCmd
HScan(key string, cursor uint64, match string, count int64) *ScanCmd
ZScan(key string, cursor uint64, match string, count int64) *ScanCmd
Append(key, value string) *IntCmd
BitCount(key string, bitCount *BitCount) *IntCmd
BitOpAnd(destKey string, keys ...string) *IntCmd
BitOpOr(destKey string, keys ...string) *IntCmd
BitOpXor(destKey string, keys ...string) *IntCmd
BitOpNot(destKey string, key string) *IntCmd
BitPos(key string, bit int64, pos ...int64) *IntCmd
Decr(key string) *IntCmd
DecrBy(key string, decrement int64) *IntCmd
Get(key string) *StringCmd
GetBit(key string, offset int64) *IntCmd
GetRange(key string, start, end int64) *StringCmd
GetSet(key string, value interface{}) *StringCmd
Incr(key string) *IntCmd
IncrBy(key string, value int64) *IntCmd
IncrByFloat(key string, value float64) *FloatCmd
MGet(keys ...string) *SliceCmd
MSet(pairs ...interface{}) *StatusCmd
MSetNX(pairs ...interface{}) *BoolCmd
Set(key string, value interface{}, expiration time.Duration) *StatusCmd
SetBit(key string, offset int64, value int) *IntCmd
SetNX(key string, value interface{}, expiration time.Duration) *BoolCmd
SetXX(key string, value interface{}, expiration time.Duration) *BoolCmd
SetRange(key string, offset int64, value string) *IntCmd
StrLen(key string) *IntCmd
HDel(key string, fields ...string) *IntCmd
HExists(key, field string) *BoolCmd
HGet(key, field string) *StringCmd
HGetAll(key string) *StringStringMapCmd
HIncrBy(key, field string, incr int64) *IntCmd
HIncrByFloat(key, field string, incr float64) *FloatCmd
HKeys(key string) *StringSliceCmd
HLen(key string) *IntCmd
HMGet(key string, fields ...string) *SliceCmd
HMSet(key string, fields map[string]interface{}) *StatusCmd
HSet(key, field string, value interface{}) *BoolCmd
HSetNX(key, field string, value interface{}) *BoolCmd
HVals(key string) *StringSliceCmd
BLPop(timeout time.Duration, keys ...string) *StringSliceCmd
BRPop(timeout time.Duration, keys ...string) *StringSliceCmd
BRPopLPush(source, destination string, timeout time.Duration) *StringCmd
LIndex(key string, index int64) *StringCmd
LInsert(key, op string, pivot, value interface{}) *IntCmd
LInsertBefore(key string, pivot, value interface{}) *IntCmd
LInsertAfter(key string, pivot, value interface{}) *IntCmd
LLen(key string) *IntCmd
LPop(key string) *StringCmd
LPush(key string, values ...interface{}) *IntCmd
LPushX(key string, value interface{}) *IntCmd
LRange(key string, start, stop int64) *StringSliceCmd
LRem(key string, count int64, value interface{}) *IntCmd
LSet(key string, index int64, value interface{}) *StatusCmd
LTrim(key string, start, stop int64) *StatusCmd
RPop(key string) *StringCmd
RPopLPush(source, destination string) *StringCmd
RPush(key string, values ...interface{}) *IntCmd
RPushX(key string, value interface{}) *IntCmd
SAdd(key string, members ...interface{}) *IntCmd
SCard(key string) *IntCmd
SDiff(keys ...string) *StringSliceCmd
SDiffStore(destination string, keys ...string) *IntCmd
SInter(keys ...string) *StringSliceCmd
SInterStore(destination string, keys ...string) *IntCmd
SIsMember(key string, member interface{}) *BoolCmd
SMembers(key string) *StringSliceCmd
SMembersMap(key string) *StringStructMapCmd
SMove(source, destination string, member interface{}) *BoolCmd
SPop(key string) *StringCmd
SPopN(key string, count int64) *StringSliceCmd
SRandMember(key string) *StringCmd
SRandMemberN(key string, count int64) *StringSliceCmd
SRem(key string, members ...interface{}) *IntCmd
SUnion(keys ...string) *StringSliceCmd
SUnionStore(destination string, keys ...string) *IntCmd
XAdd(a *XAddArgs) *StringCmd
XLen(stream string) *IntCmd
XRange(stream, start, stop string) *XMessageSliceCmd
XRangeN(stream, start, stop string, count int64) *XMessageSliceCmd
XRevRange(stream string, start, stop string) *XMessageSliceCmd
XRevRangeN(stream string, start, stop string, count int64) *XMessageSliceCmd
XRead(a *XReadArgs) *XStreamSliceCmd
XReadStreams(streams ...string) *XStreamSliceCmd
XGroupCreate(stream, group, start string) *StatusCmd
XGroupSetID(stream, group, start string) *StatusCmd
XGroupDestroy(stream, group string) *IntCmd
XGroupDelConsumer(stream, group, consumer string) *IntCmd
XReadGroup(a *XReadGroupArgs) *XStreamSliceCmd
XAck(stream, group string, ids ...string) *IntCmd
XPending(stream, group string) *XPendingCmd
XPendingExt(a *XPendingExtArgs) *XPendingExtCmd
XClaim(a *XClaimArgs) *XMessageSliceCmd
XClaimJustID(a *XClaimArgs) *StringSliceCmd
XTrim(key string, maxLen int64) *IntCmd
XTrimApprox(key string, maxLen int64) *IntCmd
ZAdd(key string, members ...Z) *IntCmd
ZAddNX(key string, members ...Z) *IntCmd
ZAddXX(key string, members ...Z) *IntCmd
ZAddCh(key string, members ...Z) *IntCmd
ZAddNXCh(key string, members ...Z) *IntCmd
ZAddXXCh(key string, members ...Z) *IntCmd
ZIncr(key string, member Z) *FloatCmd
ZIncrNX(key string, member Z) *FloatCmd
ZIncrXX(key string, member Z) *FloatCmd
ZCard(key string) *IntCmd
ZCount(key, min, max string) *IntCmd
ZLexCount(key, min, max string) *IntCmd
ZIncrBy(key string, increment float64, member string) *FloatCmd
ZInterStore(destination string, store ZStore, keys ...string) *IntCmd
ZPopMax(key string, count ...int64) *ZSliceCmd
ZPopMin(key string, count ...int64) *ZSliceCmd
ZRange(key string, start, stop int64) *StringSliceCmd
ZRangeWithScores(key string, start, stop int64) *ZSliceCmd
ZRangeByScore(key string, opt ZRangeBy) *StringSliceCmd
ZRangeByLex(key string, opt ZRangeBy) *StringSliceCmd
ZRangeByScoreWithScores(key string, opt ZRangeBy) *ZSliceCmd
ZRank(key, member string) *IntCmd
ZRem(key string, members ...interface{}) *IntCmd
ZRemRangeByRank(key string, start, stop int64) *IntCmd
ZRemRangeByScore(key, min, max string) *IntCmd
ZRemRangeByLex(key, min, max string) *IntCmd
ZRevRange(key string, start, stop int64) *StringSliceCmd
ZRevRangeWithScores(key string, start, stop int64) *ZSliceCmd
ZRevRangeByScore(key string, opt ZRangeBy) *StringSliceCmd
ZRevRangeByLex(key string, opt ZRangeBy) *StringSliceCmd
ZRevRangeByScoreWithScores(key string, opt ZRangeBy) *ZSliceCmd
ZRevRank(key, member string) *IntCmd
ZScore(key, member string) *FloatCmd
ZUnionStore(dest string, store ZStore, keys ...string) *IntCmd
PFAdd(key string, els ...interface{}) *IntCmd
PFCount(keys ...string) *IntCmd
PFMerge(dest string, keys ...string) *StatusCmd
BgRewriteAOF() *StatusCmd
BgSave() *StatusCmd
ClientKill(ipPort string) *StatusCmd
ClientKillByFilter(keys ...string) *IntCmd
ClientList() *StringCmd
ClientPause(dur time.Duration) *BoolCmd
ConfigGet(parameter string) *SliceCmd
ConfigResetStat() *StatusCmd
ConfigSet(parameter, value string) *StatusCmd
ConfigRewrite() *StatusCmd
DBSize() *IntCmd
FlushAll() *StatusCmd
FlushAllAsync() *StatusCmd
FlushDB() *StatusCmd
FlushDBAsync() *StatusCmd
Info(section ...string) *StringCmd
LastSave() *IntCmd
Save() *StatusCmd
Shutdown() *StatusCmd
ShutdownSave() *StatusCmd
ShutdownNoSave() *StatusCmd
SlaveOf(host, port string) *StatusCmd
Time() *TimeCmd
Eval(script string, keys []string, args ...interface{}) *Cmd
EvalSha(sha1 string, keys []string, args ...interface{}) *Cmd
ScriptExists(hashes ...string) *BoolSliceCmd
ScriptFlush() *StatusCmd
ScriptKill() *StatusCmd
ScriptLoad(script string) *StringCmd
DebugObject(key string) *StringCmd
Publish(channel string, message interface{}) *IntCmd
PubSubChannels(pattern string) *StringSliceCmd
PubSubNumSub(channels ...string) *StringIntMapCmd
PubSubNumPat() *IntCmd
ClusterSlots() *ClusterSlotsCmd
ClusterNodes() *StringCmd
ClusterMeet(host, port string) *StatusCmd
ClusterForget(nodeID string) *StatusCmd
ClusterReplicate(nodeID string) *StatusCmd
ClusterResetSoft() *StatusCmd
ClusterResetHard() *StatusCmd
ClusterInfo() *StringCmd
ClusterKeySlot(key string) *IntCmd
ClusterCountFailureReports(nodeID string) *IntCmd
ClusterCountKeysInSlot(slot int) *IntCmd
ClusterDelSlots(slots ...int) *StatusCmd
ClusterDelSlotsRange(min, max int) *StatusCmd
ClusterSaveConfig() *StatusCmd
ClusterSlaves(nodeID string) *StringSliceCmd
ClusterFailover() *StatusCmd
ClusterAddSlots(slots ...int) *StatusCmd
ClusterAddSlotsRange(min, max int) *StatusCmd
GeoAdd(key string, geoLocation ...*GeoLocation) *IntCmd
GeoPos(key string, members ...string) *GeoPosCmd
GeoRadius(key string, longitude, latitude float64, query *GeoRadiusQuery) *GeoLocationCmd
GeoRadiusRO(key string, longitude, latitude float64, query *GeoRadiusQuery) *GeoLocationCmd
GeoRadiusByMember(key, member string, query *GeoRadiusQuery) *GeoLocationCmd
GeoRadiusByMemberRO(key, member string, query *GeoRadiusQuery) *GeoLocationCmd
GeoDist(key string, member1, member2, unit string) *FloatCmd
GeoHash(key string, members ...string) *StringSliceCmd
ReadOnly() *StatusCmd
ReadWrite() *StatusCmd
MemoryUsage(key string, samples ...int) *IntCmd
}type Cmder interface {
Name() string
Args() []interface{}
Err() error
// contains filtered or unexported methods
}type CommandInfo struct {
Name string
Arity int8
Flags []string
FirstKeyPos int8
LastKeyPos int8
StepCount int8
ReadOnly bool
}type CommandsInfoCmd struct {
// contains filtered or unexported fields
}func NewCommandsInfoCmd(args ...interface{}) *CommandsInfoCmdfunc NewCommandsInfoCmdResult(val map[string]*CommandInfo, err error) *CommandsInfoCmd
NewCommandsInfoCmdResult returns a CommandsInfoCmd initialised with val and err for testing
func (cmd *CommandsInfoCmd) Args() []interface{}func (cmd *CommandsInfoCmd) Result() (map[string]*CommandInfo, error)
func (cmd *CommandsInfoCmd) String() string
func (cmd *CommandsInfoCmd) Val() map[string]*CommandInfo
type Conn struct {
// contains filtered or unexported fields
}Conn is like Client, but its pool contains single connection.
ClientSetName assigns a name to the connection.
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.
Do creates a Cmd from the args and processes the cmd.
TxPipeline acts like Pipeline, but wraps queued commands with MULTI/EXEC.
WrapProcess wraps function that processes Redis commands.
type DurationCmd struct {
// contains filtered or unexported fields
}func NewDurationCmd(precision time.Duration, args ...interface{}) *DurationCmd
func NewDurationResult(val time.Duration, err error) *DurationCmd
NewDurationResult returns a DurationCmd initialised with val and err for testing
func (cmd *DurationCmd) Args() []interface{}func (cmd *DurationCmd) Result() (time.Duration, error)
func (cmd *DurationCmd) String() string
func (cmd *DurationCmd) Val() time.Duration
type FailoverOptions struct {
// The master name.
MasterName string
// A seed list of host:port addresses of sentinel nodes.
SentinelAddrs []string
OnConnect func(*Conn) error
Password string
DB int
MaxRetries int
MinRetryBackoff time.Duration
MaxRetryBackoff time.Duration
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
PoolSize int
MinIdleConns int
MaxConnAge time.Duration
PoolTimeout time.Duration
IdleTimeout time.Duration
IdleCheckFrequency time.Duration
TLSConfig *tls.Config
}FailoverOptions are used to configure a failover client and should be passed to NewFailoverClient.
type FloatCmd struct {
// contains filtered or unexported fields
}NewFloatResult returns a FloatCmd initialised with val and err for testing
func (cmd *FloatCmd) Args() []interface{}GeoLocation is used with GeoAdd to add geospatial location.
type GeoLocationCmd struct {
// contains filtered or unexported fields
}func NewGeoLocationCmd(q *GeoRadiusQuery, args ...interface{}) *GeoLocationCmd
func NewGeoLocationCmdResult(val []GeoLocation, err error) *GeoLocationCmd
NewGeoLocationCmdResult returns a GeoLocationCmd initialised with val and err for testing
func (cmd *GeoLocationCmd) Args() []interface{}func (cmd *GeoLocationCmd) Result() ([]GeoLocation, error)
func (cmd *GeoLocationCmd) String() string
func (cmd *GeoLocationCmd) Val() []GeoLocation
type GeoPosCmd struct {
// contains filtered or unexported fields
}func (cmd *GeoPosCmd) Args() []interface{}type GeoRadiusQuery struct {
Radius float64
// Can be m, km, ft, or mi. Default is km.
Unit string
WithCoord bool
WithDist bool
WithGeoHash bool
Count int
// Can be ASC or DESC. Default is no sort order.
Sort string
Store string
StoreDist string
}GeoRadiusQuery is used with GeoRadius to query geospatial index.
type Hash consistenthash.Hash
Hash is type of hash function used in consistent hash.
type IntCmd struct {
// contains filtered or unexported fields
}NewIntResult returns an IntCmd initialised with val and err for testing
func (cmd *IntCmd) Args() []interface{}Message received as result of a PUBLISH command issued by another client.
type Options struct {
// The network type, either tcp or unix.
// Default is tcp.
Network string
// host:port address.
Addr string
// Dialer creates new network connection and has priority over
// Network and Addr options.
Dialer func() (net.Conn, error)
// Hook that is called when new connection is established.
OnConnect func(*Conn) error
// Optional password. Must match the password specified in the
// requirepass server configuration option.
Password string
// Database to be selected after connecting to the server.
DB int
// Maximum number of retries before giving up.
// Default is to not retry failed commands.
MaxRetries int
// Minimum backoff between each retry.
// Default is 8 milliseconds; -1 disables backoff.
MinRetryBackoff time.Duration
// Maximum backoff between each retry.
// Default is 512 milliseconds; -1 disables backoff.
MaxRetryBackoff time.Duration
// Dial timeout for establishing new connections.
// Default is 5 seconds.
DialTimeout time.Duration
// Timeout for socket reads. If reached, commands will fail
// with a timeout instead of blocking. Use value -1 for no timeout and 0 for default.
// Default is 3 seconds.
ReadTimeout time.Duration
// Timeout for socket writes. If reached, commands will fail
// with a timeout instead of blocking.
// Default is ReadTimeout.
WriteTimeout time.Duration
// Maximum number of socket connections.
// Default is 10 connections per every CPU as reported by runtime.NumCPU.
PoolSize int
// Minimum number of idle connections which is useful when establishing
// new connection is slow.
MinIdleConns int
// Connection age at which client retires (closes) the connection.
// Default is to not close aged connections.
MaxConnAge time.Duration
// Amount of time client waits for connection if all connections
// are busy before returning an error.
// Default is ReadTimeout + 1 second.
PoolTimeout time.Duration
// Amount of time after which client closes idle connections.
// Should be less than server's timeout.
// Default is 5 minutes. -1 disables idle timeout check.
IdleTimeout time.Duration
// Frequency of idle checks made by idle connections reaper.
// Default is 1 minute. -1 disables idle connections reaper,
// but idle connections are still discarded by the client
// if IdleTimeout is set.
IdleCheckFrequency time.Duration
// TLS Config to use. When set TLS will be negotiated.
TLSConfig *tls.Config
// contains filtered or unexported fields
}ParseURL parses an URL into Options that can be used to connect to Redis.
Code:
opt, err := redis.ParseURL("redis://:qwerty@localhost:6379/1")
if err != nil {
panic(err)
}
fmt.Println("addr is", opt.Addr)
fmt.Println("db is", opt.DB)
fmt.Println("password is", opt.Password)
// Create client as usually.
_ = redis.NewClient(opt)
Output:
addr is localhost:6379 db is 1 password is qwerty
type Pipeline struct {
// contains filtered or unexported fields
}Pipeline implements pipelining as described in http://redis.io/topics/pipelining. It's safe for concurrent use by multiple goroutines.
Code:
redisdb := redis.NewClient(&redis.Options{
Addr: ":6379",
})
redisdb.WrapProcessPipeline(func(old func([]redis.Cmder) error) func([]redis.Cmder) error {
return func(cmds []redis.Cmder) error {
fmt.Printf("pipeline starting processing: %v\n", cmds)
err := old(cmds)
fmt.Printf("pipeline finished processing: %v\n", cmds)
return err
}
})
redisdb.Pipelined(func(pipe redis.Pipeliner) error {
pipe.Ping()
pipe.Ping()
return nil
})
Output:
pipeline starting processing: [ping: ping: ] pipeline finished processing: [ping: PONG ping: PONG]
ClientSetName assigns a name to the connection.
Close closes the pipeline, releasing any open resources.
Discard resets the pipeline and discards queued commands.
Exec executes all previously queued commands using one client-server roundtrip.
Exec always returns list of commands and error of the first failed command if any.
Process queues the cmd for later execution.
type Pipeliner interface {
StatefulCmdable
Process(cmd Cmder) error
Close() error
Discard() error
Exec() ([]Cmder, error)
}Pong received as result of a PING command issued by another client.
type PubSub struct {
// contains filtered or unexported fields
}PubSub implements Pub/Sub commands bas described in http://redis.io/topics/pubsub. Message receiving is NOT safe for concurrent use by multiple goroutines.
PubSub automatically reconnects to Redis Server and resubscribes to the channels in case of network errors.
Code:
pubsub := redisdb.Subscribe("mychannel1")
// Wait for confirmation that subscription is created before publishing anything.
_, err := pubsub.Receive()
if err != nil {
panic(err)
}
// Go channel which receives messages.
ch := pubsub.Channel()
// Publish a message.
err = redisdb.Publish("mychannel1", "hello").Err()
if err != nil {
panic(err)
}
time.AfterFunc(time.Second, func() {
// When pubsub is closed channel is closed too.
_ = pubsub.Close()
})
// Consume messages.
for msg := range ch {
fmt.Println(msg.Channel, msg.Payload)
}
Output:
mychannel1 hello
Channel returns a Go channel for concurrently receiving messages. It periodically sends Ping messages to test connection health. The channel is closed with PubSub. Receive* APIs can not be used after channel is created.
PSubscribe the client to the given patterns. It returns empty subscription if there are no patterns.
PUnsubscribe the client from the given patterns, or from all of them if none is given.
Receive returns a message as a Subscription, Message, Pong or error. See PubSub example for details. This is low-level API and in most cases Channel should be used instead.
Code:
pubsub := redisdb.Subscribe("mychannel2")
defer pubsub.Close()
for i := 0; i < 2; i++ {
// ReceiveTimeout is a low level API. Use ReceiveMessage instead.
msgi, err := pubsub.ReceiveTimeout(time.Second)
if err != nil {
break
}
switch msg := msgi.(type) {
case *redis.Subscription:
fmt.Println("subscribed to", msg.Channel)
_, err := redisdb.Publish("mychannel2", "hello").Result()
if err != nil {
panic(err)
}
case *redis.Message:
fmt.Println("received", msg.Payload, "from", msg.Channel)
default:
panic("unreached")
}
}
// sent message to 1 redisdb
// received hello from mychannel2
ReceiveMessage returns a Message or error ignoring Subscription and Pong messages. This is low-level API and in most cases Channel should be used instead.
ReceiveTimeout acts like Receive but returns an error if message is not received in time. This is low-level API and in most cases Channel should be used instead.
Subscribe the client to the specified channels. It returns empty subscription if there are no channels.
Unsubscribe the client from the given channels, or from all of them if none is given.
type Ring struct {
// contains filtered or unexported fields
}Ring is a Redis client that uses constistent hashing to distribute keys across multiple Redis servers (shards). It's safe for concurrent use by multiple goroutines.
Ring monitors the state of each shard and removes dead shards from the ring. When shard comes online it is added back to the ring. This gives you maximum availability and partition tolerance, but no consistency between different shards or even clients. Each client uses shards that are available to the client and does not do any coordination when shard state is changed.
Ring should be used when you need multiple Redis servers for caching and can tolerate losing data when one of the servers dies. Otherwise you should use Redis Cluster.
func NewRing(opt *RingOptions) *Ring
Code:
redisdb := redis.NewRing(&redis.RingOptions{
Addrs: map[string]string{
"shard1": ":7000",
"shard2": ":7001",
"shard3": ":7002",
},
})
redisdb.Ping()
func (c *Ring) BLPop(timeout time.Duration, keys ...string) *StringSliceCmd
func (c *Ring) BRPop(timeout time.Duration, keys ...string) *StringSliceCmd
ClientGetName returns the name of the connection.
ClientKillByFilter is new style synx, while the ClientKill is old CLIENT KILL <option> [value] ... <option> [value]
Close closes the ring client, releasing any open resources.
It is rare to Close a Ring, as the Ring is meant to be long-lived and shared between many goroutines.
func (c *Ring) ClusterSlaves(nodeID string) *StringSliceCmd
func (c *Ring) ClusterSlots() *ClusterSlotsCmd
func (c *Ring) Command() *CommandsInfoCmd
Deperecated. Use DBSize instead.
Do creates a Cmd from the args and processes the cmd.
Deprecated. Use FlushDB instead.
ForEachShard concurrently calls the fn on each live shard in the ring. It returns the first error if any.
func (c *Ring) GeoAdd(key string, geoLocation ...*GeoLocation) *IntCmd
func (c *Ring) GeoHash(key string, members ...string) *StringSliceCmd
func (c *Ring) GeoRadius(key string, longitude, latitude float64, query *GeoRadiusQuery) *GeoLocationCmd
func (c *Ring) GeoRadiusByMember(key, member string, query *GeoRadiusQuery) *GeoLocationCmd
func (c *Ring) GeoRadiusByMemberRO(key, member string, query *GeoRadiusQuery) *GeoLocationCmd
func (c *Ring) GeoRadiusRO(key string, longitude, latitude float64, query *GeoRadiusQuery) *GeoLocationCmd
Redis `GET key` command. It returns redis.Nil error when key does not exist.
func (c *Ring) HGetAll(key string) *StringStringMapCmd
func (c *Ring) HKeys(key string) *StringSliceCmd
func (c *Ring) HVals(key string) *StringSliceCmd
func (c *Ring) Keys(pattern string) *StringSliceCmd
func (c *Ring) LRange(key string, start, stop int64) *StringSliceCmd
Len returns the current number of shards in the ring.
func (c *Ring) ObjectIdleTime(key string) *DurationCmd
func (c *Ring) Options() *RingOptions
Options returns read-only Options that were used to create the client.
PSubscribe subscribes the client to the given patterns.
func (c *Ring) PTTL(key string) *DurationCmd
PoolStats returns accumulated connection pool stats.
func (c *Ring) PubSubChannels(pattern string) *StringSliceCmd
func (c *Ring) PubSubNumSub(channels ...string) *StringIntMapCmd
Publish posts the message to the channel.
func (c *Ring) SDiff(keys ...string) *StringSliceCmd
func (c *Ring) SInter(keys ...string) *StringSliceCmd
func (c *Ring) SMembers(key string) *StringSliceCmd
Redis `SMEMBERS key` command output as a slice
func (c *Ring) SMembersMap(key string) *StringStructMapCmd
Redis `SMEMBERS key` command output as a map
Redis `SPOP key` command.
func (c *Ring) SPopN(key string, count int64) *StringSliceCmd
Redis `SPOP key count` command.
Redis `SRANDMEMBER key` command.
func (c *Ring) SRandMemberN(key string, count int64) *StringSliceCmd
Redis `SRANDMEMBER key count` command.
func (c *Ring) SUnion(keys ...string) *StringSliceCmd
func (c *Ring) ScriptExists(hashes ...string) *BoolSliceCmd
Redis `SET key value [expiration]` command.
Use expiration for `SETEX`-like behavior. Zero expiration means the key has no expiration time.
Redis `SET key value [expiration] NX` command.
Zero expiration means the key has no expiration time.
Redis `SET key value [expiration] XX` command.
Zero expiration means the key has no expiration time.
func (c *Ring) SlowLog()
func (c *Ring) Sort(key string, sort *Sort) *StringSliceCmd
Subscribe subscribes the client to the specified channels.
func (c *Ring) Sync()
func (c *Ring) TTL(key string) *DurationCmd
func (c *Ring) XClaim(a *XClaimArgs) *XMessageSliceCmd
func (c *Ring) XClaimJustID(a *XClaimArgs) *StringSliceCmd
func (c *Ring) XPending(stream, group string) *XPendingCmd
func (c *Ring) XPendingExt(a *XPendingExtArgs) *XPendingExtCmd
func (c *Ring) XRange(stream, start, stop string) *XMessageSliceCmd
func (c *Ring) XRangeN(stream, start, stop string, count int64) *XMessageSliceCmd
func (c *Ring) XRead(a *XReadArgs) *XStreamSliceCmd
func (c *Ring) XReadGroup(a *XReadGroupArgs) *XStreamSliceCmd
func (c *Ring) XReadStreams(streams ...string) *XStreamSliceCmd
func (c *Ring) XRevRange(stream, start, stop string) *XMessageSliceCmd
func (c *Ring) XRevRangeN(stream, start, stop string, count int64) *XMessageSliceCmd
Redis `ZADD key score member [score member ...]` command.
Redis `ZADD key CH score member [score member ...]` command.
Redis `ZADD key NX score member [score member ...]` command.
Redis `ZADD key NX CH score member [score member ...]` command.
Redis `ZADD key XX score member [score member ...]` command.
Redis `ZADD key XX CH score member [score member ...]` command.
Redis `ZADD key INCR score member` command.
Redis `ZADD key NX INCR score member` command.
Redis `ZADD key XX INCR score member` command.
func (c *Ring) ZRange(key string, start, stop int64) *StringSliceCmd
func (c *Ring) ZRangeByLex(key string, opt ZRangeBy) *StringSliceCmd
func (c *Ring) ZRangeByScore(key string, opt ZRangeBy) *StringSliceCmd
func (c *Ring) ZRevRange(key string, start, stop int64) *StringSliceCmd
func (c *Ring) ZRevRangeByLex(key string, opt ZRangeBy) *StringSliceCmd
func (c *Ring) ZRevRangeByScore(key string, opt ZRangeBy) *StringSliceCmd
type RingOptions struct {
// Map of name => host:port addresses of ring shards.
Addrs map[string]string
// Frequency of PING commands sent to check shards availability.
// Shard is considered down after 3 subsequent failed checks.
HeartbeatFrequency time.Duration
// Hash function used in consistent hash.
// Default is crc32.ChecksumIEEE.
Hash Hash
// Number of replicas in consistent hash.
// Default is 100 replicas.
//
// Higher number of replicas will provide less deviation, that is keys will be
// distributed to nodes more evenly.
//
// Following is deviation for common nreplicas:
// --------------------------------------------------------
// | nreplicas | standard error | 99% confidence interval |
// | 10 | 0.3152 | (0.37, 1.98) |
// | 100 | 0.0997 | (0.76, 1.28) |
// | 1000 | 0.0316 | (0.92, 1.09) |
// --------------------------------------------------------
//
// See https://arxiv.org/abs/1406.2294 for reference
HashReplicas int
OnConnect func(*Conn) error
DB int
Password string
MaxRetries int
MinRetryBackoff time.Duration
MaxRetryBackoff time.Duration
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
PoolSize int
MinIdleConns int
MaxConnAge time.Duration
PoolTimeout time.Duration
IdleTimeout time.Duration
IdleCheckFrequency time.Duration
}RingOptions are used to configure a ring client and should be passed to NewRing.
type ScanCmd struct {
// contains filtered or unexported fields
}NewScanCmdResult returns a ScanCmd initialised with val and err for testing
func (cmd *ScanCmd) Args() []interface{}func (cmd *ScanCmd) Iterator() *ScanIterator
Iterator creates a new ScanIterator.
Code:
iter := redisdb.Scan(0, "", 0).Iterator()
for iter.Next() {
fmt.Println(iter.Val())
}
if err := iter.Err(); err != nil {
panic(err)
}
type ScanIterator struct {
// contains filtered or unexported fields
}ScanIterator is used to incrementally iterate over a collection of elements. It's safe for concurrent use by multiple goroutines.
Code:
iter := redisdb.Scan(0, "", 0).Iterator()
for iter.Next() {
fmt.Println(iter.Val())
}
if err := iter.Err(); err != nil {
panic(err)
}
func (it *ScanIterator) Err() error
Err returns the last iterator error, if any.
func (it *ScanIterator) Next() bool
Next advances the cursor and returns true if more values can be read.
func (it *ScanIterator) Val() string
Val returns the key/field at the current cursor position.
type Script struct {
// contains filtered or unexported fields
}Code:
IncrByXX := redis.NewScript(`
if redis.call("GET", KEYS[1]) ~= false then
return redis.call("INCRBY", KEYS[1], ARGV[1])
end
return false
`)
n, err := IncrByXX.Run(redisdb, []string{"xx_counter"}, 2).Result()
fmt.Println(n, err)
err = redisdb.Set("xx_counter", "40", 0).Err()
if err != nil {
panic(err)
}
n, err = IncrByXX.Run(redisdb, []string{"xx_counter"}, 2).Result()
fmt.Println(n, err)
Output:
<nil> redis: nil 42 <nil>
func (s *Script) Exists(c scripter) *BoolSliceCmd
Run optimistically uses EVALSHA to run the script. If script does not exist it is retried using EVAL.
type SentinelClient struct {
// contains filtered or unexported fields
}func NewSentinelClient(opt *Options) *SentinelClient
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.
Do creates a Cmd from the args and processes the cmd.
func (c *SentinelClient) GetMasterAddrByName(name string) *StringSliceCmd
func (c *SentinelClient) PSubscribe(channels ...string) *PubSub
PSubscribe subscribes the client to the given patterns. Patterns can be omitted to create empty subscription.
func (c *SentinelClient) Sentinels(name string) *SliceCmd
func (c *SentinelClient) Subscribe(channels ...string) *PubSub
Subscribe subscribes the client to the specified channels. Channels can be omitted to create empty subscription.
func (c *SentinelClient) WrapProcess(
fn func(oldProcess func(cmd Cmder) error) func(cmd Cmder) error,
)WrapProcess wraps function that processes Redis commands.
func (c *SentinelClient) WrapProcessPipeline(
fn func(oldProcess func([]Cmder) error) func([]Cmder) error,
)type SliceCmd struct {
// contains filtered or unexported fields
}NewSliceResult returns a SliceCmd initialised with val and err for testing
func (cmd *SliceCmd) Args() []interface{}type StatefulCmdable interface {
Cmdable
Auth(password string) *StatusCmd
Select(index int) *StatusCmd
SwapDB(index1, index2 int) *StatusCmd
ClientSetName(name string) *BoolCmd
}type StatusCmd struct {
// contains filtered or unexported fields
}NewStatusResult returns a StatusCmd initialised with val and err for testing
func (cmd *StatusCmd) Args() []interface{}type StringCmd struct {
// contains filtered or unexported fields
}NewStringResult returns a StringCmd initialised with val and err for testing
func (cmd *StringCmd) Args() []interface{}type StringIntMapCmd struct {
// contains filtered or unexported fields
}func NewStringIntMapCmd(args ...interface{}) *StringIntMapCmdfunc NewStringIntMapCmdResult(val map[string]int64, err error) *StringIntMapCmd
NewStringIntMapCmdResult returns a StringIntMapCmd initialised with val and err for testing
func (cmd *StringIntMapCmd) Args() []interface{}func (cmd *StringIntMapCmd) Result() (map[string]int64, error)
func (cmd *StringIntMapCmd) String() string
func (cmd *StringIntMapCmd) Val() map[string]int64
type StringSliceCmd struct {
// contains filtered or unexported fields
}func NewStringSliceCmd(args ...interface{}) *StringSliceCmdfunc NewStringSliceResult(val []string, err error) *StringSliceCmd
NewStringSliceResult returns a StringSliceCmd initialised with val and err for testing
func (cmd *StringSliceCmd) Args() []interface{}func (cmd *StringSliceCmd) Result() ([]string, error)
func (cmd *StringSliceCmd) ScanSlice(container interface{}) error
func (cmd *StringSliceCmd) String() string
func (cmd *StringSliceCmd) Val() []string
type StringStringMapCmd struct {
// contains filtered or unexported fields
}func NewStringStringMapCmd(args ...interface{}) *StringStringMapCmdfunc NewStringStringMapResult(val map[string]string, err error) *StringStringMapCmd
NewStringStringMapResult returns a StringStringMapCmd initialised with val and err for testing
func (cmd *StringStringMapCmd) Args() []interface{}func (cmd *StringStringMapCmd) Result() (map[string]string, error)
func (cmd *StringStringMapCmd) String() string
func (cmd *StringStringMapCmd) Val() map[string]string
type StringStructMapCmd struct {
// contains filtered or unexported fields
}func NewStringStructMapCmd(args ...interface{}) *StringStructMapCmdfunc (cmd *StringStructMapCmd) Args() []interface{}func (cmd *StringStructMapCmd) Result() (map[string]struct{}, error)
func (cmd *StringStructMapCmd) String() string
func (cmd *StringStructMapCmd) Val() map[string]struct{}
type Subscription struct {
// Can be "subscribe", "unsubscribe", "psubscribe" or "punsubscribe".
Kind string
// Channel name we have subscribed to.
Channel string
// Number of channels we are currently subscribed to.
Count int
}Subscription received after a successful subscription to channel.
func (m *Subscription) String() string
type TimeCmd struct {
// contains filtered or unexported fields
}func (cmd *TimeCmd) Args() []interface{}type Tx struct {
// contains filtered or unexported fields
}Tx implements Redis transactions as described in http://redis.io/topics/transactions. It's NOT safe for concurrent use by multiple goroutines, because Exec resets list of watched keys. If you don't need WATCH it is better to use Pipeline.
ClientSetName assigns a name to the connection.
Close closes the transaction, releasing any open resources.
Do creates a Cmd from the args and processes the cmd.
Pipeline creates a new pipeline. It is more convenient to use Pipelined.
Pipelined executes commands queued in the fn in a transaction.
When using WATCH, EXEC will execute commands only if the watched keys were not modified, allowing for a check-and-set mechanism.
Exec always returns list of commands. If transaction fails TxFailedErr is returned. Otherwise Exec returns an error of the first failed command or nil.
TxPipeline is an alias for Pipeline.
TxPipelined is an alias for Pipelined.
Unwatch flushes all the previously watched keys for a transaction.
Watch marks the keys to be watched for conditional execution of a transaction.
WrapProcess wraps function that processes Redis commands.
type UniversalClient interface {
Cmdable
Watch(fn func(*Tx) error, keys ...string) error
Process(cmd Cmder) error
WrapProcess(fn func(oldProcess func(cmd Cmder) error) func(cmd Cmder) error)
Subscribe(channels ...string) *PubSub
PSubscribe(channels ...string) *PubSub
Close() error
}UniversalClient is an abstract client which - based on the provided options - can connect to either clusters, or sentinel-backed failover instances or simple single-instance servers. This can be useful for testing cluster-specific applications locally.
func NewUniversalClient(opts *UniversalOptions) UniversalClient
NewUniversalClient returns a new multi client. The type of client returned depends on the following three conditions:
1. if a MasterName is passed a sentinel-backed FailoverClient will be returned 2. if the number of Addrs is two or more, a ClusterClient will be returned 3. otherwise, a single-node redis Client will be returned.
Code:
redisdb := redis.NewUniversalClient(&redis.UniversalOptions{
Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
})
defer redisdb.Close()
redisdb.Ping()
Code:
redisdb := redis.NewUniversalClient(&redis.UniversalOptions{
MasterName: "master",
Addrs: []string{":26379"},
})
defer redisdb.Close()
redisdb.Ping()
Code:
redisdb := redis.NewUniversalClient(&redis.UniversalOptions{
Addrs: []string{":6379"},
})
defer redisdb.Close()
redisdb.Ping()
type UniversalOptions struct {
// Either a single address or a seed list of host:port addresses
// of cluster/sentinel nodes.
Addrs []string
// Database to be selected after connecting to the server.
// Only single-node and failover clients.
DB int
OnConnect func(*Conn) error
Password string
MaxRetries int
MinRetryBackoff time.Duration
MaxRetryBackoff time.Duration
DialTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
PoolSize int
MinIdleConns int
MaxConnAge time.Duration
PoolTimeout time.Duration
IdleTimeout time.Duration
IdleCheckFrequency time.Duration
TLSConfig *tls.Config
MaxRedirects int
ReadOnly bool
RouteByLatency bool
RouteRandomly bool
// The sentinel master name.
// Only failover clients.
MasterName string
}UniversalOptions information is required by UniversalClient to establish connections.
type XAddArgs struct {
Stream string
MaxLen int64 // MAXLEN N
MaxLenApprox int64 // MAXLEN ~ N
ID string
Values map[string]interface{}
}type XClaimArgs struct {
Stream string
Group string
Consumer string
MinIdle time.Duration
Messages []string
}type XMessageSliceCmd struct {
// contains filtered or unexported fields
}func NewXMessageSliceCmd(args ...interface{}) *XMessageSliceCmdfunc (cmd *XMessageSliceCmd) Args() []interface{}func (cmd *XMessageSliceCmd) Result() ([]XMessage, error)
func (cmd *XMessageSliceCmd) String() string
func (cmd *XMessageSliceCmd) Val() []XMessage
type XPendingCmd struct {
// contains filtered or unexported fields
}func NewXPendingCmd(args ...interface{}) *XPendingCmdfunc (cmd *XPendingCmd) Args() []interface{}func (cmd *XPendingCmd) Result() (*XPending, error)
func (cmd *XPendingCmd) String() string
func (cmd *XPendingCmd) Val() *XPending
type XPendingExtArgs struct {
Stream string
Group string
Start string
End string
Count int64
Consumer string
}type XPendingExtCmd struct {
// contains filtered or unexported fields
}func NewXPendingExtCmd(args ...interface{}) *XPendingExtCmdfunc (cmd *XPendingExtCmd) Args() []interface{}func (cmd *XPendingExtCmd) Result() ([]XPendingExt, error)
func (cmd *XPendingExtCmd) String() string
func (cmd *XPendingExtCmd) Val() []XPendingExt
type XReadGroupArgs struct {
Group string
Consumer string
Streams []string
Count int64
Block time.Duration
}type XStreamSliceCmd struct {
// contains filtered or unexported fields
}func NewXStreamSliceCmd(args ...interface{}) *XStreamSliceCmdfunc (cmd *XStreamSliceCmd) Args() []interface{}func (cmd *XStreamSliceCmd) Result() ([]XStream, error)
func (cmd *XStreamSliceCmd) String() string
func (cmd *XStreamSliceCmd) Val() []XStream
Z represents sorted set member.
type ZSliceCmd struct {
// contains filtered or unexported fields
}NewZSliceCmdResult returns a ZSliceCmd initialised with val and err for testing
func (cmd *ZSliceCmd) Args() []interface{}ZStore is used as an arg to ZInterStore and ZUnionStore.
| Path | Synopsis |
|---|---|
| internal | |
| internal/consistenthash | Package consistenthash provides an implementation of a ring hash. |
| internal/hashtag | |
| internal/pool | |
| internal/proto | |
| internal/singleflight | Package singleflight provides a duplicate function call suppression mechanism. |
| internal/util |
Package redis imports 26 packages (graph) and is imported by 298 packages. Updated 2018-10-14. Refresh now. Tools for package owners.