Go 使用三方 Redis 包操作 Redis

简介: Go 使用三方 Redis 包操作 Redis

01

概念


Redis 是一个基于内存的非关系型数据库,在项目开发中使用非常广泛,Go 语言操作 Redis 需要使用三方包,我们选择支持 Redis 集群和 Redis 哨兵的 go-redis 包来讲述 Go 语言如何操作 Redis。


go-redis 包需要使用支持 Modules 的 Go 版本,并且使用导入版本控制。所以需要确保初始化 go module,命令如下所示。


初始化


go mod init package_name


安装 go-redis


go get github.com/go-redis/redis/v8


02

Redis 单机


Redis 单机连接

方式 1:

rdb := redis.NewClient(&redis.Options{
    Addr:     "localhost:6379",
    Password: "", // no password set
    DB:       0,  // use default DB
})


go-redis 包提供 NewClient 函数,传入一个指定 Redis 服务器信息的结构体类型的参数,返回一个指向该 Redis 服务器的客户端  *Client。


查看传入参数的结构体完整字段:


type Options struct {
    Network            string
    Addr               string
    Dialer             func(ctx context.Context, network string, addr string) (net.Conn, error)
    OnConnect          func(ctx context.Context, cn *Conn) error
    Username           string
    Password           string
    DB                 int
    MaxRetries         int
    MinRetryBackoff    time.Duration
    MaxRetryBackoff    time.Duration
    DialTimeout        time.Duration
    ReadTimeout        time.Duration
    WriteTimeout       time.Duration
    PoolSize           int
    MinIdleConns       int
    MaxConnAge         time.Duration
    PoolTimeout        time.Duration
    IdleTimeout        time.Duration
    IdleCheckFrequency time.Duration
    readOnly           bool
    TLSConfig          *tls.Config
    Limiter            Limiter
}


方式 2:


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


go-redis 包提供 ParseURL 函数,传入参数为字符串类型的连接字符串,返回一个 NewClient 函数接收的参数 *Options。


02

Redis 集群


Redis 集群连接


rdb := redis.NewClusterClient(&redis.ClusterOptions{
    Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
    // To route commands by latency or randomly, enable one of the following.
    //RouteByLatency: true,
    //RouteRandomly: true,
})


go-redis 包提供 NewClusterClient 函数,传入一个指定 Redis 集群服务器信息的结构体类型的参数,返回一个 Redis 集群的客户端 *ClusterClient。


查看传入参数结构体的完整字段:


type ClusterOptions struct {
    Addrs              []string
    NewClient          func(opt *Options) *Client
    MaxRedirects       int
    ReadOnly           bool
    RouteByLatency     bool
    RouteRandomly      bool
    ClusterSlots       func(context.Context) ([]ClusterSlot, error)
    Dialer             func(ctx context.Context, network string, addr string) (net.Conn, error)
    OnConnect          func(ctx context.Context, cn *Conn) error
    Username           string
    Password           string
    MaxRetries         int
    MinRetryBackoff    time.Duration
    MaxRetryBackoff    time.Duration
    DialTimeout        time.Duration
    ReadTimeout        time.Duration
    WriteTimeout       time.Duration
    PoolSize           int
    MinIdleConns       int
    MaxConnAge         time.Duration
    PoolTimeout        time.Duration
    IdleTimeout        time.Duration
    IdleCheckFrequency time.Duration
    TLSConfig          *tls.Config
}


03

Redis 哨兵


Redis 哨兵模式连接


rdb := redis.NewFailoverClient(&redis.FailoverOptions{
    MasterName:    "master-name",
    SentinelAddrs: []string{":9126", ":9127", ":9128"},
})


使用 NewFailoverClusterClient 函数可以将只读命令路由到从 Redis 服务器。


rdb := redis.NewFailoverClusterClient(&redis.FailoverOptions{
    MasterName:    "master-name",
    SentinelAddrs: []string{":9126", ":9127", ":9128"},
    // To route commands by latency or randomly, enable one of the following.
    //RouteByLatency: true,
    //RouteRandomly: true,
})


连接 Redis 哨兵服务器


sentinel := redis.NewSentinelClient(&redis.Options{
    Addr: ":9126",
})
addr, err := sentinel.GetMasterAddrByName(ctx, "master-name").Result()


04

Redis 命令


执行 Redis 命令

方式 1:直接获取结果集


var ctx = context.Background()
val, err := rdb.Get(ctx, "key").Result()
if err != nil {
    if err == redis.Nil {
        fmt.Println("key does not exists")
        return
    }
    panic(err)
}
fmt.Println(val)


方式 2:单独访问 Err() 和 Val() 获取相应的值。


var ctx = context.Background()
get := rdb.Get(ctx, "key")
if err := get.Err(); err != nil {
    if err == redis.Nil {
        fmt.Println("key does not exists")
        return
    }
    panic(err)
}
fmt.Println(get.Val())


