Movatterモバイル変換


[0]ホーム

URL:


redis

package
v1.9.3Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2025 License:Apache-2.0Imports:20Imported by:8,587

Details

Repository

github.com/gomodule/redigo

Links

Documentation

Overview

Package redis is a client for the Redis database.

The Redigo FAQ (https://github.com/gomodule/redigo/wiki/FAQ) contains moredocumentation about this package.

Connections

The Conn interface is the primary interface for working with Redis.Applications create connections by calling the Dial, DialWithTimeout orNewConn functions. In the future, functions will be added for creatingsharded and other types of connections.

The application must call the connection Close method when the applicationis done with the connection.

Executing Commands

The Conn interface has a generic method for executing Redis commands:

Do(commandName string, args ...interface{}) (reply interface{}, err error)

The Redis command reference (http://redis.io/commands) lists the availablecommands. An example of using the Redis APPEND command is:

n, err := conn.Do("APPEND", "key", "value")

The Do method converts command arguments to bulk strings for transmissionto the server as follows:

Go Type                 Conversion[]byte                  Sent as isstring                  Sent as isint, int64              strconv.FormatInt(v)float64                 strconv.FormatFloat(v, 'g', -1, 64)bool                    true -> "1", false -> "0"nil                     ""all other types         fmt.Fprint(w, v)

Redis command reply types are represented using the following Go types:

Redis type              Go typeerror                   redis.Errorinteger                 int64simple string           stringbulk string             []byte or nil if value not present.array                   []interface{} or nil if value not present.

Use type assertions or the reply helper functions to convert frominterface{} to the specific Go type for the command result.

Pipelining

Connections support pipelining using the Send, Flush and Receive methods.

Send(commandName string, args ...interface{}) errorFlush() errorReceive() (reply interface{}, err error)

Send writes the command to the connection's output buffer. Flush flushes theconnection's output buffer to the server. Receive reads a single reply fromthe server. The following example shows a simple pipeline.

c.Send("SET", "foo", "bar")c.Send("GET", "foo")c.Flush()c.Receive() // reply from SETv, err = c.Receive() // reply from GET

The Do method combines the functionality of the Send, Flush and Receivemethods. The Do method starts by writing the command and flushing the outputbuffer. Next, the Do method receives all pending replies including the replyfor the command just sent by Do. If any of the received replies is an error,then Do returns the error. If there are no errors, then Do returns the lastreply. If the command argument to the Do method is "", then the Do methodwill flush the output buffer and receive pending replies without sending acommand.

Use the Send and Do methods to implement pipelined transactions.

c.Send("MULTI")c.Send("INCR", "foo")c.Send("INCR", "bar")r, err := c.Do("EXEC")fmt.Println(r) // prints [1, 1]

Concurrency

Connections support one concurrent caller to the Receive method and oneconcurrent caller to the Send and Flush methods. No other concurrency issupported including concurrent calls to the Do and Close methods.

For full concurrent access to Redis, use the thread-safe Pool to get, useand release a connection from within a goroutine. Connections returned froma Pool have the concurrency restrictions described in the previousparagraph.

Publish and Subscribe

Use the Send, Flush and Receive methods to implement Pub/Sub subscribers.

c.Send("SUBSCRIBE", "example")c.Flush()for {    reply, err := c.Receive()    if err != nil {        return err    }    // process pushed message}

The PubSubConn type wraps a Conn with convenience methods for implementingsubscribers. The Subscribe, PSubscribe, Unsubscribe and PUnsubscribe methodssend and flush a subscription management command. The receive methodconverts a pushed message to convenient types for use in a type switch.

psc := redis.PubSubConn{Conn: c}psc.Subscribe("example")for {    switch v := psc.Receive().(type) {    case redis.Message:        fmt.Printf("%s: message: %s\n", v.Channel, v.Data)    case redis.Subscription:        fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)    case error:        return v    }}

Reply Helpers

The Bool, Int, Bytes, String, Strings and Values functions convert a replyto a value of a specific type. To allow convenient wrapping of calls to theconnection Do and Receive methods, the functions take a second argument oftype error. If the error is non-nil, then the helper function returns theerror. If the error is nil, the function converts the reply to the specifiedtype:

exists, err := redis.Bool(c.Do("EXISTS", "foo"))if err != nil {    // handle error return from c.Do or type conversion error.}

The Scan function converts elements of a array reply to Go types:

var value1 intvar value2 stringreply, err := redis.Values(c.Do("MGET", "key1", "key2"))if err != nil {    // handle error} if _, err := redis.Scan(reply, &value1, &value2); err != nil {    // handle error}

Errors

Connection methods return error replies from the server as type redis.Error.

Call the connection Err() method to determine if the connection encounterednon-recoverable error such as a network error or protocol parsing error. IfErr() returns a non-nil value, then the connection is not usable and shouldbe closed.

Example (Zpop)

This example implements ZPOP as described athttp://redis.io/topics/transactions using WATCH/MULTI/EXEC and scripting.

package mainimport ("fmt""github.com/gomodule/redigo/redis")// zpop pops a value from the ZSET key using WATCH/MULTI/EXEC commands.func zpop(c redis.Conn, key string) (result string, err error) {defer func() {// Return connection to normal state on error.if err != nil {c.Do("DISCARD") // nolint: errcheck}}()// Loop until transaction is successful.for {if _, err := c.Do("WATCH", key); err != nil {return "", err}members, err := redis.Strings(c.Do("ZRANGE", key, 0, 0))if err != nil {return "", err}if len(members) != 1 {return "", redis.ErrNil}if err = c.Send("MULTI"); err != nil {return "", err}if err = c.Send("ZREM", key, members[0]); err != nil {return "", err}queued, err := c.Do("EXEC")if err != nil {return "", err}if queued != nil {result = members[0]break}}return result, nil}// zpopScript pops a value from a ZSET.var zpopScript = redis.NewScript(1, `    local r = redis.call('ZRANGE', KEYS[1], 0, 0)    if r ~= nil then        r = r[1]        redis.call('ZREM', KEYS[1], r)    end    return r`)// This example implements ZPOP as described at// http://redis.io/topics/transactions using WATCH/MULTI/EXEC and scripting.func main() {c, err := dial()if err != nil {fmt.Println(err)return}defer c.Close()// Add test data using a pipeline.for i, member := range []string{"red", "blue", "green"} {if err = c.Send("ZADD", "zset", i, member); err != nil {fmt.Println(err)return}}if _, err := c.Do(""); err != nil {fmt.Println(err)return}// Pop using WATCH/MULTI/EXECv, err := zpop(c, "zset")if err != nil {fmt.Println(err)return}fmt.Println(v)// Pop using a script.v, err = redis.String(zpopScript.Do(c, "zset"))if err != nil {fmt.Println(err)return}fmt.Println(v)}
Output:redblue

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNil =errors.New("redigo: nil returned")

ErrNil indicates that a reply value is nil.

View Source
var ErrPoolExhausted =errors.New("redigo: connection pool exhausted")

ErrPoolExhausted is returned from a pool connection method (Do, Send,Receive, Flush, Err) when the maximum number of database connections in thepool has been reached.

Functions

funcBool

func Bool(reply interface{}, errerror) (bool,error)

Bool is a helper that converts a command reply to a boolean. If err is notequal to nil, then Bool returns false, err. Otherwise Bool converts thereply to boolean as follows:

Reply type      Resultinteger         value != 0, nilbulk string     strconv.ParseBool(reply)nil             false, ErrNilother           false, error
Example
package mainimport ("fmt""github.com/gomodule/redigo/redis")// dial wraps DialDefaultServer() with a more suitable function name for examples.func dial() (redis.Conn, error) {return redis.DialDefaultServer()}func main() {c, err := dial()if err != nil {fmt.Println(err)return}defer c.Close()if _, err = c.Do("SET", "foo", 1); err != nil {fmt.Println(err)return}exists, err := redis.Bool(c.Do("EXISTS", "foo"))if err != nil {fmt.Println(err)return}fmt.Printf("%#v\n", exists)}
Output:true

funcByteSlices

func ByteSlices(reply interface{}, errerror) ([][]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 arrayitems are stay nil. ByteSlices returns an error if an array item is not abulk string or nil.

funcBytes

func Bytes(reply interface{}, errerror) ([]byte,error)

Bytes is a helper that converts a command reply to a slice of bytes. If erris not equal to nil, then Bytes returns nil, err. Otherwise Bytes convertsthe reply to a slice of bytes as follows:

Reply type      Resultbulk string     reply, nilsimple string   []byte(reply), nilnil             nil, ErrNilother           nil, error

funcDoContextadded inv1.8.6

func DoContext(cConn, ctxcontext.Context, cmdstring, args ...interface{}) (interface{},error)

DoContext sends a command to server and returns the received reply.min(ctx,DialReadTimeout()) will be used as the deadline.The connection will be closed if DialReadTimeout() timeout or ctx timeout or ctx canceled when this function is running.DialReadTimeout() timeout return err can be checked by errors.Is(err, os.ErrDeadlineExceeded).ctx timeout return err context.DeadlineExceeded.ctx canceled return err context.Canceled.

funcDoWithTimeout

func DoWithTimeout(cConn, timeouttime.Duration, cmdstring, args ...interface{}) (interface{},error)

DoWithTimeout executes a Redis command with the specified read timeout. Ifthe connection does not satisfy the ConnWithTimeout interface, then an erroris returned.

funcFloat64

func Float64(reply interface{}, errerror) (float64,error)

Float64 is a helper that converts a command reply to 64 bit float. If err isnot equal to nil, then Float64 returns 0, err. Otherwise, Float64 convertsthe reply to a float64 as follows:

Reply type    Resultbulk string   parsed reply, nilnil           0, ErrNilother         0, error

funcFloat64Mapadded inv1.8.9

func Float64Map(result interface{}, errerror) (map[string]float64,error)

Float64Map is a helper that converts an array of strings (alternating key, value)into a map[string]float64. The HGETALL commands return replies in this format.Requires an even number of values in result.

funcFloat64s

func Float64s(reply interface{}, errerror) ([]float64,error)

Float64s is a helper that converts an array command reply to a []float64. Iferr is not equal to nil, then Float64s returns nil, err. Nil array items areconverted to 0 in the output slice. Floats64 returns an error if an arrayitem is not a bulk string or nil.

funcInt

func Int(reply interface{}, errerror) (int,error)

Int is a helper that converts a command reply to an integer. If err is notequal to nil, then Int returns 0, err. Otherwise, Int converts thereply to an int as follows:

Reply type    Resultinteger       int(reply), nilbulk string   parsed reply, nilnil           0, ErrNilother         0, error
Example
package mainimport ("fmt""github.com/gomodule/redigo/redis")// dial wraps DialDefaultServer() with a more suitable function name for examples.func dial() (redis.Conn, error) {return redis.DialDefaultServer()}func main() {c, err := dial()if err != nil {fmt.Println(err)return}defer c.Close()_, err = c.Do("SET", "k1", 1)if err != nil {fmt.Println(err)return}n, err := redis.Int(c.Do("GET", "k1"))if err != nil {fmt.Println(err)return}fmt.Printf("%#v\n", n)n, err = redis.Int(c.Do("INCR", "k1"))if err != nil {fmt.Println(err)return}fmt.Printf("%#v\n", n)}
Output:12

funcInt64

func Int64(reply interface{}, errerror) (int64,error)

Int64 is a helper that converts a command reply to 64 bit integer. If err isnot equal to nil, then Int64 returns 0, err. Otherwise, Int64 converts thereply to an int64 as follows:

Reply type    Resultinteger       reply, nilbulk string   parsed reply, nilnil           0, ErrNilother         0, error

funcInt64Map

func Int64Map(result interface{}, errerror) (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.

funcInt64s

func Int64s(reply interface{}, errerror) ([]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 arrayitems are stay nil. Int64s returns an error if an array item is not abulk string or nil.

funcIntMap

func IntMap(result interface{}, errerror) (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.

funcInts

func Ints(reply interface{}, errerror) ([]int,error)

Ints is a helper that converts an array command reply to a []int.If err is not equal to nil, then Ints returns nil, err. Nil arrayitems are stay nil. Ints returns an error if an array item is not abulk string or nil.

Example
package mainimport ("fmt""github.com/gomodule/redigo/redis")// dial wraps DialDefaultServer() with a more suitable function name for examples.func dial() (redis.Conn, error) {return redis.DialDefaultServer()}func main() {c, err := dial()if err != nil {fmt.Println(err)return}defer c.Close()_, err = c.Do("SADD", "set_with_integers", 4, 5, 6)if err != nil {fmt.Println(err)return}ints, err := redis.Ints(c.Do("SMEMBERS", "set_with_integers"))if err != nil {fmt.Println(err)return}fmt.Printf("%#v\n", ints)}
Output:[]int{4, 5, 6}

funcMultiBulkdeprecated

func MultiBulk(reply interface{}, errerror) ([]interface{},error)

MultiBulk is a helper that converts an array command reply to a []interface{}.

Deprecated: Use Values instead.

funcPositions

func Positions(result interface{}, errerror) ([]*[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.

funcReceiveContextadded inv1.8.6

func ReceiveContext(cConn, ctxcontext.Context) (interface{},error)

ReceiveContext receives a single reply from the Redis server.min(ctx,DialReadTimeout()) will be used as the deadline.The connection will be closed if DialReadTimeout() timeout or ctx timeout or ctx canceled when this function is running.DialReadTimeout() timeout return err can be checked by strings.Contains(e.Error(), "io/timeout").ctx timeout return err context.DeadlineExceeded.ctx canceled return err context.Canceled.

funcReceiveWithTimeout

func ReceiveWithTimeout(cConn, timeouttime.Duration) (interface{},error)

ReceiveWithTimeout receives a reply with the specified read timeout. If theconnection does not satisfy the ConnWithTimeout interface, then an error isreturned.

funcScan

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 strconvpackage 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 srcfollowing the copied values.

Example
c, err := dial()if err != nil {fmt.Println(err)return}defer c.Close()if err = c.Send("HMSET", "album:1", "title", "Red", "rating", 5); err != nil {fmt.Println(err)return}if err = c.Send("HMSET", "album:2", "title", "Earthbound", "rating", 1); err != nil {fmt.Println(err)return}if err = c.Send("HMSET", "album:3", "title", "Beat"); err != nil {fmt.Println(err)return}if err = c.Send("LPUSH", "albums", "1"); err != nil {fmt.Println(err)return}if err = c.Send("LPUSH", "albums", "2"); err != nil {fmt.Println(err)return}if err = c.Send("LPUSH", "albums", "3"); err != nil {fmt.Println(err)return}values, err := redis.Values(c.Do("SORT", "albums","BY", "album:*->rating","GET", "album:*->title","GET", "album:*->rating"))if err != nil {fmt.Println(err)return}for len(values) > 0 {var title stringrating := -1 // initialize to illegal value to detect nil.values, err = redis.Scan(values, &title, &rating)if err != nil {fmt.Println(err)return}if rating == -1 {fmt.Println(title, "not-rated")} else {fmt.Println(title, rating)}}
Output:Beat not-ratedEarthbound 1Red 5

funcScanSlice

func ScanSlice(src []interface{}, dest interface{}, fieldNames ...string)error

ScanSlice scans src to the slice pointed to by dest.

If the target is a slice of types which implement Scanner then the customRedisScan method is used otherwise the following rules apply:

The elements in the dest slice must be integer, float, boolean, string, structor pointer to struct values.

Struct fields must be integer, float, boolean or string values. All structfields are used unless a subset is specified using fieldNames.

Example
c, err := dial()if err != nil {fmt.Println(err)return}defer c.Close()if err = c.Send("HMSET", "album:1", "title", "Red", "rating", 5); err != nil {fmt.Println(err)return}if err = c.Send("HMSET", "album:2", "title", "Earthbound", "rating", 1); err != nil {fmt.Println(err)return}if err = c.Send("HMSET", "album:3", "title", "Beat", "rating", 4); err != nil {fmt.Println(err)return}if err = c.Send("LPUSH", "albums", "1"); err != nil {fmt.Println(err)return}if err = c.Send("LPUSH", "albums", "2"); err != nil {fmt.Println(err)return}if err = c.Send("LPUSH", "albums", "3"); err != nil {fmt.Println(err)return}values, err := redis.Values(c.Do("SORT", "albums","BY", "album:*->rating","GET", "album:*->title","GET", "album:*->rating"))if err != nil {fmt.Println(err)return}var albums []struct {Title  stringRating int}if err := redis.ScanSlice(values, &albums); err != nil {fmt.Println(err)return}fmt.Printf("%v\n", albums)
Output:[{Earthbound 1} {Beat 4} {Red 5}]

funcScanStruct

func ScanStruct(src []interface{}, dest interface{})error

ScanStruct scans alternating names and values from src to a struct. TheHGETALL 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 thestandard strconv package to convert bulk string values to numeric andboolean types.

If a src element is nil, then the corresponding field is not modified.

funcString

func String(reply interface{}, errerror) (string,error)

String is a helper that converts a command reply to a string. If err is notequal to nil, then String returns "", err. Otherwise String converts thereply to a string as follows:

Reply type      Resultbulk string     string(reply), nilsimple string   reply, nilnil             "",  ErrNilother           "",  error
Example
package mainimport ("fmt""github.com/gomodule/redigo/redis")// dial wraps DialDefaultServer() with a more suitable function name for examples.func dial() (redis.Conn, error) {return redis.DialDefaultServer()}func main() {c, err := dial()if err != nil {fmt.Println(err)return}defer c.Close()_, err = c.Do("SET", "hello", "world")if err != nil {fmt.Println(err)return}s, err := redis.String(c.Do("GET", "hello"))if err != nil {fmt.Println(err)return}fmt.Printf("%#v\n", s)}
Output:"world"

funcStringMap

func StringMap(reply interface{}, errerror) (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.

funcStrings

func Strings(reply interface{}, errerror) ([]string,error)

Strings is a helper that converts an array command reply to a []string. Iferr is not equal to nil, then Strings returns nil, err. Nil array items areconverted to "" in the output slice. Strings returns an error if an arrayitem is not a bulk string or nil.

funcUint64

func Uint64(reply interface{}, errerror) (uint64,error)

Uint64 is a helper that converts a command reply to 64 bit unsigned integer.If err is not equal to nil, then Uint64 returns 0, err. Otherwise, Uint64 converts thereply to an uint64 as follows:

Reply type    Result+integer      reply, nilbulk string   parsed reply, nilnil           0, ErrNilother         0, error

funcUint64Mapadded inv1.7.2

func Uint64Map(result interface{}, errerror) (map[string]uint64,error)

Uint64Map is a helper that converts an array of strings (alternating key, value)into a map[string]uint64. The HGETALL commands return replies in this format.Requires an even number of values in result.

funcUint64sadded inv1.7.2

func Uint64s(reply interface{}, errerror) ([]uint64,error)

Uint64s is a helper that converts an array command reply to a []uint64.If err is not equal to nil, then Uint64s returns nil, err. Nil arrayitems are stay nil. Uint64s returns an error if an array item is not abulk string or nil.

funcValues

func Values(reply interface{}, errerror) ([]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, Valuesconverts the reply as follows:

Reply type      Resultarray           reply, nilnil             nil, ErrNilother           nil, error

Types

typeArgs

type Args []interface{}

Args is a helper for constructing command arguments from structured values.

Example
c, err := dial()if err != nil {fmt.Println(err)return}defer c.Close()var p1, p2 struct {Title  string `redis:"title"`Author string `redis:"author"`Body   string `redis:"body"`}p1.Title = "Example"p1.Author = "Gary"p1.Body = "Hello"if _, err := c.Do("HMSET", redis.Args{}.Add("id1").AddFlat(&p1)...); err != nil {fmt.Println(err)return}m := map[string]string{"title":  "Example2","author": "Steve","body":   "Map",}if _, err := c.Do("HMSET", redis.Args{}.Add("id2").AddFlat(m)...); err != nil {fmt.Println(err)return}for _, id := range []string{"id1", "id2"} {v, err := redis.Values(c.Do("HGETALL", id))if err != nil {fmt.Println(err)return}if err := redis.ScanStruct(v, &p2); err != nil {fmt.Println(err)return}fmt.Printf("%+v\n", p2)}
Output:{Title:Example Author:Gary Body:Hello}{Title:Example2 Author:Steve Body:Map}

func (Args)Add

func (argsArgs) Add(value ...interface{})Args

Add returns the result of appending value to args.

func (Args)AddFlat

func (argsArgs) 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 ofexported fields to args. If v is a nil struct pointer, then nothing isappended. The 'redis' field tag overrides struct field names. See ScanStructfor more information on the use of the 'redis' field tag.

Other types are appended to args as is.panics if v includes a recursive anonymous struct.

typeArgument

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{}}

Argument is the interface implemented by an object which wants to control howthe object is converted to Redis bulk strings.

typeConn

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.// This function will use the timeout which was set when the connection is createdDo(commandNamestring, args ...interface{}) (reply interface{}, errerror)// Send writes the command to the client's output buffer.Send(commandNamestring, args ...interface{})error// Flush flushes the output buffer to the Redis server.Flush()error// Receive receives a single reply from the Redis serverReceive() (reply interface{}, errerror)}

Conn represents a connection to a Redis server.

funcDial

func Dial(network, addressstring, options ...DialOption) (Conn,error)

Dial connects to the Redis server at the given network andaddress using the specified options.

Example

Connect to local instance of Redis running on the default port.

package mainimport ("github.com/gomodule/redigo/redis")func main() {c, err := redis.Dial("tcp", ":6379")if err != nil {// handle error}defer c.Close()}

Example (Acl)

Connect to an Redis instance using the Redis ACL system

package mainimport ("github.com/gomodule/redigo/redis")func main() {c, err := redis.Dial("tcp", "localhost:6379",redis.DialUsername("username"),redis.DialPassword("password"),)if err != nil {// handle error}defer c.Close()}

funcDialContextadded inv1.8.2

func DialContext(ctxcontext.Context, network, addressstring, options ...DialOption) (Conn,error)

DialContext connects to the Redis server at the given network andaddress using the specified options and context.

Example

Connect to local instance of Redis running on the default port using the provided context.

package mainimport ("context""github.com/gomodule/redigo/redis")func main() {ctx := context.Background()c, err := redis.DialContext(ctx, "tcp", ":6379")if err != nil {// handle error}defer c.Close()}

funcDialTimeoutdeprecated

func DialTimeout(network, addressstring, connectTimeout, readTimeout, writeTimeouttime.Duration) (Conn,error)

DialTimeout acts like Dial but takes timeouts for establishing theconnection to the server, writing a command and reading a reply.

Deprecated: Use Dial with options instead.

funcDialURL

func DialURL(rawurlstring, options ...DialOption) (Conn,error)

DialURL wraps DialURLContext using context.Background.

Example

Connect to remote instance of Redis using a URL.

package mainimport ("os""github.com/gomodule/redigo/redis")func main() {c, err := redis.DialURL(os.Getenv("REDIS_URL"))if err != nil {// handle connection error}defer c.Close()}

funcDialURLContextadded inv1.8.6

func DialURLContext(ctxcontext.Context, rawurlstring, options ...DialOption) (Conn,error)

DialURLContext connects to a Redis server at the given URL using the RedisURI scheme. URLs should follow the draft IANA specification for thescheme (https://www.iana.org/assignments/uri-schemes/prov/redis).

funcNewConn

func NewConn(netConnnet.Conn, readTimeout, writeTimeouttime.Duration)Conn

NewConn returns a new Redigo connection for the given net connection.

funcNewLoggingConn

func NewLoggingConn(connConn, logger *log.Logger, prefixstring)Conn

NewLoggingConn returns a logging wrapper around a connection.

funcNewLoggingConnFilter

func NewLoggingConnFilter(connConn, logger *log.Logger, prefixstring, skip func(cmdNamestring)bool)Conn

NewLoggingConnFilter returns a logging wrapper around a connection and a filter function.

typeConnWithContextadded inv1.8.6

type ConnWithContext interface {Conn// DoContext sends a command to server and returns the received reply.// min(ctx,DialReadTimeout()) will be used as the deadline.// The connection will be closed if DialReadTimeout() timeout or ctx timeout or ctx canceled when this function is running.// DialReadTimeout() timeout return err can be checked by errors.Is(err, os.ErrDeadlineExceeded).// ctx timeout return err context.DeadlineExceeded.// ctx canceled return err context.Canceled.DoContext(ctxcontext.Context, commandNamestring, args ...interface{}) (reply interface{}, errerror)// ReceiveContext receives a single reply from the Redis server.// min(ctx,DialReadTimeout()) will be used as the deadline.// The connection will be closed if DialReadTimeout() timeout or ctx timeout or ctx canceled when this function is running.// DialReadTimeout() timeout return err can be checked by errors.Is(err, os.ErrDeadlineExceeded).// ctx timeout return err context.DeadlineExceeded.// ctx canceled return err context.Canceled.ReceiveContext(ctxcontext.Context) (reply interface{}, errerror)}

ConnWithContext is an optional interface that allows the caller to control the command's life with context.

typeConnWithTimeout

type ConnWithTimeout interface {Conn// DoWithTimeout sends a command to the server and returns the received reply.// The timeout overrides the readtimeout set when dialing the connection.DoWithTimeout(timeouttime.Duration, commandNamestring, args ...interface{}) (reply interface{}, errerror)// ReceiveWithTimeout receives a single reply from the Redis server.// The timeout overrides the readtimeout set when dialing the connection.ReceiveWithTimeout(timeouttime.Duration) (reply interface{}, errerror)}

ConnWithTimeout is an optional interface that allows the caller to overridea connection's default read timeout. This interface is useful for executingthe BLPOP, BRPOP, BRPOPLPUSH, XREAD and other commands that block at theserver.

A connection's default read timeout is set with the DialReadTimeout dialoption. Applications should rely on the default timeout for commands that donot block at the server.

All of the Conn implementations in this package satisfy the ConnWithTimeoutinterface.

Use the DoWithTimeout and ReceiveWithTimeout helper functions to simplifyuse of this interface.

typeDialOption

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

DialOption specifies an option for dialing a Redis server.

funcDialClientNameadded inv1.7.2

func DialClientName(namestring)DialOption

DialClientName specifies a client name to be usedby the Redis server connection.

funcDialConnectTimeout

func DialConnectTimeout(dtime.Duration)DialOption

DialConnectTimeout specifies the timeout for connecting to the Redis server whenno DialNetDial option is specified.If no DialConnectTimeout option is specified then the default is 30 seconds.

funcDialContextFuncadded inv1.8.2

func DialContextFunc(f func(ctxcontext.Context, network, addrstring) (net.Conn,error))DialOption

DialContextFunc specifies a custom dial function with context for creating TCPconnections, otherwise a net.Dialer customized via the other options is used.DialContextFunc overrides DialConnectTimeout and DialKeepAlive.

funcDialDatabase

func DialDatabase(dbint)DialOption

DialDatabase specifies the database to select when dialing a connection.

funcDialKeepAlive

func DialKeepAlive(dtime.Duration)DialOption

DialKeepAlive specifies the keep-alive period for TCP connections to the Redis serverwhen no DialNetDial option is specified.If zero, keep-alives are not enabled. If no DialKeepAlive option is specified thenthe default of 5 minutes is used to ensure that half-closed TCP sessions are detected.

funcDialNetDial

func DialNetDial(dial func(network, addrstring) (net.Conn,error))DialOption

DialNetDial specifies a custom dial function for creating TCPconnections, otherwise a net.Dialer customized via the other options is used.DialNetDial overrides DialConnectTimeout and DialKeepAlive.

funcDialPassword

func DialPassword(passwordstring)DialOption

DialPassword specifies the password to use when connecting tothe Redis server.

funcDialReadTimeout

func DialReadTimeout(dtime.Duration)DialOption

DialReadTimeout specifies the timeout for reading a single command reply.

funcDialTLSConfig

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.

funcDialTLSHandshakeTimeoutadded inv1.8.3

func DialTLSHandshakeTimeout(dtime.Duration)DialOption

DialTLSHandshakeTimeout specifies the maximum amount of time waiting towait for a TLS handshake. Zero means no timeout.If no DialTLSHandshakeTimeout option is specified then the default is 30 seconds.

funcDialTLSSkipVerify

func DialTLSSkipVerify(skipbool)DialOption

DialTLSSkipVerify disables server name verification when connecting overTLS. Has no effect when not dialing a TLS connection.

funcDialUseTLS

func DialUseTLS(useTLSbool)DialOption

DialUseTLS specifies whether TLS should be used when connecting to theserver. This option is ignore by DialURL.

funcDialUsernameadded inv1.8.2

func DialUsername(usernamestring)DialOption

DialUsername specifies the username to use when connecting tothe Redis server when Redis ACLs are used.A DialPassword must also be passed otherwise this option will have no effect.

funcDialWriteTimeout

func DialWriteTimeout(dtime.Duration)DialOption

DialWriteTimeout specifies the timeout for writing a single command.

typeError

type Errorstring

Error represents an error returned in a command reply.

func (Error)Error

func (errError) Error()string

typeLatencyadded inv1.8.9

type Latency struct {// Name of the latest latency spike event.Namestring// Time of the latest latency spike for the event.Timetime.Time// Latest is the latest recorded latency for the named event.Latesttime.Duration// Max is the maximum latency for the named event.Maxtime.Duration}

Latency represents a redis LATENCY LATEST.

funcLatenciesadded inv1.8.9

func Latencies(result interface{}, errerror) ([]Latency,error)

Latencies is a helper that parses the LATENCY LATEST command output andreturn the slice of Latency values.

typeLatencyHistoryadded inv1.8.9

type LatencyHistory struct {// Time is the unix timestamp at which the event was processed.Timetime.Time// ExecutationTime is the amount of time needed for the command execution.ExecutionTimetime.Duration}

LatencyHistory represents a redis LATENCY HISTORY.

funcLatencyHistoriesadded inv1.8.9

func LatencyHistories(result interface{}, errerror) ([]LatencyHistory,error)

LatencyHistories is a helper that parse the LATENCY HISTORY command output andreturns a LatencyHistory slice.

typeMessage

type Message struct {// The originating channel.Channelstring// The matched pattern, if anyPatternstring// The message data.Data []byte}

Message represents a message notification.

typePong

type Pong struct {Datastring}

Pong represents a pubsub pong notification.

typePool

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)// DialContext is an application supplied function for creating and configuring a// connection with the given context.//// The connection returned from DialContext must not be in a special state// (subscribed to pubsub channel, transaction started, ...).DialContext func(ctxcontext.Context) (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 lastUsed is the time when the connection was returned// to the pool. If the function returns an error, then the connection is// closed.TestOnBorrow func(cConn, lastUsedtime.Time)error// TestOnBorrowContext is an optional application supplied function// for checking the health of an idle connection with the given context// before the connection is used again by the application.// Argument lastUsed is the time when the connection was returned// to the pool. If the function returns an error, then the connection is// closed.TestOnBorrowContext func(ctxcontext.Context, cConn, lastUsedtime.Time)error// Maximum number of idle connections in the pool.MaxIdleint// 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.MaxActiveint// 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.IdleTimeouttime.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.Waitbool// Close connections older than this duration. If the value is zero, then// the pool does not close connections based on age.MaxConnLifetimetime.Duration// contains filtered or unexported fields}

Pool maintains a pool of connections. The application calls the Get methodto get a connection from the pool and the connection's Close method toreturn the connection's resources to the pool.

The following example shows how to use a pool in a web application. Theapplication creates a pool at application startup and makes it available torequest handlers using a package level variable. The pool configuration usedhere is an example, not a recommendation.

func newPool(addr string) *redis.Pool {  return &redis.Pool{    MaxIdle: 3,    IdleTimeout: 240 * time.Second,    // Dial or DialContext must be set. When both are set, DialContext takes precedence over Dial.    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 connectionwhen 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 orselect 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 connectionbefore the connection is returned to the application. This example PINGsconnections 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  },}

funcNewPooldeprecated

func NewPool(newFn func() (Conn,error), maxIdleint) *Pool

NewPool creates a new pool.

Deprecated: Initialize the Pool directly as shown in the example.

func (*Pool)ActiveCount

func (p *Pool) ActiveCount()int

ActiveCount returns the number of connections in the pool. The countincludes idle connections and connections in use.

func (*Pool)Close

func (p *Pool) Close()error

Close releases the resources used by the pool.

func (*Pool)Get

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 defererror handling to the first use of the connection. If there is an errorgetting an underlying connection, then the connection Err, Do, Send, Flushand Receive methods return that error.

func (*Pool)GetContext

func (p *Pool) GetContext(ctxcontext.Context) (Conn,error)

GetContext gets a connection using the provided context.

The provided Context must be non-nil. If the context expires before theconnection is complete, an error is returned. Any expiration on the contextwill not affect the returned connection.

If the function completes without error, then the application must close thereturned connection.

func (*Pool)IdleCount

func (p *Pool) IdleCount()int

IdleCount returns the number of idle connections in the pool.

func (*Pool)Stats

func (p *Pool) Stats()PoolStats

Stats returns pool's statistics.

typePoolStats

type PoolStats struct {// ActiveCount is the number of connections in the pool. The count includes// idle connections and connections in use.ActiveCountint// IdleCount is the number of idle connections in the pool.IdleCountint// WaitCount is the total number of connections waited for.// This value is currently not guaranteed to be 100% accurate.WaitCountint64// WaitDuration is the total time blocked waiting for a new connection.// This value is currently not guaranteed to be 100% accurate.WaitDurationtime.Duration}

PoolStats contains pool statistics.

typePubSubConn

type PubSubConn struct {ConnConn}

PubSubConn wraps a Conn with convenience methods for subscribers.

Example

This example shows how receive pubsub notifications with cancelation andhealth checks.

//go:build go1.7// +build go1.7package mainimport ("context""fmt""time""github.com/gomodule/redigo/redis")// listenPubSubChannels listens for messages on Redis pubsub channels. The// onStart function is called after the channels are subscribed. The onMessage// function is called for each message.func listenPubSubChannels(ctx context.Context, redisServerAddr string,onStart func() error,onMessage func(channel string, data []byte) error,channels ...string) error {// A ping is set to the server with this period to test for the health of// the connection and server.const healthCheckPeriod = time.Minutec, err := redis.Dial("tcp", redisServerAddr,// Read timeout on server should be greater than ping period.redis.DialReadTimeout(healthCheckPeriod+10*time.Second),redis.DialWriteTimeout(10*time.Second))if err != nil {return err}defer c.Close()psc := redis.PubSubConn{Conn: c}if err := psc.Subscribe(redis.Args{}.AddFlat(channels)...); err != nil {return err}done := make(chan error, 1)// Start a goroutine to receive notifications from the server.go func() {for {switch n := psc.Receive().(type) {case error:done <- nreturncase redis.Message:if err := onMessage(n.Channel, n.Data); err != nil {done <- errreturn}case redis.Subscription:switch n.Count {case len(channels):// Notify application when all channels are subscribed.if err := onStart(); err != nil {done <- errreturn}case 0:// Return from the goroutine when all channels are unsubscribed.done <- nilreturn}}}}()ticker := time.NewTicker(healthCheckPeriod)defer ticker.Stop()loop:for {select {case <-ticker.C:// Send ping to test health of connection and server. If// corresponding pong is not received, then receive on the// connection will timeout and the receive goroutine will exit.if err = psc.Ping(""); err != nil {break loop}case <-ctx.Done():break loopcase err := <-done:// Return error from the receive goroutine.return err}}// Signal the receiving goroutine to exit by unsubscribing from all channels.if err := psc.Unsubscribe(); err != nil {return err}// Wait for goroutine to complete.return <-done}func publish() {c, err := dial()if err != nil {fmt.Println(err)return}defer c.Close()if _, err = c.Do("PUBLISH", "c1", "hello"); err != nil {fmt.Println(err)return}if _, err = c.Do("PUBLISH", "c2", "world"); err != nil {fmt.Println(err)return}if _, err = c.Do("PUBLISH", "c1", "goodbye"); err != nil {fmt.Println(err)return}}// This example shows how receive pubsub notifications with cancelation and// health checks.func main() {redisServerAddr, err := serverAddr()if err != nil {fmt.Println(err)return}ctx, cancel := context.WithCancel(context.Background())err = listenPubSubChannels(ctx,redisServerAddr,func() error {// The start callback is a good place to backfill missed// notifications. For the purpose of this example, a goroutine is// started to send notifications.go publish()return nil},func(channel string, message []byte) error {fmt.Printf("channel: %s, message: %s\n", channel, message)// For the purpose of this example, cancel the listener's context// after receiving last message sent by publish().if string(message) == "goodbye" {cancel()}return nil},"c1", "c2")if err != nil {fmt.Println(err)return}}
Output:channel: c1, message: hellochannel: c2, message: worldchannel: c1, message: goodbye

func (PubSubConn)Close

func (cPubSubConn) Close()error

Close closes the connection.

func (PubSubConn)PSubscribe

func (cPubSubConn) PSubscribe(channel ...interface{})error

PSubscribe subscribes the connection to the given patterns.

func (PubSubConn)PUnsubscribe

func (cPubSubConn) PUnsubscribe(channel ...interface{})error

PUnsubscribe unsubscribes the connection from the given patterns, or from allof them if none is given.

func (PubSubConn)Ping

func (cPubSubConn) Ping(datastring)error

Ping sends a PING to the server with the specified data.

The connection must be subscribed to at least one channel or pattern whencalling this method.

func (PubSubConn)Receive

func (cPubSubConn) 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 asillustrated in the PubSubConn example.

func (PubSubConn)ReceiveContextadded inv1.8.9

func (cPubSubConn) ReceiveContext(ctxcontext.Context) interface{}

ReceiveContext is like Receive, but it allows termination of the receivevia a Context. If the call returns due to closure of the context's Donechannel the underlying Conn will have been closed.

func (PubSubConn)ReceiveWithTimeout

func (cPubSubConn) ReceiveWithTimeout(timeouttime.Duration) interface{}

ReceiveWithTimeout is like Receive, but it allows the application tooverride the connection's default timeout.

func (PubSubConn)Subscribe

func (cPubSubConn) Subscribe(channel ...interface{})error

Subscribe subscribes the connection to the specified channels.

func (PubSubConn)Unsubscribe

func (cPubSubConn) Unsubscribe(channel ...interface{})error

Unsubscribe unsubscribes the connection from the given channels, or from allof them if none is given.

typeScanner

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}

Scanner is implemented by an object which wants to control its value isinterpreted when read from Redis.

typeScript

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

Script encapsulates the source, hash and key count for a Lua script. Seehttp://redis.io/commands/eval for information on scripts in Redis.

Example
package mainimport ("github.com/gomodule/redigo/redis")var (c     redis.Connreply interface{}err   error)func main() {// Initialize a package-level variable with a script.var getScript = redis.NewScript(1, `return redis.call('get', KEYS[1])`)// In a function, use the script Do method to evaluate the script. The Do// method optimistically uses the EVALSHA command. If the script is not// loaded, then the Do method falls back to the EVAL command.reply, err = getScript.Do(c, "foo")}

funcNewScript

func NewScript(keyCountint, srcstring) *Script

NewScript returns a new script object. If keyCount is greater than or equalto zero, then the count is automatically inserted in the EVAL commandargument list. If keyCount is less than zero, then the application suppliesthe count as the first value in the keysAndArgs argument to the Do, Send andSendHash methods.

func (*Script)Do

func (s *Script) Do(cConn, keysAndArgs ...interface{}) (interface{},error)

Do evaluates the script. Under the covers, Do optimistically evaluates thescript using the EVALSHA command. If the command fails because the script isnot loaded, then Do evaluates the script using the EVAL command (thuscausing the script to load).

func (*Script)DoContextadded inv1.8.6

func (s *Script) DoContext(ctxcontext.Context, cConn, keysAndArgs ...interface{}) (interface{},error)

func (*Script)Hash

func (s *Script) Hash()string

Hash returns the script hash.

func (*Script)Load

func (s *Script) Load(cConn)error

Load loads the script without evaluating it.

func (*Script)Send

func (s *Script) Send(cConn, keysAndArgs ...interface{})error

Send evaluates the script without waiting for the reply.

func (*Script)SendHash

func (s *Script) SendHash(cConn, keysAndArgs ...interface{})error

SendHash evaluates the script without waiting for the reply. The script isevaluated with the EVALSHA command. The application must ensure that thescript is loaded by a previous call to Send, Do or Load methods.

typeSlowLogadded inv1.7.2

type SlowLog struct {// ID is a unique progressive identifier for every slow log entry.IDint64// Time is the unix timestamp at which the logged command was processed.Timetime.Time// ExecutationTime is the amount of time needed for the command execution.ExecutionTimetime.Duration// Args is the command name and argumentsArgs []string// ClientAddr is the client IP address (4.0 only).ClientAddrstring// ClientName is the name set via the CLIENT SETNAME command (4.0 only).ClientNamestring}

SlowLog represents a redis SlowLog

funcSlowLogsadded inv1.7.2

func SlowLogs(result interface{}, errerror) ([]SlowLog,error)

SlowLogs is a helper that parse the SLOWLOG GET command output andreturn the array of SlowLog

typeSubscription

type Subscription struct {// Kind is "subscribe", "unsubscribe", "psubscribe" or "punsubscribe"Kindstring// The channel that was changed.Channelstring// The current number of subscriptions for connection.Countint}

Subscription represents a subscribe or unsubscribe notification.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2026 Movatter.jp