go-redis 指南 (Go)

将 Go 应用程序连接到 Redis 数据库

go-redis 是 Redis 的 Go 客户端。以下部分解释了如何安装 go-redis 并将您的应用程序连接到 Redis 数据库。

go-redis 需要一个正在运行的 Redis 服务器。有关 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
    })
}

您也可以使用连接字符串进行连接

opt, err := redis.ParseURL("redis://<user>:<pass>@localhost:6379/<db>")
if err != nil {
	panic(err)
}

client := redis.NewClient(opt)

连接后,您可以通过存储和检索一个简单的字符串来测试连接。

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)

您还可以轻松存储和检索一个哈希

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]

使用 struct tags,格式为 redis:"<field-name>",配合 Scan() 方法将哈希中的字段直接解析到对应的结构体字段。

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

可观测性

go-redis 支持 OpenTelemetry 检测,用于监控性能和跟踪 Redis 命令的执行。例如,以下代码对 Redis 命令进行检测以收集跟踪、日志和指标。

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)
}

有关更多 OpenTelemetry 示例,请参阅 go-redis GitHub 仓库

更多信息

有关更多信息和示例,请参阅本节中的其他页面。更多示例可在 go-redis 网站和 GitHub 仓库找到。

评价此页面
返回顶部 ↑