以下是一个在 GoZero 中使用 github.com/go-redis/redis 库进行 Redis 事务操作的示例代码:
package main
import (
"fmt"
"github.com/go-redis/redis"
)
func performRedisTransaction(client *redis.Client) {
// 开启事务
pipe := client.TxPipeline()
// 准备要在事务中执行的命令
incrCmd := pipe.Incr("counter")
setCmd := pipe.Set("key", "value", 0)
// 执行事务
_, err := pipe.Exec()
if err!= nil {
fmt.Println("Transaction failed:", err)
return
}
// 获取事务执行结果
counterValue, err := incrCmd.Result()
if err!= nil {
fmt.Println("Failed to get counter value:", err)
return
}
fmt.Println("Counter incremented to:", counterValue)
}
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
performRedisTransaction(client)
}
在上述示例中,首先通过 TxPipeline 开启一个事务管道,然后向管道中添加要在事务中执行的命令(如 Incr 和 Set ),最后通过 Exec 执行事务。根据执行结果获取相应的返回值或处理错误。