39

golang. 批量获取redis中的缓存值 原

 5 years ago
source link: https://studygolang.com/articles/14605?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

21天精品区块链课程免费学习,深入实战行家带路,助力开发者轻松玩转区块链! >>> QNJNvmJ.png!web

使用redis的pipeline,批量获取redis中的key值时,报错,分析发现,批量获取时,exec后,会返回两种值:nil 及 redis.Nil,

这种情况下,使用常规的 if err!=nil 的判断方法判断错误,是会报错的。

测试代码:

package main

import (
	"github.com/go-redis/redis"
	"log"
	"strconv"
)

func main() {
	client := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
		Network:  "tcp",
		PoolSize: 50,
	})

	if _, err := client.Ping().Result(); err != nil {
		panic(err)
	}

	pipe := client.Pipeline()

	log.Println("所有的key都存在:")
	for i := 0; i < 4; i++ {
		key := "n:" + strconv.FormatInt(int64(i), 10)
		pipe.Get(key)
	}

	result, err := pipe.Exec()

	log.Println(result)
	log.Println(err == nil)
	log.Println(err == redis.Nil)

	log.Println("有不存在的key:")
	for i := 0; i < 5; i++ {
		key := "n:" + strconv.FormatInt(int64(i), 10)
		pipe.Get(key)
	}

	result, err = pipe.Exec()

	log.Println(result)
	log.Println(err == nil)
	log.Println(err == redis.Nil)

	defer client.Close()

}

运行结果:

Qj2aMvA.jpg!web

可以看到,如果批量获取的key中,有不存在的key,返回的会是redis.Nil,否则返回的是nil。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK