Improve Tx example.

This commit is contained in:
Vladimir Mihailenco 2015-11-15 10:23:00 +02:00
parent d1e774fa21
commit f766eb0209
2 changed files with 26 additions and 17 deletions

View File

@ -159,13 +159,16 @@ func ExamplePipeline() {
// Output: 1 <nil> // Output: 1 <nil>
} }
func ExampleMulti() { func ExampleWatch() {
var incr func(string) error
// Transactionally increments key using GET and SET commands. // Transactionally increments key using GET and SET commands.
incr := func(tx *redis.Multi, key string) error { incr = func(key string) error {
err := tx.Watch(key).Err() tx, err := client.Watch(key)
if err != nil { if err != nil {
return err return err
} }
defer tx.Close()
n, err := tx.Get(key).Int64() n, err := tx.Get(key).Int64()
if err != nil && err != redis.Nil { if err != nil && err != redis.Nil {
@ -176,27 +179,21 @@ func ExampleMulti() {
tx.Set(key, strconv.FormatInt(n+1, 10), 0) tx.Set(key, strconv.FormatInt(n+1, 10), 0)
return nil return nil
}) })
if err == redis.TxFailedErr {
return incr(key)
}
return err return err
} }
var wg sync.WaitGroup var wg sync.WaitGroup
for i := 0; i < 10; i++ { for i := 0; i < 100; i++ {
wg.Add(1) wg.Add(1)
go func() { go func() {
defer wg.Done() defer wg.Done()
tx := client.Multi() err := incr("counter3")
defer tx.Close() if err != nil {
panic(err)
for {
err := incr(tx, "counter3")
if err == redis.TxFailedErr {
// Retry.
continue
} else if err != nil {
panic(err)
}
break
} }
}() }()
} }
@ -204,7 +201,7 @@ func ExampleMulti() {
n, err := client.Get("counter3").Int64() n, err := client.Get("counter3").Int64()
fmt.Println(n, err) fmt.Println(n, err)
// Output: 10 <nil> // Output: 100 <nil>
} }
func ExamplePubSub() { func ExamplePubSub() {

View File

@ -23,6 +23,18 @@ type Multi struct {
closed bool 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 { func (c *Client) Multi() *Multi {
multi := &Multi{ multi := &Multi{
base: &baseClient{ base: &baseClient{