连接到 Redis 服务器
使用 go-redis 库连接 Redis 服务器有两种常见方式。
第一种是直接通过 redis.Options 结构体进行配置:
import "github.com/redis/go-redis/v9"
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // 没有密码,默认值
DB: 0, // 默认 DB 0
})
此外,也支持通过连接字符串进行配置,这种方式在某些部署环境下更为便捷:
opt, err := redis.ParseURL("redis://<user>:<pass>@localhost:6379/<db>")
if err != nil {
panic(err)
}
rdb := redis.NewClient(opt)
发布/订阅
go-redis 库完整支持 Redis 的发布/订阅(Pub/Sub)模式。该库具备自动重连机制,当发生网络异常等问题时,会自动尝试重新连接服务器,提升了健壮性。
注意: PubSub 对象会长时间占用连接池中的一个网络连接,使用时需留意连接管理。
发布一条消息
发布消息到指定频道非常简单,只需调用 Publish 方法:
err := rdb.Publish(ctx, "mychannel1", "payload").Err()
if err != nil {
panic(err)
}
订阅一个频道
订阅频道使用 Subscribe 方法。该方法调用时不会立即返回错误,任何连接或订阅错误将在后续读取消息时返回。务必在使用完毕后关闭 PubSub 对象以释放连接资源。
pubsub := rdb.Subscribe(ctx, "mychannel1")
// 使用完毕,记得关闭
defer pubsub.Close()
读取消息
有两种主要方式从订阅中读取消息。
方式一:使用 ReceiveMessage 方法循环读取
for {
msg, err := pubsub.ReceiveMessage(ctx)
if err != nil {
panic(err)
}
fmt.Println(msg.Channel, msg.Payload)
}
方式二:通过 Channel 方法转换为 Go 管道进行消费
这种方式更符合 Go 语言的并发编程习惯,可以方便地配合 select 语句使用。
ch := pubsub.Channel()
for msg := range ch {
fmt.Println(msg.Channel, msg.Payload)
}