在go中可以使用github.com/go-redis/redis来操作Redis

一、安装

现在最新的版本是 v8

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

二、导入包

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

三、连接Redis

使用初始化InitRedis来连接Redis数据库,输入的url参数为格式。如:redis://:123456@127.0.0.1:6379

  • redis://: 协议头,固定格式
  • :前面 :redis无用户,所以为空
  • 123456:redis密码
  • 127.0.0.1: redis ip
  • 6379: redis 端口
var client *redis.Client

// url为redis地址
func InitRedis(url string) (err error) {
	if strings.HasPrefix(url, "redis://") {
		url = url[8:]
	}

	var pwd string
	if c := strings.Index(url, "@"); c != -1 {
		pair := strings.SplitN(url[:c], ":", 2)
		if len(pair) > 1 {
			pwd = pair[1]
		}
		url = url[c+1:]
	}

	client = redis.NewClient(&redis.Options{
		Addr:     url,
		Password: pwd,
		DB:       0,
	})

	return
}

四、string字符串操作

 	// 判断key是否存在
	_, err := client.Get(context.Background(), "zngw").Result()
	if err == redis.Nil {
		fmt.Println("key不存在")
	} else {
		fmt.Println("key存在")
	}

	// 设置string
	err = client.Set(context.Background(), "zngw", "hello", 0).Err()
	if err != nil {
		fmt.Println(err)
	}

	// 获取string
	val2, err := client.Get(context.Background(), "zngw").Result()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("读取 zngw :", val2)

	// 设置带超时时间的string
	set, err := client.SetNX(context.Background(), "guoke", "hello", 10*time.Second).Result()
	if set {
		fmt.Println("设置成功")
	} else {
		fmt.Println("设置失败")
	}

五、Hash操作

	// 设置Hash Key
	err = client.HSet(context.Background(), "key", "hash:key", "value").Err()
	if err != nil {
		fmt.Println(err)
	}

	// 获取Hash Key
	val1, err := client.HGet(context.Background(), "key", "hash:key").Result()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("读取 zngw :", val1)

	// 获取Key所有键值
	val2, err := client.HGetAll(context.Background(), "key").Result()
	if err != nil {
		fmt.Println(err)
	}

	for k, v := range val2 {
		fmt.Println("key:", k, "value:", v)
	}

六、批量处理

func batchSet() {
	pipeline := client.Pipeline()
	ctx := context.Background()
	for i := 0; i < 100; i++ {
		key := fmt.Sprintf("%d", i)
		pipeline.HSet(ctx, key, map[string]interface{}{key: key})
	}

	_, err := pipeline.Exec(ctx)
	if err != nil {
		panic(err)
	}
}

func batchGet() {
	pipeline := client.Pipeline()
	ctx := context.Background()
	result := make([]*redis.StringStringMapCmd, 0)
	for i := 0; i < 100; i++ {
		key := fmt.Sprintf("%d", i)
		result = append(result, pipeline.HGetAll(ctx, key))
	}

	_, _ = pipeline.Exec(ctx)
	for _, r := range result {
		v, err := r.Result()
		if err != nil {
			panic(err)
		}

		fmt.Println(v)
	}
}