Rename Multi to Tx to better reflect the purpose. Fixes #194.

This commit is contained in:
Vladimir Mihailenco 2016-04-09 11:23:58 +03:00
parent b351402995
commit 7a03514d7f
7 changed files with 124 additions and 149 deletions

View File

@ -60,7 +60,7 @@ func (c *ClusterClient) getClients() map[string]*Client {
// Watch creates new transaction and marks the keys to be watched // Watch creates new transaction and marks the keys to be watched
// for conditional execution of a transaction. // for conditional execution of a transaction.
func (c *ClusterClient) Watch(keys ...string) (*Multi, error) { func (c *ClusterClient) Watch(keys ...string) (*Tx, error) {
addr := c.slotMasterAddr(hashtag.Slot(keys[0])) addr := c.slotMasterAddr(hashtag.Slot(keys[0]))
client, err := c.getClient(addr) client, err := c.getClient(addr)
if err != nil { if err != nil {

View File

@ -4,9 +4,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"reflect" "reflect"
"strconv"
"sync"
"testing"
"time" "time"
. "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo"
@ -2551,63 +2548,6 @@ var _ = Describe("Commands", func() {
}) })
Describe("watch/unwatch", func() {
It("should WatchUnwatch", func() {
var C, N = 10, 1000
if testing.Short() {
N = 100
}
err := client.Set("key", "0", 0).Err()
Expect(err).NotTo(HaveOccurred())
wg := &sync.WaitGroup{}
for i := 0; i < C; i++ {
wg.Add(1)
go func() {
defer GinkgoRecover()
defer wg.Done()
multi := client.Multi()
defer multi.Close()
for j := 0; j < N; j++ {
val, err := multi.Watch("key").Result()
Expect(err).NotTo(HaveOccurred())
Expect(val).To(Equal("OK"))
val, err = multi.Get("key").Result()
Expect(err).NotTo(HaveOccurred())
Expect(val).NotTo(Equal(redis.Nil))
num, err := strconv.ParseInt(val, 10, 64)
Expect(err).NotTo(HaveOccurred())
cmds, err := multi.Exec(func() error {
multi.Set("key", strconv.FormatInt(num+1, 10), 0)
return nil
})
if err == redis.TxFailedErr {
j--
continue
}
Expect(err).NotTo(HaveOccurred())
Expect(cmds).To(HaveLen(1))
Expect(cmds[0].Err()).NotTo(HaveOccurred())
}
}()
}
wg.Wait()
val, err := client.Get("key").Int64()
Expect(err).NotTo(HaveOccurred())
Expect(val).To(Equal(int64(C * N)))
})
})
Describe("Geo add and radius search", func() { Describe("Geo add and radius search", func() {
BeforeEach(func() { BeforeEach(func() {
geoAdd := client.GeoAdd( geoAdd := client.GeoAdd(

View File

@ -37,16 +37,18 @@ var _ = Describe("pool", func() {
perform(1000, func(id int) { perform(1000, func(id int) {
var ping *redis.StatusCmd var ping *redis.StatusCmd
multi := client.Multi() tx, err := client.Watch()
cmds, err := multi.Exec(func() error { Expect(err).NotTo(HaveOccurred())
ping = multi.Ping()
cmds, err := tx.Exec(func() error {
ping = tx.Ping()
return nil return nil
}) })
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(cmds).To(HaveLen(1)) Expect(cmds).To(HaveLen(1))
Expect(ping.Err()).NotTo(HaveOccurred()) Expect(ping.Err()).NotTo(HaveOccurred())
Expect(ping.Val()).To(Equal("PONG")) Expect(ping.Val()).To(Equal("PONG"))
Expect(multi.Close()).NotTo(HaveOccurred()) Expect(tx.Close()).NotTo(HaveOccurred())
}) })
pool := client.Pool() pool := client.Pool()

View File

@ -208,4 +208,43 @@ var _ = Describe("races", func() {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
}) })
}) })
It("should Watch/Unwatch", func() {
err := client.Set("key", "0", 0).Err()
Expect(err).NotTo(HaveOccurred())
perform(C, func(id int) {
for i := 0; i < N; i++ {
tx, err := client.Watch("key")
Expect(err).NotTo(HaveOccurred())
val, err := tx.Get("key").Result()
Expect(err).NotTo(HaveOccurred())
Expect(val).NotTo(Equal(redis.Nil))
num, err := strconv.ParseInt(val, 10, 64)
Expect(err).NotTo(HaveOccurred())
cmds, err := tx.Exec(func() error {
tx.Set("key", strconv.FormatInt(num+1, 10), 0)
return nil
})
if err == redis.TxFailedErr {
i--
continue
}
Expect(err).NotTo(HaveOccurred())
Expect(cmds).To(HaveLen(1))
Expect(cmds[0].Err()).NotTo(HaveOccurred())
err = tx.Close()
Expect(err).NotTo(HaveOccurred())
}
})
val, err := client.Get("key").Int64()
Expect(err).NotTo(HaveOccurred())
Expect(val).To(Equal(int64(C * N)))
})
}) })

View File

@ -66,11 +66,12 @@ var _ = Describe("Client", func() {
}) })
It("should close multi without closing the client", func() { It("should close multi without closing the client", func() {
multi := client.Multi() tx, err := client.Watch()
Expect(multi.Close()).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(tx.Close()).NotTo(HaveOccurred())
_, err := multi.Exec(func() error { _, err = tx.Exec(func() error {
multi.Ping() tx.Ping()
return nil return nil
}) })
Expect(err).To(MatchError("redis: client is closed")) Expect(err).To(MatchError("redis: client is closed"))
@ -96,9 +97,10 @@ var _ = Describe("Client", func() {
}) })
It("should close multi when client is closed", func() { It("should close multi when client is closed", func() {
multi := client.Multi() tx, err := client.Watch()
Expect(err).NotTo(HaveOccurred())
Expect(client.Close()).NotTo(HaveOccurred()) Expect(client.Close()).NotTo(HaveOccurred())
Expect(multi.Close()).NotTo(HaveOccurred()) Expect(tx.Close()).NotTo(HaveOccurred())
}) })
It("should close pipeline when client is closed", func() { It("should close pipeline when client is closed", func() {

View File

@ -9,13 +9,11 @@ import (
var errDiscard = errors.New("redis: Discard can be used only inside Exec") var errDiscard = errors.New("redis: Discard can be used only inside Exec")
// Multi implements Redis transactions as described in // Tx implements Redis transactions as described in
// http://redis.io/topics/transactions. It's NOT safe for concurrent use // http://redis.io/topics/transactions. It's NOT safe for concurrent use
// by multiple goroutines, because Exec resets list of watched keys. // by multiple goroutines, because Exec resets list of watched keys.
// If you don't need WATCH it is better to use Pipeline. // If you don't need WATCH it is better to use Pipeline.
// type Tx struct {
// TODO(vmihailenco): rename to Tx and rework API
type Multi struct {
commandable commandable
base *baseClient base *baseClient
@ -24,77 +22,78 @@ type Multi struct {
closed bool closed bool
} }
// Watch creates new transaction and marks the keys to be watched func (c *Client) newTx() *Tx {
// for conditional execution of a transaction. tx := &Tx{
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{ base: &baseClient{
opt: c.opt, opt: c.opt,
connPool: pool.NewStickyConnPool(c.connPool.(*pool.ConnPool), true), connPool: pool.NewStickyConnPool(c.connPool.(*pool.ConnPool), true),
}, },
} }
multi.commandable.process = multi.process tx.commandable.process = tx.process
return multi return tx
} }
func (c *Multi) process(cmd Cmder) { // Watch creates new transaction and marks the keys to be watched
if c.cmds == nil { // for conditional execution of a transaction.
c.base.process(cmd) func (c *Client) Watch(keys ...string) (*Tx, error) {
tx := c.newTx()
if len(keys) > 0 {
if err := tx.Watch(keys...).Err(); err != nil {
tx.Close()
return nil, err
}
}
return tx, nil
}
func (tx *Tx) process(cmd Cmder) {
if tx.cmds == nil {
tx.base.process(cmd)
} else { } else {
c.cmds = append(c.cmds, cmd) tx.cmds = append(tx.cmds, cmd)
} }
} }
// Close closes the client, releasing any open resources. // Close closes the transaction, releasing any open resources.
func (c *Multi) Close() error { func (tx *Tx) Close() error {
c.closed = true tx.closed = true
if err := c.Unwatch().Err(); err != nil { if err := tx.Unwatch().Err(); err != nil {
Logger.Printf("Unwatch failed: %s", err) Logger.Printf("Unwatch failed: %s", err)
} }
return c.base.Close() return tx.base.Close()
} }
// Watch marks the keys to be watched for conditional execution // Watch marks the keys to be watched for conditional execution
// of a transaction. // of a transaction.
func (c *Multi) Watch(keys ...string) *StatusCmd { func (tx *Tx) Watch(keys ...string) *StatusCmd {
args := make([]interface{}, 1+len(keys)) args := make([]interface{}, 1+len(keys))
args[0] = "WATCH" args[0] = "WATCH"
for i, key := range keys { for i, key := range keys {
args[1+i] = key args[1+i] = key
} }
cmd := NewStatusCmd(args...) cmd := NewStatusCmd(args...)
c.Process(cmd) tx.Process(cmd)
return cmd return cmd
} }
// Unwatch flushes all the previously watched keys for a transaction. // Unwatch flushes all the previously watched keys for a transaction.
func (c *Multi) Unwatch(keys ...string) *StatusCmd { func (tx *Tx) Unwatch(keys ...string) *StatusCmd {
args := make([]interface{}, 1+len(keys)) args := make([]interface{}, 1+len(keys))
args[0] = "UNWATCH" args[0] = "UNWATCH"
for i, key := range keys { for i, key := range keys {
args[1+i] = key args[1+i] = key
} }
cmd := NewStatusCmd(args...) cmd := NewStatusCmd(args...)
c.Process(cmd) tx.Process(cmd)
return cmd return cmd
} }
// Discard discards queued commands. // Discard discards queued commands.
func (c *Multi) Discard() error { func (tx *Tx) Discard() error {
if c.cmds == nil { if tx.cmds == nil {
return errDiscard return errDiscard
} }
c.cmds = c.cmds[:1] tx.cmds = tx.cmds[:1]
return nil return nil
} }
@ -107,19 +106,19 @@ func (c *Multi) Discard() error {
// Exec always returns list of commands. If transaction fails // Exec always returns list of commands. If transaction fails
// TxFailedErr is returned. Otherwise Exec returns error of the first // TxFailedErr is returned. Otherwise Exec returns error of the first
// failed command or nil. // failed command or nil.
func (c *Multi) Exec(f func() error) ([]Cmder, error) { func (tx *Tx) Exec(f func() error) ([]Cmder, error) {
if c.closed { if tx.closed {
return nil, pool.ErrClosed return nil, pool.ErrClosed
} }
c.cmds = []Cmder{NewStatusCmd("MULTI")} tx.cmds = []Cmder{NewStatusCmd("MULTI")}
if err := f(); err != nil { if err := f(); err != nil {
return nil, err return nil, err
} }
c.cmds = append(c.cmds, NewSliceCmd("EXEC")) tx.cmds = append(tx.cmds, NewSliceCmd("EXEC"))
cmds := c.cmds cmds := tx.cmds
c.cmds = nil tx.cmds = nil
if len(cmds) == 2 { if len(cmds) == 2 {
return []Cmder{}, nil return []Cmder{}, nil
@ -128,18 +127,18 @@ func (c *Multi) Exec(f func() error) ([]Cmder, error) {
// Strip MULTI and EXEC commands. // Strip MULTI and EXEC commands.
retCmds := cmds[1 : len(cmds)-1] retCmds := cmds[1 : len(cmds)-1]
cn, err := c.base.conn() cn, err := tx.base.conn()
if err != nil { if err != nil {
setCmdsErr(retCmds, err) setCmdsErr(retCmds, err)
return retCmds, err return retCmds, err
} }
err = c.execCmds(cn, cmds) err = tx.execCmds(cn, cmds)
c.base.putConn(cn, err, false) tx.base.putConn(cn, err, false)
return retCmds, err return retCmds, err
} }
func (c *Multi) execCmds(cn *pool.Conn, cmds []Cmder) error { func (tx *Tx) execCmds(cn *pool.Conn, cmds []Cmder) error {
err := writeCmd(cn, cmds...) err := writeCmd(cn, cmds...)
if err != nil { if err != nil {
setCmdsErr(cmds[1:len(cmds)-1], err) setCmdsErr(cmds[1:len(cmds)-1], err)

View File

@ -10,7 +10,7 @@ import (
"gopkg.in/redis.v3" "gopkg.in/redis.v3"
) )
var _ = Describe("Multi", func() { var _ = Describe("Tx", func() {
var client *redis.Client var client *redis.Client
BeforeEach(func() { BeforeEach(func() {
@ -67,15 +67,16 @@ var _ = Describe("Multi", func() {
}) })
It("should discard", func() { It("should discard", func() {
multi := client.Multi() tx, err := client.Watch("key1", "key2")
Expect(err).NotTo(HaveOccurred())
defer func() { defer func() {
Expect(multi.Close()).NotTo(HaveOccurred()) Expect(tx.Close()).NotTo(HaveOccurred())
}() }()
cmds, err := multi.Exec(func() error { cmds, err := tx.Exec(func() error {
multi.Set("key1", "hello1", 0) tx.Set("key1", "hello1", 0)
multi.Discard() tx.Discard()
multi.Set("key2", "hello2", 0) tx.Set("key2", "hello2", 0)
return nil return nil
}) })
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
@ -91,40 +92,31 @@ var _ = Describe("Multi", func() {
}) })
It("should exec empty", func() { It("should exec empty", func() {
multi := client.Multi() tx, err := client.Watch()
Expect(err).NotTo(HaveOccurred())
defer func() { defer func() {
Expect(multi.Close()).NotTo(HaveOccurred()) Expect(tx.Close()).NotTo(HaveOccurred())
}() }()
cmds, err := multi.Exec(func() error { return nil }) cmds, err := tx.Exec(func() error { return nil })
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(cmds).To(HaveLen(0)) Expect(cmds).To(HaveLen(0))
ping := multi.Ping() ping := tx.Ping()
Expect(ping.Err()).NotTo(HaveOccurred()) Expect(ping.Err()).NotTo(HaveOccurred())
Expect(ping.Val()).To(Equal("PONG")) Expect(ping.Val()).To(Equal("PONG"))
}) })
It("should exec empty queue", func() {
multi := client.Multi()
defer func() {
Expect(multi.Close()).NotTo(HaveOccurred())
}()
cmds, err := multi.Exec(func() error { return nil })
Expect(err).NotTo(HaveOccurred())
Expect(cmds).To(HaveLen(0))
})
It("should exec bulks", func() { It("should exec bulks", func() {
multi := client.Multi() tx, err := client.Watch()
Expect(err).NotTo(HaveOccurred())
defer func() { defer func() {
Expect(multi.Close()).NotTo(HaveOccurred()) Expect(tx.Close()).NotTo(HaveOccurred())
}() }()
cmds, err := multi.Exec(func() error { cmds, err := tx.Exec(func() error {
for i := int64(0); i < 20000; i++ { for i := int64(0); i < 20000; i++ {
multi.Incr("key") tx.Incr("key")
} }
return nil return nil
}) })
@ -148,19 +140,20 @@ var _ = Describe("Multi", func() {
err = client.Pool().Put(cn) err = client.Pool().Put(cn)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
multi := client.Multi() tx, err := client.Watch()
Expect(err).NotTo(HaveOccurred())
defer func() { defer func() {
Expect(multi.Close()).NotTo(HaveOccurred()) Expect(tx.Close()).NotTo(HaveOccurred())
}() }()
_, err = multi.Exec(func() error { _, err = tx.Exec(func() error {
multi.Ping() tx.Ping()
return nil return nil
}) })
Expect(err).To(MatchError("bad connection")) Expect(err).To(MatchError("bad connection"))
_, err = multi.Exec(func() error { _, err = tx.Exec(func() error {
multi.Ping() tx.Ping()
return nil return nil
}) })
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())