ErrNil indicates that a reply value is nil.
var ErrNil = errors.New("redigo: nil returned")
ErrPoolExhausted is returned from a pool connection method (Do, Send, Receive, Flush, Err) when the maximum number of database connections in the pool has been reached.
var ErrPoolExhausted = errors.New("redigo: connection pool exhausted")
func Bool(reply interface{}, err error) (bool, error)
Bool is a helper that converts a command reply to a boolean. If err is not equal to nil, then Bool returns false, err. Otherwise Bool converts the reply to boolean as follows:
Reply type Result integer value != 0, nil bulk string strconv.ParseBool(reply) nil false, ErrNil other false, error
▹ Example
func ByteSlices(reply interface{}, err error) ([][]byte, error)
ByteSlices is a helper that converts an array command reply to a [][]byte. If err is not equal to nil, then ByteSlices returns nil, err. Nil array items are stay nil. ByteSlices returns an error if an array item is not a bulk string or nil.
func Bytes(reply interface{}, err error) ([]byte, error)
Bytes is a helper that converts a command reply to a slice of bytes. If err is not equal to nil, then Bytes returns nil, err. Otherwise Bytes converts the reply to a slice of bytes as follows:
Reply type Result bulk string reply, nil simple string []byte(reply), nil nil nil, ErrNil other nil, error
func DoWithTimeout(c Conn, timeout time.Duration, cmd string, args ...interface{}) (interface{}, error)
DoWithTimeout executes a Redis command with the specified read timeout. If the connection does not satisfy the ConnWithTimeout interface, then an error is returned.
func Float64(reply interface{}, err error) (float64, error)
Float64 is a helper that converts a command reply to 64 bit float. If err is not equal to nil, then Float64 returns 0, err. Otherwise, Float64 converts the reply to an int as follows:
Reply type Result bulk string parsed reply, nil nil 0, ErrNil other 0, error
func Float64s(reply interface{}, err error) ([]float64, error)
Float64s is a helper that converts an array command reply to a []float64. If err is not equal to nil, then Float64s returns nil, err. Nil array items are converted to 0 in the output slice. Floats64 returns an error if an array item is not a bulk string or nil.
func Int(reply interface{}, err error) (int, error)
Int is a helper that converts a command reply to an integer. If err is not equal to nil, then Int returns 0, err. Otherwise, Int converts the reply to an int as follows:
Reply type Result integer int(reply), nil bulk string parsed reply, nil nil 0, ErrNil other 0, error
▹ Example
func Int64(reply interface{}, err error) (int64, error)
Int64 is a helper that converts a command reply to 64 bit integer. If err is not equal to nil, then Int returns 0, err. Otherwise, Int64 converts the reply to an int64 as follows:
Reply type Result integer reply, nil bulk string parsed reply, nil nil 0, ErrNil other 0, error
func Int64Map(result interface{}, err error) (map[string]int64, error)
Int64Map is a helper that converts an array of strings (alternating key, value) into a map[string]int64. The HGETALL commands return replies in this format. Requires an even number of values in result.
func Int64s(reply interface{}, err error) ([]int64, error)
Int64s is a helper that converts an array command reply to a []int64. If err is not equal to nil, then Int64s returns nil, err. Nil array items are stay nil. Int64s returns an error if an array item is not a bulk string or nil.
func IntMap(result interface{}, err error) (map[string]int, error)
IntMap is a helper that converts an array of strings (alternating key, value) into a map[string]int. The HGETALL commands return replies in this format. Requires an even number of values in result.
func Ints(reply interface{}, err error) ([]int, error)
Ints is a helper that converts an array command reply to a []in. If err is not equal to nil, then Ints returns nil, err. Nil array items are stay nil. Ints returns an error if an array item is not a bulk string or nil.
▹ Example
func MultiBulk(reply interface{}, err error) ([]interface{}, error)
MultiBulk is a helper that converts an array command reply to a []interface{}.
Deprecated: Use Values instead.
func Positions(result interface{}, err error) ([]*[2]float64, error)
Positions is a helper that converts an array of positions (lat, long) into a [][2]float64. The GEOPOS command returns replies in this format.
func ReceiveWithTimeout(c Conn, timeout time.Duration) (interface{}, error)
ReceiveWithTimeout receives a reply with the specified read timeout. If the connection does not satisfy the ConnWithTimeout interface, then an error is returned.
func Scan(src []interface{}, dest ...interface{}) ([]interface{}, error)
Scan copies from src to the values pointed at by dest.
Scan uses RedisScan if available otherwise:
The values pointed at by dest must be an integer, float, boolean, string, []byte, interface{} or slices of these types. Scan uses the standard strconv package to convert bulk strings to numeric and boolean types.
If a dest value is nil, then the corresponding src value is skipped.
If a src element is nil, then the corresponding dest value is not modified.
To enable easy use of Scan in a loop, Scan returns the slice of src following the copied values.
▹ Example
func ScanSlice(src []interface{}, dest interface{}, fieldNames ...string) error
ScanSlice scans src to the slice pointed to by dest. The elements the dest slice must be integer, float, boolean, string, struct or pointer to struct values.
Struct fields must be integer, float, boolean or string values. All struct fields are used unless a subset is specified using fieldNames.
▹ Example
func ScanStruct(src []interface{}, dest interface{}) error
ScanStruct scans alternating names and values from src to a struct. The HGETALL and CONFIG GET commands return replies in this format.
ScanStruct uses exported field names to match values in the response. Use 'redis' field tag to override the name:
Field int `redis:"myName"`
Fields with the tag redis:"-" are ignored.
Each field uses RedisScan if available otherwise: Integer, float, boolean, string and []byte fields are supported. Scan uses the standard strconv package to convert bulk string values to numeric and boolean types.
If a src element is nil, then the corresponding field is not modified.
func String(reply interface{}, err error) (string, error)
String is a helper that converts a command reply to a string. If err is not equal to nil, then String returns "", err. Otherwise String converts the reply to a string as follows:
Reply type Result bulk string string(reply), nil simple string reply, nil nil "", ErrNil other "", error
▹ Example
func StringMap(result interface{}, err error) (map[string]string, error)
StringMap is a helper that converts an array of strings (alternating key, value) into a map[string]string. The HGETALL and CONFIG GET commands return replies in this format. Requires an even number of values in result.
func Strings(reply interface{}, err error) ([]string, error)
Strings is a helper that converts an array command reply to a []string. If err is not equal to nil, then Strings returns nil, err. Nil array items are converted to "" in the output slice. Strings returns an error if an array item is not a bulk string or nil.
func Uint64(reply interface{}, err error) (uint64, error)
Uint64 is a helper that converts a command reply to 64 bit integer. If err is not equal to nil, then Int returns 0, err. Otherwise, Int64 converts the reply to an int64 as follows:
Reply type Result integer reply, nil bulk string parsed reply, nil nil 0, ErrNil other 0, error
func Values(reply interface{}, err error) ([]interface{}, error)
Values is a helper that converts an array command reply to a []interface{}. If err is not equal to nil, then Values returns nil, err. Otherwise, Values converts the reply as follows:
Reply type Result array reply, nil nil nil, ErrNil other nil, error
Args is a helper for constructing command arguments from structured values.
type Args []interface{}
▹ Example
func (args Args) Add(value ...interface{}) Args
Add returns the result of appending value to args.
func (args Args) AddFlat(v interface{}) Args
AddFlat returns the result of appending the flattened value of v to args.
Maps are flattened by appending the alternating keys and map values to args.
Slices are flattened by appending the slice elements to args.
Structs are flattened by appending the alternating names and values of exported fields to args. If v is a nil struct pointer, then nothing is appended. The 'redis' field tag overrides struct field names. See ScanStruct for more information on the use of the 'redis' field tag.
Other types are appended to args as is.
Argument is the interface implemented by an object which wants to control how the object is converted to Redis bulk strings.
type Argument interface { // RedisArg returns a value to be encoded as a bulk string per the // conversions listed in the section 'Executing Commands'. // Implementations should typically return a []byte or string. RedisArg() interface{} }
Conn represents a connection to a Redis server.
type Conn interface { // Close closes the connection. Close() error // Err returns a non-nil value when the connection is not usable. Err() error // Do sends a command to the server and returns the received reply. Do(commandName string, args ...interface{}) (reply interface{}, err error) // Send writes the command to the client's output buffer. Send(commandName string, args ...interface{}) error // Flush flushes the output buffer to the Redis server. Flush() error // Receive receives a single reply from the Redis server Receive() (reply interface{}, err error) }
func Dial(network, address string, options ...DialOption) (Conn, error)
Dial connects to the Redis server at the given network and address using the specified options.
▹ Example
func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error)
DialTimeout acts like Dial but takes timeouts for establishing the connection to the server, writing a command and reading a reply.
Deprecated: Use Dial with options instead.
func DialURL(rawurl string, options ...DialOption) (Conn, error)
DialURL connects to a Redis server at the given URL using the Redis URI scheme. URLs should follow the draft IANA specification for the scheme (https://www.iana.org/assignments/uri-schemes/prov/redis).
▹ Example
func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn
NewConn returns a new Redigo connection for the given net connection.
func NewLoggingConn(conn Conn, logger *log.Logger, prefix string) Conn
NewLoggingConn returns a logging wrapper around a connection.
ConnWithTimeout is an optional interface that allows the caller to override a connection's default read timeout. This interface is useful for executing the BLPOP, BRPOP, BRPOPLPUSH, XREAD and other commands that block at the server.
A connection's default read timeout is set with the DialReadTimeout dial option. Applications should rely on the default timeout for commands that do not block at the server.
All of the Conn implementations in this package satisfy the ConnWithTimeout interface.
Use the DoWithTimeout and ReceiveWithTimeout helper functions to simplify use of this interface.
type ConnWithTimeout interface { Conn // Do sends a command to the server and returns the received reply. // The timeout overrides the read timeout set when dialing the // connection. DoWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (reply interface{}, err error) // Receive receives a single reply from the Redis server. The timeout // overrides the read timeout set when dialing the connection. ReceiveWithTimeout(timeout time.Duration) (reply interface{}, err error) }
DialOption specifies an option for dialing a Redis server.
type DialOption struct {
// contains filtered or unexported fields
}
func DialConnectTimeout(d time.Duration) DialOption
DialConnectTimeout specifies the timeout for connecting to the Redis server when no DialNetDial option is specified.
func DialDatabase(db int) DialOption
DialDatabase specifies the database to select when dialing a connection.
func DialKeepAlive(d time.Duration) DialOption
DialKeepAlive specifies the keep-alive period for TCP connections to the Redis server when no DialNetDial option is specified. If zero, keep-alives are not enabled. If no DialKeepAlive option is specified then the default of 5 minutes is used to ensure that half-closed TCP sessions are detected.
func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption
DialNetDial specifies a custom dial function for creating TCP connections, otherwise a net.Dialer customized via the other options is used. DialNetDial overrides DialConnectTimeout and DialKeepAlive.
func DialPassword(password string) DialOption
DialPassword specifies the password to use when connecting to the Redis server.
func DialReadTimeout(d time.Duration) DialOption
DialReadTimeout specifies the timeout for reading a single command reply.
func DialTLSConfig(c *tls.Config) DialOption
DialTLSConfig specifies the config to use when a TLS connection is dialed. Has no effect when not dialing a TLS connection.
func DialTLSSkipVerify(skip bool) DialOption
DialTLSSkipVerify disables server name verification when connecting over TLS. Has no effect when not dialing a TLS connection.
func DialUseTLS(useTLS bool) DialOption
DialUseTLS specifies whether TLS should be used when connecting to the server. This option is ignore by DialURL.
func DialWriteTimeout(d time.Duration) DialOption
DialWriteTimeout specifies the timeout for writing a single command.
Error represents an error returned in a command reply.
type Error string
func (err Error) Error() string
Message represents a message notification.
type Message struct { // The originating channel. Channel string // The matched pattern, if any Pattern string // The message data. Data []byte }
Pong represents a pubsub pong notification.
type Pong struct { Data string }
Pool maintains a pool of connections. The application calls the Get method to get a connection from the pool and the connection's Close method to return the connection's resources to the pool.
The following example shows how to use a pool in a web application. The application creates a pool at application startup and makes it available to request handlers using a package level variable. The pool configuration used here is an example, not a recommendation.
func newPool(addr string) *redis.Pool { return &redis.Pool{ MaxIdle: 3, IdleTimeout: 240 * time.Second, Dial: func () (redis.Conn, error) { return redis.Dial("tcp", addr) }, } } var ( pool *redis.Pool redisServer = flag.String("redisServer", ":6379", "") ) func main() { flag.Parse() pool = newPool(*redisServer) ... }
A request handler gets a connection from the pool and closes the connection when the handler is done:
func serveHome(w http.ResponseWriter, r *http.Request) { conn := pool.Get() defer conn.Close() ... }
Use the Dial function to authenticate connections with the AUTH command or select a database with the SELECT command:
pool := &redis.Pool{ // Other pool configuration not shown in this example. Dial: func () (redis.Conn, error) { c, err := redis.Dial("tcp", server) if err != nil { return nil, err } if _, err := c.Do("AUTH", password); err != nil { c.Close() return nil, err } if _, err := c.Do("SELECT", db); err != nil { c.Close() return nil, err } return c, nil }, }
Use the TestOnBorrow function to check the health of an idle connection before the connection is returned to the application. This example PINGs connections that have been idle more than a minute:
pool := &redis.Pool{ // Other pool configuration not shown in this example. TestOnBorrow: func(c redis.Conn, t time.Time) error { if time.Since(t) < time.Minute { return nil } _, err := c.Do("PING") return err }, }
type Pool struct { // Dial is an application supplied function for creating and configuring a // connection. // // The connection returned from Dial must not be in a special state // (subscribed to pubsub channel, transaction started, ...). Dial func() (Conn, error) // TestOnBorrow is an optional application supplied function for checking // the health of an idle connection before the connection is used again by // the application. Argument t is the time that the connection was returned // to the pool. If the function returns an error, then the connection is // closed. TestOnBorrow func(c Conn, t time.Time) error // Maximum number of idle connections in the pool. MaxIdle int // Maximum number of connections allocated by the pool at a given time. // When zero, there is no limit on the number of connections in the pool. MaxActive int // Close connections after remaining idle for this duration. If the value // is zero, then idle connections are not closed. Applications should set // the timeout to a value less than the server's timeout. IdleTimeout time.Duration // If Wait is true and the pool is at the MaxActive limit, then Get() waits // for a connection to be returned to the pool before returning. Wait bool // Close connections older than this duration. If the value is zero, then // the pool does not close connections based on age. MaxConnLifetime time.Duration // contains filtered or unexported fields }
func NewPool(newFn func() (Conn, error), maxIdle int) *Pool
NewPool creates a new pool.
Deprecated: Initialize the Pool directory as shown in the example.
func (p *Pool) ActiveCount() int
ActiveCount returns the number of connections in the pool. The count includes idle connections and connections in use.
func (p *Pool) Close() error
Close releases the resources used by the pool.
func (p *Pool) Get() Conn
Get gets a connection. The application must close the returned connection. This method always returns a valid connection so that applications can defer error handling to the first use of the connection. If there is an error getting an underlying connection, then the connection Err, Do, Send, Flush and Receive methods return that error.
func (p *Pool) GetContext(ctx context.Context) (Conn, error)
GetContext gets a connection using the provided context.
The provided Context must be non-nil. If the context expires before the connection is complete, an error is returned. Any expiration on the context will not affect the returned connection.
If the function completes without error, then the application must close the returned connection.
func (p *Pool) IdleCount() int
IdleCount returns the number of idle connections in the pool.
func (p *Pool) Stats() PoolStats
Stats returns pool's statistics.
PoolStats contains pool statistics.
type PoolStats struct { // ActiveCount is the number of connections in the pool. The count includes // idle connections and connections in use. ActiveCount int // IdleCount is the number of idle connections in the pool. IdleCount int }
PubSubConn wraps a Conn with convenience methods for subscribers.
type PubSubConn struct { Conn Conn }
▹ Example
func (c PubSubConn) Close() error
Close closes the connection.
func (c PubSubConn) PSubscribe(channel ...interface{}) error
PSubscribe subscribes the connection to the given patterns.
func (c PubSubConn) PUnsubscribe(channel ...interface{}) error
PUnsubscribe unsubscribes the connection from the given patterns, or from all of them if none is given.
func (c PubSubConn) Ping(data string) error
Ping sends a PING to the server with the specified data.
The connection must be subscribed to at least one channel or pattern when calling this method.
func (c PubSubConn) Receive() interface{}
Receive returns a pushed message as a Subscription, Message, Pong or error. The return value is intended to be used directly in a type switch as illustrated in the PubSubConn example.
func (c PubSubConn) ReceiveWithTimeout(timeout time.Duration) interface{}
ReceiveWithTimeout is like Receive, but it allows the application to override the connection's default timeout.
func (c PubSubConn) Subscribe(channel ...interface{}) error
Subscribe subscribes the connection to the specified channels.
func (c PubSubConn) Unsubscribe(channel ...interface{}) error
Unsubscribe unsubscribes the connection from the given channels, or from all of them if none is given.
Scanner is implemented by an object which wants to control its value is interpreted when read from Redis.
type Scanner interface { // RedisScan assigns a value from a Redis value. The argument src is one of // the reply types listed in the section `Executing Commands`. // // An error should be returned if the value cannot be stored without // loss of information. RedisScan(src interface{}) error }
Script encapsulates the source, hash and key count for a Lua script. See http://redis.io/commands/eval for information on scripts in Redis.
type Script struct {
// contains filtered or unexported fields
}
▹ Example
func NewScript(keyCount int, src string) *Script
NewScript returns a new script object. If keyCount is greater than or equal to zero, then the count is automatically inserted in the EVAL command argument list. If keyCount is less than zero, then the application supplies the count as the first value in the keysAndArgs argument to the Do, Send and SendHash methods.
func (s *Script) Do(c Conn, keysAndArgs ...interface{}) (interface{}, error)
Do evaluates the script. Under the covers, Do optimistically evaluates the script using the EVALSHA command. If the command fails because the script is not loaded, then Do evaluates the script using the EVAL command (thus causing the script to load).
func (s *Script) Hash() string
Hash returns the script hash.
func (s *Script) Load(c Conn) error
Load loads the script without evaluating it.
func (s *Script) Send(c Conn, keysAndArgs ...interface{}) error
Send evaluates the script without waiting for the reply.
func (s *Script) SendHash(c Conn, keysAndArgs ...interface{}) error
SendHash evaluates the script without waiting for the reply. The script is evaluated with the EVALSHA command. The application must ensure that the script is loaded by a previous call to Send, Do or Load methods.
Subscription represents a subscribe or unsubscribe notification.
type Subscription struct { // Kind is "subscribe", "unsubscribe", "psubscribe" or "punsubscribe" Kind string // The channel that was changed. Channel string // The current number of subscriptions for connection. Count int }