Skip to content

Commit

Permalink
Merge pull request redis#190 from go-redis/fix/multi-example
Browse files Browse the repository at this point in the history
Improve Tx example.
  • Loading branch information
vmihailenco committed Nov 15, 2015
2 parents d1e774f + f766eb0 commit 7ea220f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 17 deletions.
31 changes: 14 additions & 17 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,13 +159,16 @@ func ExamplePipeline() {
// Output: 1 <nil>
}

func ExampleMulti() {
func ExampleClient_Watch() {
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 {
Expand All @@ -176,35 +179,29 @@ 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)
}
}()
}
wg.Wait()

n, err := client.Get("counter3").Int64()
fmt.Println(n, err)
// Output: 10 <nil>
// Output: 100 <nil>
}

func ExamplePubSub() {
Expand Down
12 changes: 12 additions & 0 deletions multi.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down

0 comments on commit 7ea220f

Please sign in to comment.