Redis Connections

Overview

This section focuses on the case of redis creating a single node.

Preparing

  1. Complete golang installation
  2. Prepare for yourself a redis server, for example we use 127.0.0.1:6379.

redis configuration description

RedisConf related introduction.

  1. RedisConf struct {
  2. Host string
  3. Type string `json:",default=node,options=node|cluster"`
  4. Pass string `json:",optional"`
  5. Tls bool `json:",optional"`
  6. }
  7. Host: redis service address :port, if redis cluster is ip1:port1,ip2:port2,ip3:port3. .(redis is not supported)
  8. Type: node single nodes redis, cluster reced
  9. Pass: password
  10. Tls: Turn on tls:

Initialize redis configuration, we recommend loading using conf.MustLoad for configurations, referenceconfiguration profiles

  1. conf := redis.RedisConf{
  2. Host: "127.0.0.1:6379",
  3. Type: "node",
  4. Pass: "123456",
  5. Tls: false,
  6. }

Create redis instance

Create a redis link using MustNewRedis.

  1. conf := redis.RedisConf{
  2. Host: "127.0.0.1:6379",
  3. Type: "node",
  4. Pass: "123456",
  5. Tls: false,
  6. }
  7. rds := redis.MustNewRedis(conf)

This way we have finished creating an instance of rds.

redis Usage

String values are associated to key and extracted from redis.

  1. ctx := context.Background()
  2. err := rds.SetCtx(ctx, "key", "hello world")
  3. if err != nil {
  4. logc.Error(ctx, err)
  5. }
  6. v, err := rds.GetCtx(ctx, "key")
  7. if err != nil {
  8. logc.Error(ctx, err)
  9. }
  10. fmt.Println(v)

Full examples below

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "github.com/zeromicro/go-zero/core/logc"
  7. "github.com/zeromicro/go-zero/core/stores/redis"
  8. )
  9. func main() {
  10. conf := redis.RedisConf{
  11. Host: "127.0.0.1:6379",
  12. Type: "node",
  13. Pass: "",
  14. Tls: false,
  15. NonBlock: false,
  16. PingTimeout: time.Second,
  17. }
  18. rds := redis.MustNewRedis(conf)
  19. ctx := context.Background()
  20. err := rds.SetCtx(ctx, "key", "hello world")
  21. if err != nil {
  22. logc.Error(ctx, err)
  23. }
  24. v, err := rds.GetCtx(ctx, "key")
  25. if err != nil {
  26. logc.Error(ctx, err)
  27. }
  28. fmt.Println(v)
  29. }