前言
通过redigo连接redis,以后有时间的话搞搞go-redis.
参考
https://github.com/go-redis/redis
https://github.com/gomodule/redigo
func
func Dial
1 | 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.
Connect to local instance of Redis running on the default port.
Code:
1 | c, err := redis.Dial("tcp", ":6379") |
Connect to an Redis instance using the Redis ACL system
Code:
1 | c, err := redis.Dial("tcp", "localhost:6379", |
func DialTimeout
1 | 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 NewConn
1 | func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn |
NewConn returns a new Redigo connection for the given net connection.
func do
1 | Do(commandName string, args ...interface{}) (reply interface{}, err error) |
The Do method converts command arguments to bulk strings for transmission to the server as follows:
Go Type Conversion
[]byte Sent as is
string Sent as is
int, 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 type
error redis.Error
integer int64
simple string string
bulk string []byte or nil if value not present.
array []interface{} or nil if value not present.
func bytes
1 | 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 ByteSlices
1 | 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 Bool
1 | 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
demo
1 | package main |
pipeline
1 | if _, err = cache.Do("SET", "key2", 1); err != nil { |
通过Do的get返回的interface{}需要转换成切片再转成数字,receive返回的直接就是interface{}->int64了,这个后面再看下原因。
这里主要的点是连续作业,send+flush+receive或者send+do,do相当于flush+receive了。也可以DO(“”)来flush然后取上一条命令的结果。