From f766eb02098fbbaff031f9edbe6c31fdfe7bb0ac Mon Sep 17 00:00:00 2001 From: Vladimir Mihailenco Date: Sun, 15 Nov 2015 10:23:00 +0200 Subject: [PATCH] Improve Tx example. --- example_test.go | 31 ++++++++++++++----------------- multi.go | 12 ++++++++++++ 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/example_test.go b/example_test.go index cb4b8f6..1d8be98 100644 --- a/example_test.go +++ b/example_test.go @@ -159,13 +159,16 @@ func ExamplePipeline() { // Output: 1 } -func ExampleMulti() { +func ExampleWatch() { + var incr func(string) error + // Transactionally increments key using GET and SET commands. - incr := func(tx *redis.Multi, key string) error { - err := tx.Watch(key).Err() + incr = func(key string) error { + tx, err := client.Watch(key) if err != nil { return err } + defer tx.Close() n, err := tx.Get(key).Int64() if err != nil && err != redis.Nil { @@ -176,27 +179,21 @@ func ExampleMulti() { tx.Set(key, strconv.FormatInt(n+1, 10), 0) return nil }) + if err == redis.TxFailedErr { + return incr(key) + } return err } var wg sync.WaitGroup - for i := 0; i < 10; i++ { + for i := 0; i < 100; i++ { wg.Add(1) go func() { defer wg.Done() - tx := client.Multi() - defer tx.Close() - - for { - err := incr(tx, "counter3") - if err == redis.TxFailedErr { - // Retry. - continue - } else if err != nil { - panic(err) - } - break + err := incr("counter3") + if err != nil { + panic(err) } }() } @@ -204,7 +201,7 @@ func ExampleMulti() { n, err := client.Get("counter3").Int64() fmt.Println(n, err) - // Output: 10 + // Output: 100 } func ExamplePubSub() { diff --git a/multi.go b/multi.go index 86be83f..43db5e8 100644 --- a/multi.go +++ b/multi.go @@ -23,6 +23,18 @@ type Multi struct { closed bool } +// Watch marks the keys to be watched for conditional execution +// of a transaction. +func (c *Client) Watch(keys ...string) (*Multi, error) { + tx := c.Multi() + if err := tx.Watch(keys...).Err(); err != nil { + tx.Close() + return nil, err + } + return tx, nil +} + +// Deprecated. Use Watch instead. func (c *Client) Multi() *Multi { multi := &Multi{ base: &baseClient{