首頁  >  文章  >  後端開發  >  Redis:儘管資料存在,但 rdb.Pipelined 中出現「redis:nil」錯誤

Redis:儘管資料存在,但 rdb.Pipelined 中出現「redis:nil」錯誤

PHPz
PHPz轉載
2024-02-09 11:50:09432瀏覽

Redis:尽管数据存在,但 rdb.Pipelined 中出现“redis:nil”错误

php小編排香蕉在使用Redis時,可能會遇到一個問題:儘管資料存在,但在rdb.Pipelined中出現"redis:nil"錯誤。這個錯誤可能導致資料無法正確地被讀取,給程式帶來困擾。在解決這個問題之前,我們首先要了解它的原因和可能的解決方法。在本文中,我將為你詳細解析這個問題,並提供一些實用的解決方案,幫助你順利解決這個錯誤。

問題內容

當使用rdb.Pipelined 時,我在Go 中遇到github.com/go-redis/redis/v9包的問題。我有一個包含兩個 Get 查詢的管道,一個資料存在,而第二個不存在。但我仍然收到 redis: nil 錯誤。

這是範例程式碼:

ctx := context.Background()

_, err := rdb.Pipelined(ctx, func(pipe redis.Pipeliner) error {
    pipe.Get(ctx, "key1")

    pipe.Get(ctx, "key2")

    return nil
})

if err != nil {
    log.Printf("Error executing pipeline: %v", err)
}

「key1」存在於 redis 中,而「key2」則不存在。我可以使用 Redis CLI 來驗證這一點。當我執行 rdb.Get(ctx, "key1").Result() 時,它也會傳回資料。 同樣的事情在 EC2 的臨時環境中運作良好。

我已經檢查了拼寫錯誤並確保密鑰存在。造成這種差異的原因是什麼?如何解決?

其他資訊: Redis伺服器版本:7.0.11 Go-Redis版本:v9.1.0 Go版:go1.21.0 darwin/arm64 作業系統:MacOs

感謝您提供有關如何排查和解決此問題的見解或建議。

解決方法

我們可以在go-redis原始程式碼中找到這個:

<code>// Exec executes all previously queued commands using one
// client-server roundtrip.
//
// Exec always returns list of commands and error of the first failed
// command if any.
func (c *Pipeline) Exec(ctx context.Context) ([]Cmder, error) {
    if len(c.cmds) == 0 {
        return nil, nil
    }

    cmds := c.cmds
    c.cmds = nil

    return cmds, c.exec(ctx, cmds)
}

func (c *Pipeline) Pipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error) {
    if err := fn(c); err != nil {
        return nil, err
    }
    return c.Exec(ctx)
}
</code>

所以也許你可以這樣使用它:

var results []string
cmds, _ := cli.Pipelined(context.TODO(), func(pipeliner redis.Pipeliner) error {
    return nil
})
for _, cmd := range cmds {
    if cmd.Err() != nil && cmd.Err() != redis.Nil {
        // log error
        continue
    }
    res := cmd.(*redis.StringCmd).Val()
    results = append(results, res)
}

以上是Redis:儘管資料存在,但 rdb.Pipelined 中出現「redis:nil」錯誤的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除