首页 > 数据库 >golang之Redis

golang之Redis

时间:2022-08-15 20:36:19浏览次数:77  
标签:string err Redis redis golang time Duration

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

 

 

 

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。

 

 


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
}

 

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

 

 

执行 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 类型的参数,作为传入请求的顶级上下文。

 

 

相关文档:

 

标签:string,err,Redis,redis,golang,time,Duration
From: https://www.cnblogs.com/xingxia/p/golang_redis.html

相关文章

  • golang之jwt的token登录
    什么是JSONWebToken?JSONWebToken(JWT)是一个开放标准(RFC7519),它定义了一种紧凑且自包含的方式,用于在各方之间以JSON方式安全地传输信息。由于此信息是经过数字签名的......
  • python连接mysql与redis(ssh方式)
    python如何连接数据库(SSH方式)性能测试时,有个支付订单的场景,需要用到已生成的订单code,如何获取订单code?一,通过Jmeter连接数据库获取。二,直接mysql导出数据我这里是使用......
  • nodejs环境下使用redis(基础入门)
    redis-server--service-start 启动redis服务winptyredis-cli进入redis-cli,可查看存入的数据redis环境配好之后,先[email protected]安装nodejs环境下的redis库......
  • Golang框架之gin
    gin是目前golang的主要web框架之一,之所以选择这个框架是因为其拥有高效的路由性能,并且有人长期维护,目前github上的star数已经破3W。 ......
  • golang 企业转账到零钱
    packagemainimport("bytes""crypto/md5""crypto/tls""encoding/hex""encoding/xml""fmt""io/ioutil""net/http""net/u......
  • Linux安装Redis服务
    一、安装1、进入linux系统,选择下载的目录,输入命令“wgethttp://download.redis.io/releases/redis-5.0.5.tar.gz” 2、解压下载的压缩包“tarxzfredis-5.0.5.tar.g......
  • golang 实现生产者消费者模式(转)
    方法一:用两个通道+A协程sleep一个通道用来传数据,一个用来传停止信号。packagemainimport( "fmt" "time")//老师视频里的生产者消费者funcmain(){ //......
  • golang超时控制(转)
    Go实现超时退出之前手写rpc框架的时候,吃多了网络超时处理的苦,今天偶然发现了实现超时退出的方法,MARKfuncAsyncCall(){ ctx,cancel:=context.WithTimeout(context.......
  • redis五种数据类型及使用场景(转载)
    (19条消息)【Redis】五种数据类型及其使用场景_编程芝士的博客-CSDN博客_redis有几种数据类型......
  • redis 和docker等名词了解
    redisredis产生redis是MySQL数据库经常直接面对大量的读写访问,面对比较复杂的数据据操作,会导致数据库I/O反映缓慢或者奔溃;有人研究学习CPU从内寸直接读取数据,把MYSQL经......