Go&Redis

一、redigo 

  Go官方推荐使用的Redis客户端

  https://github.com/gomodule/redigo

  文档:https://pkg.go.dev/github.com/gomodule/redigo#readme-documentation

  1、安装

    go get github.com/gomodule/redigo/redis

(base) ➜  go_study git:(master) ✗ go get github.com/gomodule/redigo/redis
go: downloading github.com/gomodule/redigo v1.8.6
go: downloading github.com/gomodule/redigo/redis v0.0.0-do-not-use

  2、创建连接

    redigo提供了多个函数创建连接,如:Dial函数,DialURL函数和NewConn函数,以Dial函数为例

import (
    "fmt"
    "github.com/gomodule/redigo/redis"
)

func connect() {
    // 连接 redis-server
    // 创建连接
    con, err := redis.Dial("tcp", "localhost:6379")
    if err != nil {
        fmt.Printf("redis.Dial() error:%v", err)
        return
    }
    // 操作 con.Do()

    // 操作完成后关闭连接
    defer con.Close()
}

    注意:在生产环境应使用连接池,避免每次执行命令都需要先创建连接,影响性能

 

  3、连接池

import (
    "fmt"
    "github.com/gomodule/redigo/redis"
)

// redis.Pool指针
var pool *redis.Pool

// 包初始化时执行
func init() {
    // 实例化连接池
    pool = &redis.Pool{
        MaxIdle:     10,  // 最初的连接数量
        MaxActive:   0,   // 连接池最大连接数量,不确定可以用0(0表示自动定义),按需分配
        IdleTimeout: 300, // 连接关闭时间 300秒 (300秒不使用自动关闭)
        Dial: func() (redis.Conn, error) { //要连接的redis数据库
            return redis.Dial("tcp", "localhost:6379")
        },
    }
}

func main() {
    con := pool.Get() //从连接池,取一个链接
    defer con.Close() //函数运行结束 ,把连接放回连接池

    // 操作 con.Do()
    v, err := redis.String(con.Do("get", "redigo"))
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(v)

}

 

  4、操作数据

    redigo执行Redis命令的通用方法是使用Conn接口的Do函数,Do函数可以发送命令给Redis服务器,并返回Redis服务器的回复

    // Do sends a command to the server and returns the received reply.
    // This function will use the timeout which was set when the connection is created
    Do(commandName string, args ...interface{}) (reply interface{}, err error)

    其中命令的大小写都可以

 

    1)String

      ①:set

    reply, err := con.Do("set", "redigo", "succ")
    if err != nil {
        fmt.Println("SET error: ", err)
    }
    fmt.Println(reply) // OK

 

      ②:get 

    v, err := redis.String(con.Do("get", "redigo"))
    if err != nil {
        fmt.Println(err)
        return
    }

   

  

 

二、go-redis

  go-redis是一个支持Redis集群和Redis哨兵模式的三方包

  源码:https://github.com/go-redis/redis

  官网:https://redis.uptrace.dev/

  文档:https://redis.uptrace.dev/guide/#installation

  1、安装go-redis

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

go mod init project_name

    2)安装 go-redis/v8

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

 

  2、使用示例:

import (
    "context"
    "github.com/go-redis/redis/v8"
)

var ctx = context.Background()

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

    err := rdb.Set(ctx, "key", "value", 0).Err()
    if err != nil {
        panic(err)
    }

    val, err := rdb.Get(ctx, "key").Result()
    if err != nil {
        panic(err)
    }
    fmt.Println("key", val)
}

 

  2、单机

    1)方式1(推荐):

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

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

      redis.Options结构体完整字段:

// Options keeps the settings to setup redis connection.
type Options struct {
    // The network type, either tcp or unix.
    // Default is tcp.
    Network string
    // host:port address.
    Addr string

    // Dialer creates new network connection and has priority over
    // Network and Addr options.
    Dialer func(ctx context.Context, network, addr string) (net.Conn, error)

    // Hook that is called when new connection is established.
    OnConnect func(ctx context.Context, cn *Conn) error

    // Use the specified Username to authenticate the current connection
    // with one of the connections defined in the ACL list when connecting
    // to a Redis 6.0 instance, or greater, that is using the Redis ACL system.
    Username string
    // Optional password. Must match the password specified in the
    // requirepass server configuration option (if connecting to a Redis 5.0 instance, or lower),
    // or the User Password when connecting to a Redis 6.0 instance, or greater,
    // that is using the Redis ACL system.
    Password string

    // Database to be selected after connecting to the server.
    DB int

    // Maximum number of retries before giving up.
    // Default is 3 retries; -1 (not 0) disables retries.
    MaxRetries int
    // Minimum backoff between each retry.
    // Default is 8 milliseconds; -1 disables backoff.
    MinRetryBackoff time.Duration
    // Maximum backoff between each retry.
    // Default is 512 milliseconds; -1 disables backoff.
    MaxRetryBackoff time.Duration

    // Dial timeout for establishing new connections.
    // Default is 5 seconds.
    DialTimeout time.Duration
    // Timeout for socket reads. If reached, commands will fail
    // with a timeout instead of blocking. Use value -1 for no timeout and 0 for default.
    // Default is 3 seconds.
    ReadTimeout time.Duration
    // Timeout for socket writes. If reached, commands will fail
    // with a timeout instead of blocking.
    // Default is ReadTimeout.
    WriteTimeout time.Duration

    // Type of connection pool.
    // true for FIFO pool, false for LIFO pool.
    // Note that fifo has higher overhead compared to lifo.
    PoolFIFO bool
    // Maximum number of socket connections.
    // Default is 10 connections per every available CPU as reported by runtime.GOMAXPROCS.
    PoolSize int
    // Minimum number of idle connections which is useful when establishing
    // new connection is slow.
    MinIdleConns int
    // Connection age at which client retires (closes) the connection.
    // Default is to not close aged connections.
    MaxConnAge time.Duration
    // Amount of time client waits for connection if all connections
    // are busy before returning an error.
    // Default is ReadTimeout + 1 second.
    PoolTimeout time.Duration
    // Amount of time after which client closes idle connections.
    // Should be less than server's timeout.
    // Default is 5 minutes. -1 disables idle timeout check.
    IdleTimeout time.Duration
    // Frequency of idle checks made by idle connections reaper.
    // Default is 1 minute. -1 disables idle connections reaper,
    // but idle connections are still discarded by the client
    // if IdleTimeout is set.
    IdleCheckFrequency time.Duration

    // Enables read only queries on slave nodes.
    readOnly bool

    // TLS Config to use. When set TLS will be negotiated.
    TLSConfig *tls.Config

    // Limiter interface used to implemented circuit breaker or rate limiter.
    Limiter Limiter
}
View Code

 

    2)方式2:

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

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

rdb := redis.NewClient(opt)

 

    完整示例:

package main

import (
    "context"
    "fmt"
    "github.com/go-redis/redis/v8"
)

func main() {
    ctx := context.Background()

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

    // set值
    err := rdb.Set(ctx, "key", "value", 0).Err()
    if err != nil {
        panic(err)
    }

    // get值
    val, err := rdb.Get(ctx, "key").Result()
    if err == redis.Nil {
        fmt.Println("key does not exist")
    } else if err != nil {
        panic(err)
    } else {
        fmt.Println("key", val)
    }
}

 

 

  3、集群

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

rdb := redis.NewClusterClient(&redis.ClusterOptions{
    Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
})

 

  

 

 

END.

posted @ 2021-12-08 23:47  杨岂  阅读(608)  评论(0编辑  收藏  举报