如何使用go-redis/redis包在Go中创建Redis事务?

Keb*_*eng 7 transactions go redis

我想用事务使用MULTI 和执行多个redis命令EXEC,所以DISCARD如果发生了不好的事情,我就可以.

我正在寻找如何使用go-redis/redis包进行redis事务的示例,但 一无所获.

我也在这里查看文档,我没有任何关于如何使用该软件包进行redis事务的例子.或者也许我从文档中遗漏了一些东西,因为是的,你知道godoc只是解释包中的每个功能,主要使用一个衬垫.

即使我找到一些使用其他Go Redis库进行redis事务的示例,我也不会修改我的程序以使用另一个库,因为使用另一个库移植整个应用程序的工作量要大得多.

任何人都可以帮我使用go-redis/redis包吗?

提前致谢.

Bra*_*chi 6

您可以在此处找到如何创建 Redis 事务的示例:

代码:

pipe := rdb.TxPipeline()

incr := pipe.Incr("tx_pipeline_counter")
pipe.Expire("tx_pipeline_counter", time.Hour)

// Execute
//
//     MULTI
//     INCR pipeline_counter
//     EXPIRE pipeline_counts 3600
//     EXEC
//
// using one rdb-server roundtrip.
_, err := pipe.Exec()
fmt.Println(incr.Val(), err)
Run Code Online (Sandbox Code Playgroud)

输出:

1 <nil>
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢使用手表(乐观锁定),您可以在此处查看示例

代码:

const routineCount = 100

// Transactionally increments key using GET and SET commands.
increment := func(key string) error {
    txf := func(tx *redis.Tx) error {
        // get current value or zero
        n, err := tx.Get(key).Int()
        if err != nil && err != redis.Nil {
            return err
        }

        // actual opperation (local in optimistic lock)
        n++

        // runs only if the watched keys remain unchanged
        _, err = tx.TxPipelined(func(pipe redis.Pipeliner) error {
            // pipe handles the error case
            pipe.Set(key, n, 0)
            return nil
        })
        return err
    }

    for retries := routineCount; retries > 0; retries-- {
        err := rdb.Watch(txf, key)
        if err != redis.TxFailedErr {
            return err
        }
        // optimistic lock lost
    }
    return errors.New("increment reached maximum number of retries")
}

var wg sync.WaitGroup
wg.Add(routineCount)
for i := 0; i < routineCount; i++ {
    go func() {
        defer wg.Done()

        if err := increment("counter3"); err != nil {
            fmt.Println("increment error:", err)
        }
    }()
}
wg.Wait()

n, err := rdb.Get("counter3").Int()
fmt.Println("ended with", n, err)
Run Code Online (Sandbox Code Playgroud)

输出:

ended with 100 <nil>
Run Code Online (Sandbox Code Playgroud)


Jim*_*imB 5

Tx在使用时获得交易的价值Client.Watch

err := client.Watch(func(tx *redis.Tx) error {
    n, err := tx.Get(key).Int64()
    if err != nil && err != redis.Nil {
        return err
    }

    _, err = tx.Pipelined(func(pipe *redis.Pipeline) error {
        pipe.Set(key, strconv.FormatInt(n+1, 10), 0)
        return nil
    })
    return err
}, key)
Run Code Online (Sandbox Code Playgroud)

  • 这个答案中的代码将生成下一个redis命令:````WATCH key GET key SET key UNWATCH````这不是redis网站https://redis.io/topics/transactions#cas上解释事务的方式。为了用 ```MULTI / EXEC``` 包装 SET,请使用 ```tx.TxPipelined``` 而不是 ```tx.Pipelined```。 (3认同)