Redis 不会在事务中返回 WRONGTYPE 作为错误

时间:2024-04-23

浏览:239

作者:佚名

学习Golang要努力,但是不要急!今天的这篇文章《Redis 不会在事务中返回 WRONGTYPE 作为错误》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

如果已经有人问过这个问题,我们深表歉意。首先,让我展示如何重现我的问题:

  1. 在 docker 容器中运行 redis
  2. 连接到 redis 并执行以下命令:
> set test 10
  • 在 go 中,运行以下代码:
  • func main() {
        redisclient := getconnection() // abstracting get connection for simplicity
    
        r, err := redisclient.do("hset", "test", "f1", "v1", "f2", "v2")
        fmt.printf("%+v e: %+v\n")
    }
    

    很公平,在此步骤中显示以下错误(这意味着 err != nil):

    wrongtype operation against a key holding the wrong kind of value e: wrongtype operation against a key holding the wrong kind of value
  • 作为对比,执行以下代码:
  • func main() {
        redisclient := getconnection()
    
        redisclient.send("multi")
    
        redisclient.send("hset", "test", "f1", "v1", "f2", "v2")
    
        r, err := redisclient.do("exec")
        fmt.printf("%+v e: %+v\n")
    }
    

    正在打印的行是:

    WRONGTYPE Operation against a key holding the wrong kind of value e: <nil>

    这对我来说似乎不一致,因为我希望 multi 也能在错误变量中返回 wrongtype 。

    这是有意为之的行为还是我错过了什么?


    解决方案


    redis 事务中的每个命令都有两个结果。一个是在事务中添加命令的结果,一个是在事务中执行命令的结果。

    do方法返回将命令添加到事务的结果。

    redis EXEC 命令返回一个数组,其中每个元素都是在事务中执行该命令的结果。检查每个元素以检查单个命令错误:

    values, err := redis.values(redisclient.do("exec"))
    if err != nil {
        // handle error
    }
    if err, ok := values[0].(redis.error); ok {
        // handle error for command 0.
        // adjust the index to match the actual index of 
        // of the hmset command in the transaction.
    }

    用于测试事务命令错误的辅助函数可能很有用:

    func execvalues(reply interface{}, err error) ([]interface{}, error) {
        if err != nil {
            return nil, err
        }
        values, ok := reply.([]interface{})
        if !ok {
            return nil, fmt.errorf("unexpected type for exec reply, got type %t", reply)
        }
        for _, v := range values {
            if err, ok := v.(redis.error); ok {
                return values, err
            }
        }
        return values, nil
    }

    像这样使用它:

    values, err := execValues(redisClient.Do("EXEC"))
    if err != nil {
        // Handle error.
    }

    以上就是《Redis 不会在事务中返回 WRONGTYPE 作为错误》的详细内容,更多关于的资料请关注golang学习网公众号!

    本文内容来源于互联网,如有侵权请联系删除。

    相关文章

    更多

    热门专题

    更多
    首页