go-redis 指南 (Go)
将 Go 应用程序连接到 Redis 数据库
go-redis
是 Redis 的 Go 客户端。
以下部分介绍了如何安装go-redis
并将您的应用程序连接到 Redis 数据库。
go-redis
需要正在运行的 Redis 或 Redis Stack 服务器。
请参阅 Redis 安装入门
指示。
安装
go-redis
支持最后两个 Go 版本。您只能从内部使用它
Go 模块,因此您必须在开始之前初始化 Go 模块,或将代码添加到
现有模块:
go mod init github.com/my/repo
使用go get
命令进行安装go-redis/v9
:
go get github.com/redis/go-redis/v9
连接
以下示例显示了连接到 Redis 服务器的最简单方法:
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // No password set
DB: 0, // Use default DB
Protocol: 2, // Connection protocol
})
}
You can also connect using a connection string:
opt, err := redis.ParseURL("redis://<user>:<pass>@localhost:6379/<db>")
if err != nil {
panic(err)
}
client := redis.NewClient(opt)
After connecting, you can test the connection by storing and retrieving
a simple string:
ctx := context.Background()
err := client.Set(ctx, "foo", "bar", 0).Err()
if err != nil {
panic(err)
}
val, err := client.Get(ctx, "foo").Result()
if err != nil {
panic(err)
}
fmt.Println("foo", val)
You can also easily store and retrieve a hash:
hashFields := []string{
"model", "Deimos",
"brand", "Ergonom",
"type", "Enduro bikes",
"price", "4972",
}
res1, err := client.HSet(ctx, "bike:1", hashFields).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> 4
res2, err := client.HGet(ctx, "bike:1", "model").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> Deimos
res3, err := client.HGet(ctx, "bike:1", "price").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> 4972
res4, err := client.HGetAll(ctx, "bike:1").Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> map[brand:Ergonom model:Deimos price:4972 type:Enduro bikes]
Use
struct tags
of the form redis:"<field-name>"
with the Scan()
method to parse fields from
a hash directly into corresponding struct fields:
type BikeInfo struct {
Model string `redis:"model"`
Brand string `redis:"brand"`
Type string `redis:"type"`
Price int `redis:"price"`
}
var res4a BikeInfo
err = client.HGetAll(ctx, "bike:1").Scan(&res4a)
if err != nil {
panic(err)
}
fmt.Printf("Model: %v, Brand: %v, Type: %v, Price: $%v\n",
res4a.Model, res4a.Brand, res4a.Type, res4a.Price)
// >>> Model: Deimos, Brand: Ergonom, Type: Enduro bikes, Price: $4972
Observability
go-redis
supports OpenTelemetry instrumentation.
to monitor performance and trace the execution of Redis commands.
For example, the following code instruments Redis commands to collect traces, logs, and metrics:
import (
"github.com/redis/go-redis/v9"
"github.com/redis/go-redis/extra/redisotel/v9"
)
client := redis.NewClient(&redis.Options{...})
// Enable tracing instrumentation.
if err := redisotel.InstrumentTracing(client); err != nil {
panic(err)
}
// Enable metrics instrumentation.
if err := redisotel.InstrumentMetrics(client); err != nil {
panic(err)
}
See the go-redis
GitHub repo.
for more OpenTelemetry examples.
More information
See the other pages in this section for more information and examples.
Further examples are available at the go-redis
website
and the GitHub repository.
On this page