1. redis 官方go驱动包下载
go get github.com/gomodule/redigo/redis
2. 测试
创建如下test.go测试文件,编译并执行。在redis中查找到键c1值为hello,说明安装成功
package main
import ( "github.com/gomodule/redigo/redis")
func main(){
conn,_ := redis.Dial("tcp", ":6379")
defer conn.Close()
conn.Do("set", "c1", "hello")
}
备注: 此处默认设置ip及端口号为127.0.0.1 和 6379,可手动设置下代码中的ip及port 。
conn,_ := redis.Dial("tcp", "ip:port")
3. 操作指令
Go操作redis文档https://godoc.org/github.com/gomodule/redigo/redis
3.1连接数据库
Dial(network, address string)(conn,err)
3.2 执行数据库操作命令
Send函数发出指令,flush将连接的输出缓冲区刷新到服务器,Receive接收服务器返回的数据
Send(commandName string, args ...interface{}) error
Flush() error
Receive() (reply interface{}, err error)
3.3另外一种执行数据库操作命令
Do(commandName string, args ...interface{}) (reply interface{}, err error)
3.4 reply helper functions(回复助手函数)
Bool,Int,Bytes,map,String,Strings和Values函数将回复转换为特定类型的值。为了方便地包含对连接Do和Receive方法的调用,这些函数采用了类型为error的第二个参数。如果错误是非nil,则辅助函数返回错误。如果错误为nil,则该函数将回复转换为指定的类型:
exists, err := redis.Bool(c.Do("EXISTS", "foo"))
if err != nil {
//处理错误代码
}
reflect.TypeOf(exists)//打印exists类型
常用的回复助手函数
- func Bool(reply interface{}, err error) (bool, error)
- func ByteSlices(reply interface{}, err error) ([][]byte, error)
- func Bytes(reply interface{}, err error) ([]byte, error)
- func DoWithTimeout(c Conn, timeout time.Duration, cmd string, args ...interface{}) (interface{}, error)
- func Float64(reply interface{}, err error) (float64, error)
- func Float64s(reply interface{}, err error) ([]float64, error)
- func Int(reply interface{}, err error) (int, error)
- func Int64(reply interface{}, err error) (int64, error)
- func Int64Map(result interface{}, err error) (map[string]int64, error)
- func Int64s(reply interface{}, err error) ([]int64, error)
- func IntMap(result interface{}, err error) (map[string]int, error)
- func Ints(reply interface{}, err error) ([]int, error)
3.5 Scan 函数
Scan函数从src复制到dest指向的值。
Dest参数的值必须是整数,浮点数,布尔值,字符串,[]byte,interface{}或这些类型的切片。Scan使用标准的strconv包将批量字符串转换为数字和布尔类型。
func Scan(src [] interface {},dest ... interface {})([] interface {},error)
示例代码:
var value1 int
var value2 string
reply, err := redis.Values(c.Do("MGET", "key1", "key2"))
if err != nil {
//处理错误代码
}
if _, err := redis.Scan(reply, &value1, &value2); err != nil {
// 处理错误代码
}
网友评论