我想使用MULTI和EXEC执行多个redis命令和事务,这样如果发生了什么不好的事情,我就可以DISCARD它了。
我一直在寻找如何使用go-redis/redis包进行redis事务的示例,但什么也没有找到。
我还查看了文档here,但我没有得到任何有关如何使用该包进行redis事务like this for example的信息。或者也许我在文档中遗漏了一些东西,因为你知道godoc只解释了包中的每个函数,主要使用了一行代码。
尽管我发现了一些使用其他Go redis库进行Redis事务的例子,但我不会修改我的程序来使用其他库,因为使用另一个库移植整个应用程序的工作量会大得多。
有没有人能用go-redis/redis包帮我做到这一点?
发布于 2016-12-07 00:20:25
使用Client.Watch时,将获得事务的Tx值
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)发布于 2020-01-28 22:38:40
您可以找到如何创建Redis事务here的示例
代码:
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>如果您更喜欢使用watch (乐观锁定),您可以查看示例here
代码:
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>https://stackoverflow.com/questions/40999446
复制相似问题