|
| 1 | +// EXAMPLE: pipe_trans_tutorial |
| 2 | +// HIDE_START |
| 3 | +package example_commands_test |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "fmt" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/redis/go-redis/v9" |
| 11 | +) |
| 12 | + |
| 13 | +// HIDE_END |
| 14 | + |
| 15 | +func ExampleClient_transactions() { |
| 16 | + // STEP_START basic_trans |
| 17 | + ctx := context.Background() |
| 18 | + |
| 19 | + rdb := redis.NewClient(&redis.Options{ |
| 20 | + Addr: "localhost:6379", |
| 21 | + Password: "", // no password docs |
| 22 | + DB: 0, // use default DB |
| 23 | + }) |
| 24 | + |
| 25 | + // REMOVE_START |
| 26 | + rdb.Del(ctx, "RateCounter") |
| 27 | + // REMOVE_END |
| 28 | + |
| 29 | + setResult, err := rdb.Set(ctx, "RateCounter", 0, 0).Result() |
| 30 | + |
| 31 | + if err != nil { |
| 32 | + panic(err) |
| 33 | + } |
| 34 | + |
| 35 | + fmt.Println(setResult) // >>> OK |
| 36 | + |
| 37 | + trans := rdb.TxPipeline() |
| 38 | + |
| 39 | + // The values of `incrResult` and `expResult` are not available |
| 40 | + // until the transaction has finished executing. |
| 41 | + incrResult := trans.Incr(ctx, "RateCounter") |
| 42 | + expResult := trans.Expire(ctx, "RateCounter", time.Second*10) |
| 43 | + |
| 44 | + cmdsExecuted, err := trans.Exec(ctx) |
| 45 | + |
| 46 | + if err != nil { |
| 47 | + panic(err) |
| 48 | + } |
| 49 | + |
| 50 | + // Values are now available. |
| 51 | + fmt.Println(incrResult.Val()) // >>> 1 |
| 52 | + fmt.Println(expResult.Val()) // >>> true |
| 53 | + |
| 54 | + // You can also use the array of command data returned |
| 55 | + // by the `Exec()` call. |
| 56 | + fmt.Println(len(cmdsExecuted)) // >>> 2 |
| 57 | + |
| 58 | + fmt.Printf("%v: %v\n", |
| 59 | + cmdsExecuted[0].Name(), |
| 60 | + cmdsExecuted[0].(*redis.IntCmd).Val(), |
| 61 | + ) |
| 62 | + // >>> incr: 1 |
| 63 | + |
| 64 | + fmt.Printf("%v: %v\n", |
| 65 | + cmdsExecuted[1].Name(), |
| 66 | + cmdsExecuted[1].(*redis.BoolCmd).Val(), |
| 67 | + ) |
| 68 | + // >>> expire: true |
| 69 | + // STEP_END |
| 70 | + |
| 71 | + // Output: |
| 72 | + // OK |
| 73 | + // 1 |
| 74 | + // true |
| 75 | + // 2 |
| 76 | + // incr: 1 |
| 77 | + // expire: true |
| 78 | +} |
0 commit comments