Keb*_*eng 7 transactions go redis
我想用事务使用MULTI  和执行多个redis命令EXEC,所以DISCARD如果发生了不好的事情,我就可以.
我正在寻找如何使用go-redis/redis包进行redis事务的示例,但 一无所获.
我也在这里查看文档,我没有任何关于如何使用该软件包进行redis事务的例子.或者也许我从文档中遗漏了一些东西,因为是的,你知道godoc只是解释包中的每个功能,主要使用一个衬垫.
即使我找到一些使用其他Go Redis库进行redis事务的示例,我也不会修改我的程序以使用另一个库,因为使用另一个库移植整个应用程序的工作量要大得多.
任何人都可以帮我使用go-redis/redis包吗?
提前致谢.
您可以在此处找到如何创建 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)
输出:
1 <nil>
代码:
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)
输出:
ended with 100 <nil>
您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)
| 归档时间: | 
 | 
| 查看次数: | 3025 次 | 
| 最近记录: |