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 類型的參數,作為傳入請求的頂級上下文。
相關文檔:
- https://pkg.go.dev/github.com/go-redis/redis/v8#section-readme