redis/redis.go

437 lines
9.3 KiB
Go
Raw Normal View History

2017-02-18 17:42:34 +03:00
package redis
2012-07-25 17:00:50 +04:00
import (
2015-05-15 15:21:28 +03:00
"fmt"
2014-07-31 17:01:54 +04:00
"log"
"time"
2017-02-18 17:42:34 +03:00
"github.com/go-redis/redis/internal"
"github.com/go-redis/redis/internal/pool"
"github.com/go-redis/redis/internal/proto"
2012-08-09 14:12:41 +04:00
)
2012-07-25 17:00:50 +04:00
2016-07-02 15:52:10 +03:00
// Redis nil reply, .e.g. when key does not exist.
const Nil = internal.Nil
2016-07-02 15:52:10 +03:00
func SetLogger(logger *log.Logger) {
2016-04-09 14:52:01 +03:00
internal.Logger = logger
}
2015-05-15 15:21:28 +03:00
func (c *baseClient) String() string {
2016-10-05 23:20:05 +03:00
return fmt.Sprintf("Redis<%s db:%d>", c.getAddr(), c.opt.DB)
2015-05-15 15:21:28 +03:00
}
2016-09-29 15:07:04 +03:00
func (c *baseClient) conn() (*pool.Conn, bool, error) {
cn, isNew, err := c.connPool.Get()
2016-03-15 15:04:35 +03:00
if err != nil {
2016-09-29 15:07:04 +03:00
return nil, false, err
2016-03-15 15:04:35 +03:00
}
2016-03-15 15:04:35 +03:00
if !cn.Inited {
if err := c.initConn(cn); err != nil {
_ = c.connPool.Remove(cn)
2016-09-29 15:07:04 +03:00
return nil, false, err
2016-03-12 13:41:02 +03:00
}
}
2017-04-18 13:12:38 +03:00
2016-09-29 15:07:04 +03:00
return cn, isNew, nil
2012-07-26 19:16:17 +04:00
}
2017-04-24 12:43:15 +03:00
func (c *baseClient) putConn(cn *pool.Conn, err error) bool {
if internal.IsBadConn(err, false) {
_ = c.connPool.Remove(cn)
return false
}
_ = c.connPool.Put(cn)
return true
}
2016-03-12 13:41:02 +03:00
func (c *baseClient) initConn(cn *pool.Conn) error {
2016-03-15 15:04:35 +03:00
cn.Inited = true
2017-05-25 14:16:39 +03:00
if c.opt.Password == "" &&
c.opt.DB == 0 &&
!c.opt.ReadOnly &&
c.opt.OnConnect == nil {
2016-03-12 13:41:02 +03:00
return nil
}
2017-05-25 14:16:39 +03:00
// Temp client to initialize connection.
conn := &Conn{
baseClient: baseClient{
opt: c.opt,
connPool: pool.NewSingleConnPool(cn),
},
}
conn.setProcessor(conn.Process)
_, err := conn.Pipelined(func(pipe Pipeliner) error {
if c.opt.Password != "" {
pipe.Auth(c.opt.Password)
2016-03-12 13:41:02 +03:00
}
if c.opt.DB > 0 {
pipe.Select(c.opt.DB)
2016-03-12 13:41:02 +03:00
}
if c.opt.ReadOnly {
pipe.ReadOnly()
}
return nil
})
2017-05-25 14:16:39 +03:00
if err != nil {
return err
}
if c.opt.OnConnect != nil {
return c.opt.OnConnect(conn)
}
return nil
2016-03-12 13:41:02 +03:00
}
2016-06-17 15:09:38 +03:00
func (c *baseClient) Process(cmd Cmder) error {
if c.process != nil {
return c.process(cmd)
}
return c.defaultProcess(cmd)
}
// WrapProcess replaces the process func. It takes a function createWrapper
// which is supplied by the user. createWrapper takes the old process func as
// an input and returns the new wrapper process func. createWrapper should
// use call the old process func within the new process func.
func (c *baseClient) WrapProcess(fn func(oldProcess func(cmd Cmder) error) func(cmd Cmder) error) {
c.process = fn(c.defaultProcess)
}
func (c *baseClient) defaultProcess(cmd Cmder) error {
for i := 0; i <= c.opt.MaxRetries; i++ {
2017-05-25 08:08:44 +03:00
if i > 0 {
time.Sleep(internal.RetryBackoff(i, c.opt.MaxRetryBackoff))
}
2016-09-29 15:07:04 +03:00
cn, _, err := c.conn()
if err != nil {
cmd.setErr(err)
2017-05-25 08:08:44 +03:00
if internal.IsRetryableError(err) {
continue
}
2016-06-17 15:09:38 +03:00
return err
}
2012-07-26 22:43:21 +04:00
cn.SetWriteTimeout(c.opt.WriteTimeout)
if err := writeCmd(cn, cmd); err != nil {
2017-04-24 12:43:15 +03:00
c.putConn(cn, err)
cmd.setErr(err)
2017-05-25 08:08:44 +03:00
if internal.IsRetryableError(err) {
continue
}
2016-06-17 15:09:38 +03:00
return err
}
cn.SetReadTimeout(c.cmdTimeout(cmd))
2015-10-07 17:09:20 +03:00
err = cmd.readReply(cn)
2017-04-24 12:43:15 +03:00
c.putConn(cn, err)
if err != nil && internal.IsRetryableError(err) {
continue
}
2016-06-17 15:09:38 +03:00
return err
2012-07-26 19:16:17 +04:00
}
2016-06-17 15:09:38 +03:00
return cmd.Err()
2014-05-11 11:42:40 +04:00
}
func (c *baseClient) cmdTimeout(cmd Cmder) time.Duration {
if timeout := cmd.readTimeout(); timeout != nil {
return *timeout
} else {
return c.opt.ReadTimeout
}
}
2014-05-11 11:42:40 +04:00
// Close closes the client, releasing any open resources.
2015-09-12 09:36:03 +03:00
//
// It is rare to Close a Client, as the Client is meant to be
// long-lived and shared between many goroutines.
2014-05-11 11:42:40 +04:00
func (c *baseClient) Close() error {
var firstErr error
if c.onClose != nil {
if err := c.onClose(); err != nil && firstErr == nil {
firstErr = err
}
}
if err := c.connPool.Close(); err != nil && firstErr == nil {
firstErr = err
}
return firstErr
2012-07-26 19:16:17 +04:00
}
2016-10-05 23:20:05 +03:00
func (c *baseClient) getAddr() string {
return c.opt.Addr
}
2016-12-13 18:28:39 +03:00
type pipelineProcessor func(*pool.Conn, []Cmder) (bool, error)
func (c *baseClient) pipelineExecer(p pipelineProcessor) pipelineExecer {
return func(cmds []Cmder) error {
var firstErr error
for i := 0; i <= c.opt.MaxRetries; i++ {
cn, _, err := c.conn()
if err != nil {
setCmdsErr(cmds, err)
return err
}
canRetry, err := p(cn, cmds)
2017-04-24 12:43:15 +03:00
c.putConn(cn, err)
2016-12-13 18:28:39 +03:00
if err == nil {
return nil
}
if firstErr == nil {
firstErr = err
}
if !canRetry || !internal.IsRetryableError(err) {
break
}
}
return firstErr
}
}
2017-05-25 14:16:39 +03:00
func (c *baseClient) pipelineProcessCmds(cn *pool.Conn, cmds []Cmder) (bool, error) {
2016-12-13 18:28:39 +03:00
cn.SetWriteTimeout(c.opt.WriteTimeout)
if err := writeCmd(cn, cmds...); err != nil {
setCmdsErr(cmds, err)
return true, err
}
// Set read timeout for all commands.
cn.SetReadTimeout(c.opt.ReadTimeout)
return pipelineReadCmds(cn, cmds)
}
func pipelineReadCmds(cn *pool.Conn, cmds []Cmder) (retry bool, firstErr error) {
for i, cmd := range cmds {
err := cmd.readReply(cn)
if err == nil {
continue
}
if i == 0 {
retry = true
}
if firstErr == nil {
firstErr = err
}
}
return
2016-12-13 18:28:39 +03:00
}
func (c *baseClient) txPipelineProcessCmds(cn *pool.Conn, cmds []Cmder) (bool, error) {
cn.SetWriteTimeout(c.opt.WriteTimeout)
if err := txPipelineWriteMulti(cn, cmds); err != nil {
setCmdsErr(cmds, err)
return true, err
}
// Set read timeout for all commands.
cn.SetReadTimeout(c.opt.ReadTimeout)
if err := c.txPipelineReadQueued(cn, cmds); err != nil {
return false, err
}
_, err := pipelineReadCmds(cn, cmds)
return false, err
}
func txPipelineWriteMulti(cn *pool.Conn, cmds []Cmder) error {
multiExec := make([]Cmder, 0, len(cmds)+2)
multiExec = append(multiExec, NewStatusCmd("MULTI"))
multiExec = append(multiExec, cmds...)
multiExec = append(multiExec, NewSliceCmd("EXEC"))
return writeCmd(cn, multiExec...)
}
func (c *baseClient) txPipelineReadQueued(cn *pool.Conn, cmds []Cmder) error {
var firstErr error
// Parse queued replies.
var statusCmd StatusCmd
if err := statusCmd.readReply(cn); err != nil && firstErr == nil {
firstErr = err
}
for _, cmd := range cmds {
err := statusCmd.readReply(cn)
if err != nil {
cmd.setErr(err)
if firstErr == nil {
firstErr = err
}
}
}
// Parse number of replies.
line, err := cn.Rd.ReadLine()
if err != nil {
if err == Nil {
err = TxFailedErr
}
return err
}
switch line[0] {
case proto.ErrorReply:
return proto.ParseErrorReply(line)
case proto.ArrayReply:
// ok
default:
err := fmt.Errorf("redis: expected '*', but got line %q", line)
return err
}
return nil
}
2014-05-11 11:42:40 +04:00
//------------------------------------------------------------------------------
2015-09-12 09:36:03 +03:00
// Client is a Redis client representing a pool of zero or more
// underlying connections. It's safe for concurrent use by multiple
// goroutines.
type Client struct {
2016-03-09 12:49:05 +03:00
baseClient
cmdable
2015-01-24 15:12:48 +03:00
}
func newClient(opt *Options, pool pool.Pooler) *Client {
2016-12-30 13:58:04 +03:00
client := Client{
baseClient: baseClient{
opt: opt,
connPool: pool,
},
2015-01-24 15:12:48 +03:00
}
2017-05-25 13:38:04 +03:00
client.setProcessor(client.Process)
2016-12-30 13:58:04 +03:00
return &client
2012-08-05 16:09:43 +04:00
}
2015-09-12 09:36:03 +03:00
// NewClient returns a client to the Redis Server specified by Options.
func NewClient(opt *Options) *Client {
2016-06-05 14:10:30 +03:00
opt.init()
return newClient(opt, newConnPool(opt))
}
2016-01-19 19:36:40 +03:00
2017-01-13 07:11:07 +03:00
func (c *Client) copy() *Client {
2017-01-11 06:32:10 +03:00
c2 := new(Client)
*c2 = *c
2017-05-25 13:38:04 +03:00
c2.setProcessor(c2.Process)
2017-01-11 06:32:10 +03:00
return c2
}
2017-05-25 14:16:39 +03:00
// Options returns read-only Options that were used to create the client.
func (c *Client) Options() *Options {
return c.opt
}
// PoolStats returns connection pool stats.
2016-01-19 19:36:40 +03:00
func (c *Client) PoolStats() *PoolStats {
s := c.connPool.Stats()
return &PoolStats{
2016-03-19 17:10:34 +03:00
Requests: s.Requests,
Hits: s.Hits,
Timeouts: s.Timeouts,
2016-03-19 17:10:34 +03:00
TotalConns: s.TotalConns,
FreeConns: s.FreeConns,
}
2016-01-19 19:36:40 +03:00
}
2017-05-02 18:00:53 +03:00
func (c *Client) Pipelined(fn func(Pipeliner) error) ([]Cmder, error) {
2016-12-13 18:28:39 +03:00
return c.Pipeline().pipelined(fn)
}
2017-05-02 18:00:53 +03:00
func (c *Client) Pipeline() Pipeliner {
pipe := Pipeline{
2016-12-13 18:28:39 +03:00
exec: c.pipelineExecer(c.pipelineProcessCmds),
}
2017-05-25 13:38:04 +03:00
pipe.setProcessor(pipe.Process)
return &pipe
}
2017-05-02 18:00:53 +03:00
func (c *Client) TxPipelined(fn func(Pipeliner) error) ([]Cmder, error) {
2016-12-13 18:28:39 +03:00
return c.TxPipeline().pipelined(fn)
}
2016-12-16 15:19:53 +03:00
// TxPipeline acts like Pipeline, but wraps queued commands with MULTI/EXEC.
func (c *Client) TxPipeline() Pipeliner {
2016-12-13 18:28:39 +03:00
pipe := Pipeline{
exec: c.pipelineExecer(c.txPipelineProcessCmds),
}
2017-05-25 13:38:04 +03:00
pipe.setProcessor(pipe.Process)
2016-12-13 18:28:39 +03:00
return &pipe
}
func (c *Client) pubSub() *PubSub {
return &PubSub{
base: baseClient{
opt: c.opt,
connPool: c.connPool,
},
}
}
// Subscribe subscribes the client to the specified channels.
2017-06-17 12:43:19 +03:00
// Channels can be omitted to create empty subscription.
2017-04-11 16:53:55 +03:00
func (c *Client) Subscribe(channels ...string) *PubSub {
pubsub := c.pubSub()
if len(channels) > 0 {
2017-04-11 16:53:55 +03:00
_ = pubsub.Subscribe(channels...)
}
2017-04-11 16:53:55 +03:00
return pubsub
}
// PSubscribe subscribes the client to the given patterns.
2017-06-17 12:43:19 +03:00
// Patterns can be omitted to create empty subscription.
2017-04-11 16:53:55 +03:00
func (c *Client) PSubscribe(channels ...string) *PubSub {
pubsub := c.pubSub()
if len(channels) > 0 {
2017-04-11 16:53:55 +03:00
_ = pubsub.PSubscribe(channels...)
}
2017-04-11 16:53:55 +03:00
return pubsub
}
2017-05-25 14:16:39 +03:00
//------------------------------------------------------------------------------
// Conn is like Client, but its pool contains single connection.
type Conn struct {
baseClient
statefulCmdable
}
func (c *Conn) Pipelined(fn func(Pipeliner) error) ([]Cmder, error) {
return c.Pipeline().pipelined(fn)
}
func (c *Conn) Pipeline() Pipeliner {
pipe := Pipeline{
exec: c.pipelineExecer(c.pipelineProcessCmds),
}
pipe.setProcessor(pipe.Process)
return &pipe
}
func (c *Conn) TxPipelined(fn func(Pipeliner) error) ([]Cmder, error) {
return c.TxPipeline().pipelined(fn)
}
// TxPipeline acts like Pipeline, but wraps queued commands with MULTI/EXEC.
func (c *Conn) TxPipeline() Pipeliner {
pipe := Pipeline{
exec: c.pipelineExecer(c.txPipelineProcessCmds),
}
pipe.setProcessor(pipe.Process)
return &pipe
}