Golang连接Redis
使用 Golang 开发的一大直观感受就是,基本上你日常遇到的开发问题,都有官方或者第三方包帮你辅助实现,同时这些包都是开源的,只要你感兴趣,都可以深入到包的内部实现去学习理解包的实现思路和方法。当然这也有利有弊,第三包的不稳定和质量参差不齐也增加了一些开发成本,目前还是感受利大于弊。研究好的包源码实现,也是目前我的一个学习方向。
garyburd/redigo 包简介
garyburd/redigo 包是网上很多博文都在推荐使用的一个高Star的 Redis 连接包,但是当我自己去 Github 的项目地址 garyburd/redigo 上查看 API 时,发现这个项目目前是归档状态,项目已经迁移到了 gomodule/redigo ,同时包的获取也理所当然地改成了 go get github.com/gomodule/redigo/redis ,这已经不是我第一次感受了第三方包的不稳定,之前用 dep 进行包管理时,就遇到过 dep 拉取的包版本和本地包版本 API 冲突的问题,这个有时间单独再说。总之,暂时不管这两个包的详细区别,以下就以新包为准,介绍下 redigo 包使用。
建立连接池
Redigo Pool 结构维护一个 Redis 连接池。应用程序调用 Get 方法从池中获取连接,并使用连接的 Close 方法将连接的资源返回到池中。一般我们在系统初始化时声明一个全局连接池,然后在需要操作 redis 时获得连接,执行指令。
pool := &redis.Pool{
MaxIdle: 3, /*最大的空闲连接数*/
MaxActive: 8, /*最大的激活连接数*/
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", '链接地址,例如127.0.0.1:6379', redis.DialPassword('密码'))
if err != nil {
return nil, err
}
return c, nil
}
}
c:=pool.Get()
defer c.Close()
执行指令
查看源码,发现 Conn 接口有一个执行 Redis 命令的通用方法:
```
//gomodule/redigo/redis/redis.go
// 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)
}
```
http://redis.io/commands 中的 Redis 命令参考列出了可用的命令。 do 的参数和 redis-cli 命令参数格式一致,比如 SET key value EX 360 对应函数调用为 Do("SET", "key", "value","EX",360)