方式 3:执行任意命令


var ctx = context.Background()
get := rdb.Do(ctx, "get", "key")
if err := get.Err(); err != nil {
    if err == redis.Nil {
        fmt.Println("key does not exists")
        return
    }
    panic(err)
}
fmt.Println(get.Val().(string))


更多特定类型的取值方法:


// Shortcut for get.Val().(string) with error handling.
s, err := get.Text()
num, err := get.Int()
num, err := get.Int64()
num, err := get.Uint64()
num, err := get.Float32()
num, err := get.Float64()
flag, err := get.Bool()

需要注意的是,第一个参数需要传入 context.Context 类型的参数,作为传入请求的顶级上下文。





目录
相关文章
|
Go 开发者
Go语言包的组织与导入 -《Go语言实战指南》
本章详细介绍了Go语言中的包(Package)概念及其使用方法。包是实现代码模块化、复用性和可维护性的核心单位,内容涵盖包的基本定义、命名规则、组织结构以及导入方式。通过示例说明了如何创建和调用包,并深入讲解了`go.mod`文件对包路径的管理。此外,还提供了多种导入技巧,如别名导入、匿名导入等,帮助开发者优化代码结构与可读性。最后以表格形式总结了关键点,便于快速回顾和应用。
655 61
|
消息中间件 缓存 NoSQL
Redis各类数据结构详细介绍及其在Go语言Gin框架下实践应用
这只是利用Go语言和Gin框架与Redis交互最基础部分展示;根据具体业务需求可能需要更复杂查询、事务处理或订阅发布功能实现更多高级特性应用场景。
748 86
|
JSON 中间件 Go
Go语言实战指南 —— Go中的反射机制:reflect 包使用
Go语言中的反射机制通过`reflect`包实现,允许程序在运行时动态检查变量类型、获取或设置值、调用方法等。它适用于初中级开发者深入理解Go的动态能力,帮助构建通用工具、中间件和ORM系统等。
1031 63
|
Java 编译器 Go
【Golang】(1)Go的运行流程步骤与包的概念
初次上手Go语言!先来了解它的运行流程吧! 在Go中对包的概念又有怎样不同的见解呢?
647 4
|
Go 持续交付 开发者
Go语言包与模块(module)的基本使用-《Go语言实战指南》
本章深入讲解Go语言中的包(Package)和模块(Module)概念。包是代码组织的最小单位,每个`.go`文件属于一个包,通过`import`实现复用;主程序包需命名为`main`。模块是Go 1.11引入的依赖管理机制,支持自动版本管理和私有/远程仓库,无需依赖GOPATH。通过实际示例,如自定义包`mathutil`和第三方模块`gin`的引入,展示其使用方法。常用命令包括`go mod init`、`go mod tidy`等,帮助开发者高效管理项目依赖。最后总结,包负责功能划分,模块实现现代化依赖管理,提升团队协作效率。
637 15
|
缓存 监控 安全
告别缓存击穿!Go 语言中的防并发神器:singleflight 包深度解析
在高并发场景中,多个请求同时访问同一资源易导致缓存击穿、数据库压力过大。Go 语言提供的 `singleflight` 包可将相同 key 的请求合并,仅执行一次实际操作,其余请求共享结果,有效降低系统负载。本文详解其原理、实现及典型应用场景,并附示例代码,助你掌握高并发优化技巧。
1021 0
|
Linux Go iOS开发
怎么禁用 vscode 中点击 go 包名时自动打开浏览器跳转到 pkg.go.dev
本文介绍了如何在 VSCode 中禁用点击 Go 包名时自动打开浏览器跳转到 pkg.go.dev 的功能。通过将 gopls 的 `ui.navigation.importShortcut` 设置为 &quot;Definition&quot;,可以实现仅跳转到定义处而不打开链接。具体操作步骤包括:打开设置、搜索 gopls、编辑 settings.json 文件并保存更改,最后重启 VSCode 使设置生效。
1082 9
怎么禁用 vscode 中点击 go 包名时自动打开浏览器跳转到 pkg.go.dev
|
Go 数据库
Go语言中的包(package)是如何组织的?
在Go语言中,包是代码组织和管理的基本单元,用于集合相关函数、类型和变量,便于复用和维护。包通过目录结构、文件命名、初始化函数(`init`)及导出规则来管理命名空间和依赖关系。合理的包组织能提高代码的可读性、可维护性和可复用性,减少耦合度。例如,`stringutils`包提供字符串处理函数,主程序导入使用这些函数,使代码结构清晰易懂。
656 11
|
Go 索引
go语言使用strings包
go语言使用strings包
516 3
|
编译器 Go 开发者
go语言中导入相关包
【11月更文挑战第1天】
358 3

热门文章

最新文章