我想使用MULTI
和EXEC
对事务执行多个redis命令,因此如果发生不良事件我可以DISCARD
。
我正在寻找如何使用redis事务的示例 go-redis/redis包裹,一无所获。
我还查看了文档here,并且我没有涉及如何使用该包进行redis事务like this for example。或许我遗漏了文档中的内容,因为是的,你知道godoc只是解释了包中的每个功能,主要是使用一个衬里。
即使我找到一些使用其他Go Redis库进行redis事务的示例,我也不会修改我的程序以使用另一个库,因为使用另一个库移植整个应用程序的工作量要大得多。
任何人都可以帮我使用go-redis / redis包吗?
提前感谢。
答案 0 :(得分: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)
答案 1 :(得分:3)
您可以找到有关如何创建Redis交易here的示例:
代码:
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)
如果您更喜欢使用watch(乐观锁定) 您可以看到一个示例here
代码:
ended with 100 <nil>
输出:
desc 'generate pdf',
detail: '...',
body_name: 'pdf',
success: String,
consumes: %w[application/x-www-form-urlencoded],
failure: BaseAPI.document_errors([401, 403, 404])