Skip to content

Commit

Permalink
DOC-4560 basic transaction example
Browse files Browse the repository at this point in the history
  • Loading branch information
andy-stark-redis committed Nov 21, 2024
1 parent f1ffb55 commit 59007b8
Showing 1 changed file with 78 additions and 0 deletions.
78 changes: 78 additions & 0 deletions doctests/pipe_trans_example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// EXAMPLE: pipe_trans_tutorial
// HIDE_START
package example_commands_test

import (
"context"
"fmt"
"time"

"github.com/redis/go-redis/v9"
)

// HIDE_END

func ExampleClient_transactions() {
// STEP_START basic_trans
ctx := context.Background()

rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})

// REMOVE_START
rdb.Del(ctx, "RateCounter")
// REMOVE_END

setResult, err := rdb.Set(ctx, "RateCounter", 0, 0).Result()

if err != nil {
panic(err)
}

fmt.Println(setResult) // >>> OK

trans := rdb.TxPipeline()

// The values of `incrResult` and `expResult` are not available
// until the transaction has finished executing.
incrResult := trans.Incr(ctx, "RateCounter")
expResult := trans.Expire(ctx, "RateCounter", time.Second*10)

cmdsExecuted, err := trans.Exec(ctx)

if err != nil {
panic(err)
}

// Values are now available.
fmt.Println(incrResult.Val()) // >>> 1
fmt.Println(expResult.Val()) // >>> true

// You can also use the array of command data returned
// by the `Exec()` call.
fmt.Println(len(cmdsExecuted)) // >>> 2

fmt.Printf("%v: %v\n",
cmdsExecuted[0].Name(),
cmdsExecuted[0].(*redis.IntCmd).Val(),
)
// >>> incr: 1

fmt.Printf("%v: %v\n",
cmdsExecuted[1].Name(),
cmdsExecuted[1].(*redis.BoolCmd).Val(),
)
// >>> expire: true
// STEP_END

// Output:
// OK
// 1
// true
// 2
// incr: 1
// expire: true
}

0 comments on commit 59007b8

Please sign in to comment.