redigo可以为Go提供操作Redis的API,其本质和手动在”redis-cli”是一样的,只是提供了一些方便的功能。
类似redigo的还有go-redis,与redigo相比封装的更细致一点,但是本质是相同的。
安装redigo
执行下载包命令
1 |
|
执行一下连接测试
1 |
|
正确输出”connect success !”后,说明安装成功。
基本操作示例
1 |
|
- 从上面的操作可以看出,主要使用连接对象的Do函数执行,输入的参数与手动输入的相同。
- 返回后,最好使用redis.String转换一下,这样能保证非ASCII也能正常显示。
发送与接收时的自动类型转换
- Do函数发送命令时会必要时将参数转化为二进制字符串:
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.Print(v) |
- 命令执行结果返回后会用下面Go类型表示:
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. |