Explorar el Código

增加 redis 队列

abiao hace 5 años
padre
commit
57ba3d1d59
Se han modificado 75 ficheros con 21605 adiciones y 3 borrados
  1. 0 3
      go.mod
  2. 2 0
      go/gopath/src/github.com/go-redis/redis/.gitignore
  3. 11 0
      go/gopath/src/github.com/go-redis/redis/.golangci.yml
  4. 23 0
      go/gopath/src/github.com/go-redis/redis/.travis.yml
  5. 35 0
      go/gopath/src/github.com/go-redis/redis/CHANGELOG.md
  6. 25 0
      go/gopath/src/github.com/go-redis/redis/LICENSE
  7. 24 0
      go/gopath/src/github.com/go-redis/redis/Makefile
  8. 119 0
      go/gopath/src/github.com/go-redis/redis/README.md
  9. 338 0
      go/gopath/src/github.com/go-redis/redis/bench_test.go
  10. 1626 0
      go/gopath/src/github.com/go-redis/redis/cluster.go
  11. 22 0
      go/gopath/src/github.com/go-redis/redis/cluster_commands.go
  12. 1051 0
      go/gopath/src/github.com/go-redis/redis/cluster_test.go
  13. 1918 0
      go/gopath/src/github.com/go-redis/redis/command.go
  14. 87 0
      go/gopath/src/github.com/go-redis/redis/command_test.go
  15. 2586 0
      go/gopath/src/github.com/go-redis/redis/commands.go
  16. 3975 0
      go/gopath/src/github.com/go-redis/redis/commands_test.go
  17. 4 0
      go/gopath/src/github.com/go-redis/redis/doc.go
  18. 58 0
      go/gopath/src/github.com/go-redis/redis/example_instrumentation_test.go
  19. 480 0
      go/gopath/src/github.com/go-redis/redis/example_test.go
  20. 82 0
      go/gopath/src/github.com/go-redis/redis/export_test.go
  21. 8 0
      go/gopath/src/github.com/go-redis/redis/go.mod
  22. 27 0
      go/gopath/src/github.com/go-redis/redis/go.sum
  23. 81 0
      go/gopath/src/github.com/go-redis/redis/internal/consistenthash/consistenthash.go
  24. 110 0
      go/gopath/src/github.com/go-redis/redis/internal/consistenthash/consistenthash_test.go
  25. 90 0
      go/gopath/src/github.com/go-redis/redis/internal/error.go
  26. 77 0
      go/gopath/src/github.com/go-redis/redis/internal/hashtag/hashtag.go
  27. 74 0
      go/gopath/src/github.com/go-redis/redis/internal/hashtag/hashtag_test.go
  28. 24 0
      go/gopath/src/github.com/go-redis/redis/internal/internal.go
  29. 18 0
      go/gopath/src/github.com/go-redis/redis/internal/internal_test.go
  30. 8 0
      go/gopath/src/github.com/go-redis/redis/internal/log.go
  31. 60 0
      go/gopath/src/github.com/go-redis/redis/internal/once.go
  32. 94 0
      go/gopath/src/github.com/go-redis/redis/internal/pool/bench_test.go
  33. 110 0
      go/gopath/src/github.com/go-redis/redis/internal/pool/conn.go
  34. 7 0
      go/gopath/src/github.com/go-redis/redis/internal/pool/export_test.go
  35. 36 0
      go/gopath/src/github.com/go-redis/redis/internal/pool/main_test.go
  36. 491 0
      go/gopath/src/github.com/go-redis/redis/internal/pool/pool.go
  37. 55 0
      go/gopath/src/github.com/go-redis/redis/internal/pool/pool_single.go
  38. 112 0
      go/gopath/src/github.com/go-redis/redis/internal/pool/pool_sticky.go
  39. 421 0
      go/gopath/src/github.com/go-redis/redis/internal/pool/pool_test.go
  40. 13 0
      go/gopath/src/github.com/go-redis/redis/internal/proto/proto_test.go
  41. 294 0
      go/gopath/src/github.com/go-redis/redis/internal/proto/reader.go
  42. 56 0
      go/gopath/src/github.com/go-redis/redis/internal/proto/reader_test.go
  43. 166 0
      go/gopath/src/github.com/go-redis/redis/internal/proto/scan.go
  44. 48 0
      go/gopath/src/github.com/go-redis/redis/internal/proto/scan_test.go
  45. 93 0
      go/gopath/src/github.com/go-redis/redis/internal/proto/write_buffer_test.go
  46. 161 0
      go/gopath/src/github.com/go-redis/redis/internal/proto/writer.go
  47. 29 0
      go/gopath/src/github.com/go-redis/redis/internal/util.go
  48. 11 0
      go/gopath/src/github.com/go-redis/redis/internal/util/safe.go
  49. 19 0
      go/gopath/src/github.com/go-redis/redis/internal/util/strconv.go
  50. 22 0
      go/gopath/src/github.com/go-redis/redis/internal/util/unsafe.go
  51. 65 0
      go/gopath/src/github.com/go-redis/redis/internal_test.go
  52. 75 0
      go/gopath/src/github.com/go-redis/redis/iterator.go
  53. 136 0
      go/gopath/src/github.com/go-redis/redis/iterator_test.go
  54. 364 0
      go/gopath/src/github.com/go-redis/redis/main_test.go
  55. 228 0
      go/gopath/src/github.com/go-redis/redis/options.go
  56. 119 0
      go/gopath/src/github.com/go-redis/redis/options_test.go
  57. 142 0
      go/gopath/src/github.com/go-redis/redis/pipeline.go
  58. 87 0
      go/gopath/src/github.com/go-redis/redis/pipeline_test.go
  59. 150 0
      go/gopath/src/github.com/go-redis/redis/pool_test.go
  60. 592 0
      go/gopath/src/github.com/go-redis/redis/pubsub.go
  61. 446 0
      go/gopath/src/github.com/go-redis/redis/pubsub_test.go
  62. 347 0
      go/gopath/src/github.com/go-redis/redis/race_test.go
  63. 690 0
      go/gopath/src/github.com/go-redis/redis/redis.go
  64. 344 0
      go/gopath/src/github.com/go-redis/redis/redis_test.go
  65. 148 0
      go/gopath/src/github.com/go-redis/redis/result.go
  66. 725 0
      go/gopath/src/github.com/go-redis/redis/ring.go
  67. 485 0
      go/gopath/src/github.com/go-redis/redis/ring_test.go
  68. 62 0
      go/gopath/src/github.com/go-redis/redis/script.go
  69. 496 0
      go/gopath/src/github.com/go-redis/redis/sentinel.go
  70. 88 0
      go/gopath/src/github.com/go-redis/redis/sentinel_test.go
  71. 10 0
      go/gopath/src/github.com/go-redis/redis/testdata/redis.conf
  72. 142 0
      go/gopath/src/github.com/go-redis/redis/tx.go
  73. 151 0
      go/gopath/src/github.com/go-redis/redis/tx_test.go
  74. 191 0
      go/gopath/src/github.com/go-redis/redis/universal.go
  75. 41 0
      go/gopath/src/github.com/go-redis/redis/universal_test.go

+ 0 - 3
go.mod

@@ -1,3 +0,0 @@
-module github.com/my/repo
-
-go 1.12

+ 2 - 0
go/gopath/src/github.com/go-redis/redis/.gitignore

@@ -0,0 +1,2 @@
+*.rdb
+testdata/*/

+ 11 - 0
go/gopath/src/github.com/go-redis/redis/.golangci.yml

@@ -0,0 +1,11 @@
+run:
+  concurrency: 8
+  deadline: 5m
+  tests: false
+linters:
+  enable-all: true
+  disable:
+    - gochecknoglobals
+    - goconst
+    - gosec
+    - maligned

+ 23 - 0
go/gopath/src/github.com/go-redis/redis/.travis.yml

@@ -0,0 +1,23 @@
+dist: xenial
+sudo: false
+language: go
+
+services:
+  - redis-server
+
+go:
+  - 1.11.x
+  - 1.12.x
+  - tip
+
+matrix:
+  allow_failures:
+    - go: tip
+
+env:
+  - GO111MODULE=on
+
+go_import_path: github.com/go-redis/redis
+
+before_install:
+  - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(go env GOPATH)/bin v1.17.1

+ 35 - 0
go/gopath/src/github.com/go-redis/redis/CHANGELOG.md

@@ -0,0 +1,35 @@
+# Changelog
+
+## v7 WIP
+
+- WrapProcess is replaced with more convenient AddHook that has access to context.Context.
+- WithContext now can not be used to create a shallow copy of the client.
+- New methods ProcessContext, DoContext, and ExecContext.
+- Client respects Context.Deadline when setting net.Conn deadline.
+- Client listens on Context.Done while waiting for a connection from the pool and returns an error when context context is cancelled.
+- Add PubSub.ChannelWithSubscriptions that sends `*Subscription` in addition to `*Message` to allow detecting reconnections.
+- `time.Time` is now marshalled in RFC3339 format. `rdb.Get("foo").Time()` helper is added to parse time.
+
+## v6.15
+
+- Cluster and Ring pipelines process commands for each node in its own goroutine.
+
+## 6.14
+
+- Added Options.MinIdleConns.
+- Added Options.MaxConnAge.
+- PoolStats.FreeConns is renamed to PoolStats.IdleConns.
+- Add Client.Do to simplify creating custom commands.
+- Add Cmd.String, Cmd.Int, Cmd.Int64, Cmd.Uint64, Cmd.Float64, and Cmd.Bool helpers.
+- Lower memory usage.
+
+## v6.13
+
+- Ring got new options called `HashReplicas` and `Hash`. It is recommended to set `HashReplicas = 1000` for better keys distribution between shards.
+- Cluster client was optimized to use much less memory when reloading cluster state.
+- PubSub.ReceiveMessage is re-worked to not use ReceiveTimeout so it does not lose data when timeout occurres. In most cases it is recommended to use PubSub.Channel instead.
+- Dialer.KeepAlive is set to 5 minutes by default.
+
+## v6.12
+
+- ClusterClient got new option called `ClusterSlots` which allows to build cluster of normal Redis Servers that don't have cluster mode enabled. See https://godoc.org/github.com/go-redis/redis#example-NewClusterClient--ManualSetup

+ 25 - 0
go/gopath/src/github.com/go-redis/redis/LICENSE

@@ -0,0 +1,25 @@
+Copyright (c) 2013 The github.com/go-redis/redis Authors.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+   * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+   * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+ 24 - 0
go/gopath/src/github.com/go-redis/redis/Makefile

@@ -0,0 +1,24 @@
+all: testdeps
+	go test ./...
+	go test ./... -short -race
+	go test ./... -run=NONE -bench=. -benchmem
+	env GOOS=linux GOARCH=386 go test ./...
+	go vet
+	go get github.com/gordonklaus/ineffassign
+	ineffassign .
+	golangci-lint run
+
+testdeps: testdata/redis/src/redis-server
+
+bench: testdeps
+	go test ./... -test.run=NONE -test.bench=. -test.benchmem
+
+.PHONY: all test testdeps bench
+
+testdata/redis:
+	mkdir -p $@
+	wget -qO- https://github.com/antirez/redis/archive/5.0.tar.gz | tar xvz --strip-components=1 -C $@
+
+testdata/redis/src/redis-server: testdata/redis
+	sed -i.bak 's/libjemalloc.a/libjemalloc.a -lrt/g' $</src/Makefile
+	cd $< && make all

+ 119 - 0
go/gopath/src/github.com/go-redis/redis/README.md

@@ -0,0 +1,119 @@
+# Redis client for Golang
+
+[![Build Status](https://travis-ci.org/go-redis/redis.png?branch=master)](https://travis-ci.org/go-redis/redis)
+[![GoDoc](https://godoc.org/github.com/go-redis/redis?status.svg)](https://godoc.org/github.com/go-redis/redis)
+[![Airbrake](https://img.shields.io/badge/kudos-airbrake.io-orange.svg)](https://airbrake.io)
+
+Supports:
+
+- Redis 3 commands except QUIT, MONITOR, SLOWLOG and SYNC.
+- Automatic connection pooling with [circuit breaker](https://en.wikipedia.org/wiki/Circuit_breaker_design_pattern) support.
+- [Pub/Sub](https://godoc.org/github.com/go-redis/redis#PubSub).
+- [Transactions](https://godoc.org/github.com/go-redis/redis#example-Client-TxPipeline).
+- [Pipeline](https://godoc.org/github.com/go-redis/redis#example-Client-Pipeline) and [TxPipeline](https://godoc.org/github.com/go-redis/redis#example-Client-TxPipeline).
+- [Scripting](https://godoc.org/github.com/go-redis/redis#Script).
+- [Timeouts](https://godoc.org/github.com/go-redis/redis#Options).
+- [Redis Sentinel](https://godoc.org/github.com/go-redis/redis#NewFailoverClient).
+- [Redis Cluster](https://godoc.org/github.com/go-redis/redis#NewClusterClient).
+- [Cluster of Redis Servers](https://godoc.org/github.com/go-redis/redis#example-NewClusterClient--ManualSetup) without using cluster mode and Redis Sentinel.
+- [Ring](https://godoc.org/github.com/go-redis/redis#NewRing).
+- [Instrumentation](https://godoc.org/github.com/go-redis/redis#ex-package--Instrumentation).
+- [Cache friendly](https://github.com/go-redis/cache).
+- [Rate limiting](https://github.com/go-redis/redis_rate).
+- [Distributed Locks](https://github.com/bsm/redislock).
+
+API docs: https://godoc.org/github.com/go-redis/redis.
+Examples: https://godoc.org/github.com/go-redis/redis#pkg-examples.
+
+## Installation
+
+Install:
+
+```shell
+go get -u github.com/go-redis/redis
+```
+
+Import:
+
+```go
+import "github.com/go-redis/redis"
+```
+
+## Quickstart
+
+```go
+func ExampleNewClient() {
+	client := redis.NewClient(&redis.Options{
+		Addr:     "localhost:6379",
+		Password: "", // no password set
+		DB:       0,  // use default DB
+	})
+
+	pong, err := client.Ping().Result()
+	fmt.Println(pong, err)
+	// Output: PONG <nil>
+}
+
+func ExampleClient() {
+	err := client.Set("key", "value", 0).Err()
+	if err != nil {
+		panic(err)
+	}
+
+	val, err := client.Get("key").Result()
+	if err != nil {
+		panic(err)
+	}
+	fmt.Println("key", val)
+
+	val2, err := client.Get("key2").Result()
+	if err == redis.Nil {
+		fmt.Println("key2 does not exist")
+	} else if err != nil {
+		panic(err)
+	} else {
+		fmt.Println("key2", val2)
+	}
+	// Output: key value
+	// key2 does not exist
+}
+```
+
+## Howto
+
+Please go through [examples](https://godoc.org/github.com/go-redis/redis#pkg-examples) to get an idea how to use this package.
+
+## Look and feel
+
+Some corner cases:
+
+```go
+// SET key value EX 10 NX
+set, err := client.SetNX("key", "value", 10*time.Second).Result()
+
+// SORT list LIMIT 0 2 ASC
+vals, err := client.Sort("list", redis.Sort{Offset: 0, Count: 2, Order: "ASC"}).Result()
+
+// ZRANGEBYSCORE zset -inf +inf WITHSCORES LIMIT 0 2
+vals, err := client.ZRangeByScoreWithScores("zset", redis.ZRangeBy{
+	Min: "-inf",
+	Max: "+inf",
+	Offset: 0,
+	Count: 2,
+}).Result()
+
+// ZINTERSTORE out 2 zset1 zset2 WEIGHTS 2 3 AGGREGATE SUM
+vals, err := client.ZInterStore("out", redis.ZStore{Weights: []int64{2, 3}}, "zset1", "zset2").Result()
+
+// EVAL "return {KEYS[1],ARGV[1]}" 1 "key" "hello"
+vals, err := client.Eval("return {KEYS[1],ARGV[1]}", []string{"key"}, "hello").Result()
+
+// custom command
+res, err := client.Do("set", "key", "value")
+```
+
+## See also
+
+- [Golang PostgreSQL ORM](https://github.com/go-pg/pg)
+- [Golang msgpack](https://github.com/vmihailenco/msgpack)
+- [Golang message task queue](https://github.com/vmihailenco/taskq)

+ 338 - 0
go/gopath/src/github.com/go-redis/redis/bench_test.go

@@ -0,0 +1,338 @@
+package redis_test
+
+import (
+	"bytes"
+	"context"
+	"fmt"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/go-redis/redis"
+)
+
+func benchmarkRedisClient(poolSize int) *redis.Client {
+	client := redis.NewClient(&redis.Options{
+		Addr:         ":6379",
+		DialTimeout:  time.Second,
+		ReadTimeout:  time.Second,
+		WriteTimeout: time.Second,
+		PoolSize:     poolSize,
+	})
+	if err := client.FlushDB().Err(); err != nil {
+		panic(err)
+	}
+	return client
+}
+
+func BenchmarkRedisPing(b *testing.B) {
+	client := benchmarkRedisClient(10)
+	defer client.Close()
+
+	b.ResetTimer()
+
+	b.RunParallel(func(pb *testing.PB) {
+		for pb.Next() {
+			if err := client.Ping().Err(); err != nil {
+				b.Fatal(err)
+			}
+		}
+	})
+}
+
+func BenchmarkRedisGetNil(b *testing.B) {
+	client := benchmarkRedisClient(10)
+	defer client.Close()
+
+	b.ResetTimer()
+
+	b.RunParallel(func(pb *testing.PB) {
+		for pb.Next() {
+			if err := client.Get("key").Err(); err != redis.Nil {
+				b.Fatal(err)
+			}
+		}
+	})
+}
+
+type setStringBenchmark struct {
+	poolSize  int
+	valueSize int
+}
+
+func (bm setStringBenchmark) String() string {
+	return fmt.Sprintf("pool=%d value=%d", bm.poolSize, bm.valueSize)
+}
+
+func BenchmarkRedisSetString(b *testing.B) {
+	benchmarks := []setStringBenchmark{
+		{10, 64},
+		{10, 1024},
+		{10, 64 * 1024},
+		{10, 1024 * 1024},
+		{10, 10 * 1024 * 1024},
+
+		{100, 64},
+		{100, 1024},
+		{100, 64 * 1024},
+		{100, 1024 * 1024},
+		{100, 10 * 1024 * 1024},
+	}
+	for _, bm := range benchmarks {
+		b.Run(bm.String(), func(b *testing.B) {
+			client := benchmarkRedisClient(bm.poolSize)
+			defer client.Close()
+
+			value := strings.Repeat("1", bm.valueSize)
+
+			b.ResetTimer()
+
+			b.RunParallel(func(pb *testing.PB) {
+				for pb.Next() {
+					err := client.Set("key", value, 0).Err()
+					if err != nil {
+						b.Fatal(err)
+					}
+				}
+			})
+		})
+	}
+}
+
+func BenchmarkRedisSetGetBytes(b *testing.B) {
+	client := benchmarkRedisClient(10)
+	defer client.Close()
+
+	value := bytes.Repeat([]byte{'1'}, 10000)
+
+	b.ResetTimer()
+
+	b.RunParallel(func(pb *testing.PB) {
+		for pb.Next() {
+			if err := client.Set("key", value, 0).Err(); err != nil {
+				b.Fatal(err)
+			}
+
+			got, err := client.Get("key").Bytes()
+			if err != nil {
+				b.Fatal(err)
+			}
+			if !bytes.Equal(got, value) {
+				b.Fatalf("got != value")
+			}
+		}
+	})
+}
+
+func BenchmarkRedisMGet(b *testing.B) {
+	client := benchmarkRedisClient(10)
+	defer client.Close()
+
+	if err := client.MSet("key1", "hello1", "key2", "hello2").Err(); err != nil {
+		b.Fatal(err)
+	}
+
+	b.ResetTimer()
+
+	b.RunParallel(func(pb *testing.PB) {
+		for pb.Next() {
+			if err := client.MGet("key1", "key2").Err(); err != nil {
+				b.Fatal(err)
+			}
+		}
+	})
+}
+
+func BenchmarkSetExpire(b *testing.B) {
+	client := benchmarkRedisClient(10)
+	defer client.Close()
+
+	b.ResetTimer()
+
+	b.RunParallel(func(pb *testing.PB) {
+		for pb.Next() {
+			if err := client.Set("key", "hello", 0).Err(); err != nil {
+				b.Fatal(err)
+			}
+			if err := client.Expire("key", time.Second).Err(); err != nil {
+				b.Fatal(err)
+			}
+		}
+	})
+}
+
+func BenchmarkPipeline(b *testing.B) {
+	client := benchmarkRedisClient(10)
+	defer client.Close()
+
+	b.ResetTimer()
+
+	b.RunParallel(func(pb *testing.PB) {
+		for pb.Next() {
+			_, err := client.Pipelined(func(pipe redis.Pipeliner) error {
+				pipe.Set("key", "hello", 0)
+				pipe.Expire("key", time.Second)
+				return nil
+			})
+			if err != nil {
+				b.Fatal(err)
+			}
+		}
+	})
+}
+
+func BenchmarkZAdd(b *testing.B) {
+	client := benchmarkRedisClient(10)
+	defer client.Close()
+
+	b.ResetTimer()
+
+	b.RunParallel(func(pb *testing.PB) {
+		for pb.Next() {
+			err := client.ZAdd("key", &redis.Z{
+				Score:  float64(1),
+				Member: "hello",
+			}).Err()
+			if err != nil {
+				b.Fatal(err)
+			}
+		}
+	})
+}
+
+var clientSink *redis.Client
+
+func BenchmarkWithContext(b *testing.B) {
+	rdb := benchmarkRedisClient(10)
+	defer rdb.Close()
+
+	ctx := context.Background()
+
+	b.ResetTimer()
+	b.ReportAllocs()
+
+	for i := 0; i < b.N; i++ {
+		clientSink = rdb.WithContext(ctx)
+	}
+}
+
+var ringSink *redis.Ring
+
+func BenchmarkRingWithContext(b *testing.B) {
+	rdb := redis.NewRing(&redis.RingOptions{})
+	defer rdb.Close()
+
+	ctx := context.Background()
+
+	b.ResetTimer()
+	b.ReportAllocs()
+
+	for i := 0; i < b.N; i++ {
+		ringSink = rdb.WithContext(ctx)
+	}
+}
+
+//------------------------------------------------------------------------------
+
+func newClusterScenario() *clusterScenario {
+	return &clusterScenario{
+		ports:     []string{"8220", "8221", "8222", "8223", "8224", "8225"},
+		nodeIDs:   make([]string, 6),
+		processes: make(map[string]*redisProcess, 6),
+		clients:   make(map[string]*redis.Client, 6),
+	}
+}
+
+func BenchmarkClusterPing(b *testing.B) {
+	if testing.Short() {
+		b.Skip("skipping in short mode")
+	}
+
+	cluster := newClusterScenario()
+	if err := startCluster(cluster); err != nil {
+		b.Fatal(err)
+	}
+	defer stopCluster(cluster)
+
+	client := cluster.clusterClient(redisClusterOptions())
+	defer client.Close()
+
+	b.ResetTimer()
+
+	b.RunParallel(func(pb *testing.PB) {
+		for pb.Next() {
+			err := client.Ping().Err()
+			if err != nil {
+				b.Fatal(err)
+			}
+		}
+	})
+}
+
+func BenchmarkClusterSetString(b *testing.B) {
+	if testing.Short() {
+		b.Skip("skipping in short mode")
+	}
+
+	cluster := newClusterScenario()
+	if err := startCluster(cluster); err != nil {
+		b.Fatal(err)
+	}
+	defer stopCluster(cluster)
+
+	client := cluster.clusterClient(redisClusterOptions())
+	defer client.Close()
+
+	value := string(bytes.Repeat([]byte{'1'}, 10000))
+
+	b.ResetTimer()
+
+	b.RunParallel(func(pb *testing.PB) {
+		for pb.Next() {
+			err := client.Set("key", value, 0).Err()
+			if err != nil {
+				b.Fatal(err)
+			}
+		}
+	})
+}
+
+func BenchmarkClusterReloadState(b *testing.B) {
+	if testing.Short() {
+		b.Skip("skipping in short mode")
+	}
+
+	cluster := newClusterScenario()
+	if err := startCluster(cluster); err != nil {
+		b.Fatal(err)
+	}
+	defer stopCluster(cluster)
+
+	client := cluster.clusterClient(redisClusterOptions())
+	defer client.Close()
+
+	b.ResetTimer()
+
+	for i := 0; i < b.N; i++ {
+		err := client.ReloadState()
+		if err != nil {
+			b.Fatal(err)
+		}
+	}
+}
+
+var clusterSink *redis.ClusterClient
+
+func BenchmarkClusterWithContext(b *testing.B) {
+	rdb := redis.NewClusterClient(&redis.ClusterOptions{})
+	defer rdb.Close()
+
+	ctx := context.Background()
+
+	b.ResetTimer()
+	b.ReportAllocs()
+
+	for i := 0; i < b.N; i++ {
+		clusterSink = rdb.WithContext(ctx)
+	}
+}

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 1626 - 0
go/gopath/src/github.com/go-redis/redis/cluster.go


+ 22 - 0
go/gopath/src/github.com/go-redis/redis/cluster_commands.go

@@ -0,0 +1,22 @@
+package redis
+
+import "sync/atomic"
+
+func (c *ClusterClient) DBSize() *IntCmd {
+	cmd := NewIntCmd("dbsize")
+	var size int64
+	err := c.ForEachMaster(func(master *Client) error {
+		n, err := master.DBSize().Result()
+		if err != nil {
+			return err
+		}
+		atomic.AddInt64(&size, n)
+		return nil
+	})
+	if err != nil {
+		cmd.setErr(err)
+		return cmd
+	}
+	cmd.val = size
+	return cmd
+}

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 1051 - 0
go/gopath/src/github.com/go-redis/redis/cluster_test.go


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 1918 - 0
go/gopath/src/github.com/go-redis/redis/command.go


+ 87 - 0
go/gopath/src/github.com/go-redis/redis/command_test.go

@@ -0,0 +1,87 @@
+package redis_test
+
+import (
+	"time"
+
+	"github.com/go-redis/redis"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("Cmd", func() {
+	var client *redis.Client
+
+	BeforeEach(func() {
+		client = redis.NewClient(redisOptions())
+		Expect(client.FlushDB().Err()).NotTo(HaveOccurred())
+	})
+
+	AfterEach(func() {
+		Expect(client.Close()).NotTo(HaveOccurred())
+	})
+
+	It("implements Stringer", func() {
+		set := client.Set("foo", "bar", 0)
+		Expect(set.String()).To(Equal("set foo bar: OK"))
+
+		get := client.Get("foo")
+		Expect(get.String()).To(Equal("get foo: bar"))
+	})
+
+	It("has val/err", func() {
+		set := client.Set("key", "hello", 0)
+		Expect(set.Err()).NotTo(HaveOccurred())
+		Expect(set.Val()).To(Equal("OK"))
+
+		get := client.Get("key")
+		Expect(get.Err()).NotTo(HaveOccurred())
+		Expect(get.Val()).To(Equal("hello"))
+
+		Expect(set.Err()).NotTo(HaveOccurred())
+		Expect(set.Val()).To(Equal("OK"))
+	})
+
+	It("has helpers", func() {
+		set := client.Set("key", "10", 0)
+		Expect(set.Err()).NotTo(HaveOccurred())
+
+		n, err := client.Get("key").Int64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(n).To(Equal(int64(10)))
+
+		un, err := client.Get("key").Uint64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(un).To(Equal(uint64(10)))
+
+		f, err := client.Get("key").Float64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(f).To(Equal(float64(10)))
+	})
+
+	It("supports float32", func() {
+		f := float32(66.97)
+
+		err := client.Set("float_key", f, 0).Err()
+		Expect(err).NotTo(HaveOccurred())
+
+		val, err := client.Get("float_key").Float32()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(val).To(Equal(f))
+	})
+
+	It("supports time.Time", func() {
+		tm := time.Date(2019, 01, 01, 0, 0, 0, 0, time.UTC)
+
+		err := client.Set("time_key", tm, 0).Err()
+		Expect(err).NotTo(HaveOccurred())
+
+		s, err := client.Get("time_key").Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(s).To(Equal("2019-01-01T00:00:00Z"))
+
+		tm2, err := client.Get("time_key").Time()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(tm2).To(BeTemporally("==", tm))
+	})
+})

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 2586 - 0
go/gopath/src/github.com/go-redis/redis/commands.go


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 3975 - 0
go/gopath/src/github.com/go-redis/redis/commands_test.go


+ 4 - 0
go/gopath/src/github.com/go-redis/redis/doc.go

@@ -0,0 +1,4 @@
+/*
+Package redis implements a Redis client.
+*/
+package redis

+ 58 - 0
go/gopath/src/github.com/go-redis/redis/example_instrumentation_test.go

@@ -0,0 +1,58 @@
+package redis_test
+
+import (
+	"context"
+	"fmt"
+
+	"github.com/go-redis/redis"
+)
+
+type redisHook struct{}
+
+var _ redis.Hook = redisHook{}
+
+func (redisHook) BeforeProcess(ctx context.Context, cmd redis.Cmder) (context.Context, error) {
+	fmt.Printf("starting processing: <%s>\n", cmd)
+	return ctx, nil
+}
+
+func (redisHook) AfterProcess(ctx context.Context, cmd redis.Cmder) error {
+	fmt.Printf("finished processing: <%s>\n", cmd)
+	return nil
+}
+
+func (redisHook) BeforeProcessPipeline(ctx context.Context, cmds []redis.Cmder) (context.Context, error) {
+	fmt.Printf("pipeline starting processing: %v\n", cmds)
+	return ctx, nil
+}
+
+func (redisHook) AfterProcessPipeline(ctx context.Context, cmds []redis.Cmder) error {
+	fmt.Printf("pipeline finished processing: %v\n", cmds)
+	return nil
+}
+
+func Example_instrumentation() {
+	rdb := redis.NewClient(&redis.Options{
+		Addr: ":6379",
+	})
+	rdb.AddHook(redisHook{})
+
+	rdb.Ping()
+	// Output: starting processing: <ping: >
+	// finished processing: <ping: PONG>
+}
+
+func ExamplePipeline_instrumentation() {
+	rdb := redis.NewClient(&redis.Options{
+		Addr: ":6379",
+	})
+	rdb.AddHook(redisHook{})
+
+	rdb.Pipelined(func(pipe redis.Pipeliner) error {
+		pipe.Ping()
+		pipe.Ping()
+		return nil
+	})
+	// Output: pipeline starting processing: [ping:  ping: ]
+	// pipeline finished processing: [ping: PONG ping: PONG]
+}

+ 480 - 0
go/gopath/src/github.com/go-redis/redis/example_test.go

@@ -0,0 +1,480 @@
+package redis_test
+
+import (
+	"errors"
+	"fmt"
+	"sync"
+	"time"
+
+	"github.com/go-redis/redis"
+)
+
+var redisdb *redis.Client
+
+func init() {
+	redisdb = redis.NewClient(&redis.Options{
+		Addr:         ":6379",
+		DialTimeout:  10 * time.Second,
+		ReadTimeout:  30 * time.Second,
+		WriteTimeout: 30 * time.Second,
+		PoolSize:     10,
+		PoolTimeout:  30 * time.Second,
+	})
+}
+
+func ExampleNewClient() {
+	redisdb := redis.NewClient(&redis.Options{
+		Addr:     "localhost:6379", // use default Addr
+		Password: "",               // no password set
+		DB:       0,                // use default DB
+	})
+
+	pong, err := redisdb.Ping().Result()
+	fmt.Println(pong, err)
+	// Output: PONG <nil>
+}
+
+func ExampleParseURL() {
+	opt, err := redis.ParseURL("redis://:qwerty@localhost:6379/1")
+	if err != nil {
+		panic(err)
+	}
+	fmt.Println("addr is", opt.Addr)
+	fmt.Println("db is", opt.DB)
+	fmt.Println("password is", opt.Password)
+
+	// Create client as usually.
+	_ = redis.NewClient(opt)
+
+	// Output: addr is localhost:6379
+	// db is 1
+	// password is qwerty
+}
+
+func ExampleNewFailoverClient() {
+	// See http://redis.io/topics/sentinel for instructions how to
+	// setup Redis Sentinel.
+	redisdb := redis.NewFailoverClient(&redis.FailoverOptions{
+		MasterName:    "master",
+		SentinelAddrs: []string{":26379"},
+	})
+	redisdb.Ping()
+}
+
+func ExampleNewClusterClient() {
+	// See http://redis.io/topics/cluster-tutorial for instructions
+	// how to setup Redis Cluster.
+	redisdb := redis.NewClusterClient(&redis.ClusterOptions{
+		Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
+	})
+	redisdb.Ping()
+}
+
+// Following example creates a cluster from 2 master nodes and 2 slave nodes
+// without using cluster mode or Redis Sentinel.
+func ExampleNewClusterClient_manualSetup() {
+	// clusterSlots returns cluster slots information.
+	// It can use service like ZooKeeper to maintain configuration information
+	// and Cluster.ReloadState to manually trigger state reloading.
+	clusterSlots := func() ([]redis.ClusterSlot, error) {
+		slots := []redis.ClusterSlot{
+			// First node with 1 master and 1 slave.
+			{
+				Start: 0,
+				End:   8191,
+				Nodes: []redis.ClusterNode{{
+					Addr: ":7000", // master
+				}, {
+					Addr: ":8000", // 1st slave
+				}},
+			},
+			// Second node with 1 master and 1 slave.
+			{
+				Start: 8192,
+				End:   16383,
+				Nodes: []redis.ClusterNode{{
+					Addr: ":7001", // master
+				}, {
+					Addr: ":8001", // 1st slave
+				}},
+			},
+		}
+		return slots, nil
+	}
+
+	redisdb := redis.NewClusterClient(&redis.ClusterOptions{
+		ClusterSlots:  clusterSlots,
+		RouteRandomly: true,
+	})
+	redisdb.Ping()
+
+	// ReloadState reloads cluster state. It calls ClusterSlots func
+	// to get cluster slots information.
+	err := redisdb.ReloadState()
+	if err != nil {
+		panic(err)
+	}
+}
+
+func ExampleNewRing() {
+	redisdb := redis.NewRing(&redis.RingOptions{
+		Addrs: map[string]string{
+			"shard1": ":7000",
+			"shard2": ":7001",
+			"shard3": ":7002",
+		},
+	})
+	redisdb.Ping()
+}
+
+func ExampleClient() {
+	err := redisdb.Set("key", "value", 0).Err()
+	if err != nil {
+		panic(err)
+	}
+
+	val, err := redisdb.Get("key").Result()
+	if err != nil {
+		panic(err)
+	}
+	fmt.Println("key", val)
+
+	val2, err := redisdb.Get("missing_key").Result()
+	if err == redis.Nil {
+		fmt.Println("missing_key does not exist")
+	} else if err != nil {
+		panic(err)
+	} else {
+		fmt.Println("missing_key", val2)
+	}
+	// Output: key value
+	// missing_key does not exist
+}
+
+func ExampleClient_Set() {
+	// Last argument is expiration. Zero means the key has no
+	// expiration time.
+	err := redisdb.Set("key", "value", 0).Err()
+	if err != nil {
+		panic(err)
+	}
+
+	// key2 will expire in an hour.
+	err = redisdb.Set("key2", "value", time.Hour).Err()
+	if err != nil {
+		panic(err)
+	}
+}
+
+func ExampleClient_Incr() {
+	result, err := redisdb.Incr("counter").Result()
+	if err != nil {
+		panic(err)
+	}
+
+	fmt.Println(result)
+	// Output: 1
+}
+
+func ExampleClient_BLPop() {
+	if err := redisdb.RPush("queue", "message").Err(); err != nil {
+		panic(err)
+	}
+
+	// use `redisdb.BLPop(0, "queue")` for infinite waiting time
+	result, err := redisdb.BLPop(1*time.Second, "queue").Result()
+	if err != nil {
+		panic(err)
+	}
+
+	fmt.Println(result[0], result[1])
+	// Output: queue message
+}
+
+func ExampleClient_Scan() {
+	redisdb.FlushDB()
+	for i := 0; i < 33; i++ {
+		err := redisdb.Set(fmt.Sprintf("key%d", i), "value", 0).Err()
+		if err != nil {
+			panic(err)
+		}
+	}
+
+	var cursor uint64
+	var n int
+	for {
+		var keys []string
+		var err error
+		keys, cursor, err = redisdb.Scan(cursor, "key*", 10).Result()
+		if err != nil {
+			panic(err)
+		}
+		n += len(keys)
+		if cursor == 0 {
+			break
+		}
+	}
+
+	fmt.Printf("found %d keys\n", n)
+	// Output: found 33 keys
+}
+
+func ExampleClient_Pipelined() {
+	var incr *redis.IntCmd
+	_, err := redisdb.Pipelined(func(pipe redis.Pipeliner) error {
+		incr = pipe.Incr("pipelined_counter")
+		pipe.Expire("pipelined_counter", time.Hour)
+		return nil
+	})
+	fmt.Println(incr.Val(), err)
+	// Output: 1 <nil>
+}
+
+func ExampleClient_Pipeline() {
+	pipe := redisdb.Pipeline()
+
+	incr := pipe.Incr("pipeline_counter")
+	pipe.Expire("pipeline_counter", time.Hour)
+
+	// Execute
+	//
+	//     INCR pipeline_counter
+	//     EXPIRE pipeline_counts 3600
+	//
+	// using one redisdb-server roundtrip.
+	_, err := pipe.Exec()
+	fmt.Println(incr.Val(), err)
+	// Output: 1 <nil>
+}
+
+func ExampleClient_TxPipelined() {
+	var incr *redis.IntCmd
+	_, err := redisdb.TxPipelined(func(pipe redis.Pipeliner) error {
+		incr = pipe.Incr("tx_pipelined_counter")
+		pipe.Expire("tx_pipelined_counter", time.Hour)
+		return nil
+	})
+	fmt.Println(incr.Val(), err)
+	// Output: 1 <nil>
+}
+
+func ExampleClient_TxPipeline() {
+	pipe := redisdb.TxPipeline()
+
+	incr := pipe.Incr("tx_pipeline_counter")
+	pipe.Expire("tx_pipeline_counter", time.Hour)
+
+	// Execute
+	//
+	//     MULTI
+	//     INCR pipeline_counter
+	//     EXPIRE pipeline_counts 3600
+	//     EXEC
+	//
+	// using one redisdb-server roundtrip.
+	_, err := pipe.Exec()
+	fmt.Println(incr.Val(), err)
+	// Output: 1 <nil>
+}
+
+func ExampleClient_Watch() {
+	const routineCount = 100
+
+	// Transactionally increments key using GET and SET commands.
+	increment := func(key string) error {
+		txf := func(tx *redis.Tx) error {
+			// get current value or zero
+			n, err := tx.Get(key).Int()
+			if err != nil && err != redis.Nil {
+				return err
+			}
+
+			// actual opperation (local in optimistic lock)
+			n++
+
+			// runs only if the watched keys remain unchanged
+			_, err = tx.Pipelined(func(pipe redis.Pipeliner) error {
+				// pipe handles the error case
+				pipe.Set(key, n, 0)
+				return nil
+			})
+			return err
+		}
+
+		for retries := routineCount; retries > 0; retries-- {
+			err := redisdb.Watch(txf, key)
+			if err != redis.TxFailedErr {
+				return err
+			}
+			// optimistic lock lost
+		}
+		return errors.New("increment reached maximum number of retries")
+	}
+
+	var wg sync.WaitGroup
+	wg.Add(routineCount)
+	for i := 0; i < routineCount; i++ {
+		go func() {
+			defer wg.Done()
+
+			if err := increment("counter3"); err != nil {
+				fmt.Println("increment error:", err)
+			}
+		}()
+	}
+	wg.Wait()
+
+	n, err := redisdb.Get("counter3").Int()
+	fmt.Println("ended with", n, err)
+	// Output: ended with 100 <nil>
+}
+
+func ExamplePubSub() {
+	pubsub := redisdb.Subscribe("mychannel1")
+
+	// Wait for confirmation that subscription is created before publishing anything.
+	_, err := pubsub.Receive()
+	if err != nil {
+		panic(err)
+	}
+
+	// Go channel which receives messages.
+	ch := pubsub.Channel()
+
+	// Publish a message.
+	err = redisdb.Publish("mychannel1", "hello").Err()
+	if err != nil {
+		panic(err)
+	}
+
+	time.AfterFunc(time.Second, func() {
+		// When pubsub is closed channel is closed too.
+		_ = pubsub.Close()
+	})
+
+	// Consume messages.
+	for msg := range ch {
+		fmt.Println(msg.Channel, msg.Payload)
+	}
+
+	// Output: mychannel1 hello
+}
+
+func ExamplePubSub_Receive() {
+	pubsub := redisdb.Subscribe("mychannel2")
+	defer pubsub.Close()
+
+	for i := 0; i < 2; i++ {
+		// ReceiveTimeout is a low level API. Use ReceiveMessage instead.
+		msgi, err := pubsub.ReceiveTimeout(time.Second)
+		if err != nil {
+			break
+		}
+
+		switch msg := msgi.(type) {
+		case *redis.Subscription:
+			fmt.Println("subscribed to", msg.Channel)
+
+			_, err := redisdb.Publish("mychannel2", "hello").Result()
+			if err != nil {
+				panic(err)
+			}
+		case *redis.Message:
+			fmt.Println("received", msg.Payload, "from", msg.Channel)
+		default:
+			panic("unreached")
+		}
+	}
+
+	// sent message to 1 redisdb
+	// received hello from mychannel2
+}
+
+func ExampleScript() {
+	IncrByXX := redis.NewScript(`
+		if redis.call("GET", KEYS[1]) ~= false then
+			return redis.call("INCRBY", KEYS[1], ARGV[1])
+		end
+		return false
+	`)
+
+	n, err := IncrByXX.Run(redisdb, []string{"xx_counter"}, 2).Result()
+	fmt.Println(n, err)
+
+	err = redisdb.Set("xx_counter", "40", 0).Err()
+	if err != nil {
+		panic(err)
+	}
+
+	n, err = IncrByXX.Run(redisdb, []string{"xx_counter"}, 2).Result()
+	fmt.Println(n, err)
+
+	// Output: <nil> redis: nil
+	// 42 <nil>
+}
+
+func Example_customCommand() {
+	Get := func(redisdb *redis.Client, key string) *redis.StringCmd {
+		cmd := redis.NewStringCmd("get", key)
+		redisdb.Process(cmd)
+		return cmd
+	}
+
+	v, err := Get(redisdb, "key_does_not_exist").Result()
+	fmt.Printf("%q %s", v, err)
+	// Output: "" redis: nil
+}
+
+func Example_customCommand2() {
+	v, err := redisdb.Do("get", "key_does_not_exist").String()
+	fmt.Printf("%q %s", v, err)
+	// Output: "" redis: nil
+}
+
+func ExampleScanIterator() {
+	iter := redisdb.Scan(0, "", 0).Iterator()
+	for iter.Next() {
+		fmt.Println(iter.Val())
+	}
+	if err := iter.Err(); err != nil {
+		panic(err)
+	}
+}
+
+func ExampleScanCmd_Iterator() {
+	iter := redisdb.Scan(0, "", 0).Iterator()
+	for iter.Next() {
+		fmt.Println(iter.Val())
+	}
+	if err := iter.Err(); err != nil {
+		panic(err)
+	}
+}
+
+func ExampleNewUniversalClient_simple() {
+	redisdb := redis.NewUniversalClient(&redis.UniversalOptions{
+		Addrs: []string{":6379"},
+	})
+	defer redisdb.Close()
+
+	redisdb.Ping()
+}
+
+func ExampleNewUniversalClient_failover() {
+	redisdb := redis.NewUniversalClient(&redis.UniversalOptions{
+		MasterName: "master",
+		Addrs:      []string{":26379"},
+	})
+	defer redisdb.Close()
+
+	redisdb.Ping()
+}
+
+func ExampleNewUniversalClient_cluster() {
+	redisdb := redis.NewUniversalClient(&redis.UniversalOptions{
+		Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
+	})
+	defer redisdb.Close()
+
+	redisdb.Ping()
+}

+ 82 - 0
go/gopath/src/github.com/go-redis/redis/export_test.go

@@ -0,0 +1,82 @@
+package redis
+
+import (
+	"fmt"
+	"net"
+	"strings"
+
+	"github.com/go-redis/redis/internal/hashtag"
+	"github.com/go-redis/redis/internal/pool"
+)
+
+func (c *baseClient) Pool() pool.Pooler {
+	return c.connPool
+}
+
+func (c *PubSub) SetNetConn(netConn net.Conn) {
+	c.cn = pool.NewConn(netConn)
+}
+
+func (c *ClusterClient) LoadState() (*clusterState, error) {
+	return c.loadState()
+}
+
+func (c *ClusterClient) SlotAddrs(slot int) []string {
+	state, err := c.state.Get()
+	if err != nil {
+		panic(err)
+	}
+
+	var addrs []string
+	for _, n := range state.slotNodes(slot) {
+		addrs = append(addrs, n.Client.getAddr())
+	}
+	return addrs
+}
+
+func (c *ClusterClient) Nodes(key string) ([]*clusterNode, error) {
+	state, err := c.state.Reload()
+	if err != nil {
+		return nil, err
+	}
+
+	slot := hashtag.Slot(key)
+	nodes := state.slotNodes(slot)
+	if len(nodes) != 2 {
+		return nil, fmt.Errorf("slot=%d does not have enough nodes: %v", slot, nodes)
+	}
+	return nodes, nil
+}
+
+func (c *ClusterClient) SwapNodes(key string) error {
+	nodes, err := c.Nodes(key)
+	if err != nil {
+		return err
+	}
+	nodes[0], nodes[1] = nodes[1], nodes[0]
+	return nil
+}
+
+func (state *clusterState) IsConsistent() bool {
+	if len(state.Masters) < 3 {
+		return false
+	}
+	for _, master := range state.Masters {
+		s := master.Client.Info("replication").Val()
+		if !strings.Contains(s, "role:master") {
+			return false
+		}
+	}
+
+	if len(state.Slaves) < 3 {
+		return false
+	}
+	for _, slave := range state.Slaves {
+		s := slave.Client.Info("replication").Val()
+		if !strings.Contains(s, "role:slave") {
+			return false
+		}
+	}
+
+	return true
+}

+ 8 - 0
go/gopath/src/github.com/go-redis/redis/go.mod

@@ -0,0 +1,8 @@
+module github.com/go-redis/redis
+
+require (
+	github.com/onsi/ginkgo v1.8.0
+	github.com/onsi/gomega v1.5.0
+)
+
+go 1.13

+ 27 - 0
go/gopath/src/github.com/go-redis/redis/go.sum

@@ -0,0 +1,27 @@
+github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
+github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
+github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
+github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
+github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
+github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
+github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
+github.com/onsi/ginkgo v1.8.0 h1:VkHVNpR4iVnU8XQR6DBm8BqYjN7CRzw+xKUbVVbbW9w=
+github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
+github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo=
+github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
+golang.org/x/net v0.0.0-20180906233101-161cd47e91fd h1:nTDtHvHSdCn1m6ITfMRqtOd/9+7a3s8RBNOZ3eYZzJA=
+golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA=
+golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs=
+golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
+gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
+gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
+gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
+gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
+gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

+ 81 - 0
go/gopath/src/github.com/go-redis/redis/internal/consistenthash/consistenthash.go

@@ -0,0 +1,81 @@
+/*
+Copyright 2013 Google Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Package consistenthash provides an implementation of a ring hash.
+package consistenthash
+
+import (
+	"hash/crc32"
+	"sort"
+	"strconv"
+)
+
+type Hash func(data []byte) uint32
+
+type Map struct {
+	hash     Hash
+	replicas int
+	keys     []int // Sorted
+	hashMap  map[int]string
+}
+
+func New(replicas int, fn Hash) *Map {
+	m := &Map{
+		replicas: replicas,
+		hash:     fn,
+		hashMap:  make(map[int]string),
+	}
+	if m.hash == nil {
+		m.hash = crc32.ChecksumIEEE
+	}
+	return m
+}
+
+// Returns true if there are no items available.
+func (m *Map) IsEmpty() bool {
+	return len(m.keys) == 0
+}
+
+// Adds some keys to the hash.
+func (m *Map) Add(keys ...string) {
+	for _, key := range keys {
+		for i := 0; i < m.replicas; i++ {
+			hash := int(m.hash([]byte(strconv.Itoa(i) + key)))
+			m.keys = append(m.keys, hash)
+			m.hashMap[hash] = key
+		}
+	}
+	sort.Ints(m.keys)
+}
+
+// Gets the closest item in the hash to the provided key.
+func (m *Map) Get(key string) string {
+	if m.IsEmpty() {
+		return ""
+	}
+
+	hash := int(m.hash([]byte(key)))
+
+	// Binary search for appropriate replica.
+	idx := sort.Search(len(m.keys), func(i int) bool { return m.keys[i] >= hash })
+
+	// Means we have cycled back to the first replica.
+	if idx == len(m.keys) {
+		idx = 0
+	}
+
+	return m.hashMap[m.keys[idx]]
+}

+ 110 - 0
go/gopath/src/github.com/go-redis/redis/internal/consistenthash/consistenthash_test.go

@@ -0,0 +1,110 @@
+/*
+Copyright 2013 Google Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package consistenthash
+
+import (
+	"fmt"
+	"strconv"
+	"testing"
+)
+
+func TestHashing(t *testing.T) {
+
+	// Override the hash function to return easier to reason about values. Assumes
+	// the keys can be converted to an integer.
+	hash := New(3, func(key []byte) uint32 {
+		i, err := strconv.Atoi(string(key))
+		if err != nil {
+			panic(err)
+		}
+		return uint32(i)
+	})
+
+	// Given the above hash function, this will give replicas with "hashes":
+	// 2, 4, 6, 12, 14, 16, 22, 24, 26
+	hash.Add("6", "4", "2")
+
+	testCases := map[string]string{
+		"2":  "2",
+		"11": "2",
+		"23": "4",
+		"27": "2",
+	}
+
+	for k, v := range testCases {
+		if hash.Get(k) != v {
+			t.Errorf("Asking for %s, should have yielded %s", k, v)
+		}
+	}
+
+	// Adds 8, 18, 28
+	hash.Add("8")
+
+	// 27 should now map to 8.
+	testCases["27"] = "8"
+
+	for k, v := range testCases {
+		if hash.Get(k) != v {
+			t.Errorf("Asking for %s, should have yielded %s", k, v)
+		}
+	}
+
+}
+
+func TestConsistency(t *testing.T) {
+	hash1 := New(1, nil)
+	hash2 := New(1, nil)
+
+	hash1.Add("Bill", "Bob", "Bonny")
+	hash2.Add("Bob", "Bonny", "Bill")
+
+	if hash1.Get("Ben") != hash2.Get("Ben") {
+		t.Errorf("Fetching 'Ben' from both hashes should be the same")
+	}
+
+	hash2.Add("Becky", "Ben", "Bobby")
+
+	if hash1.Get("Ben") != hash2.Get("Ben") ||
+		hash1.Get("Bob") != hash2.Get("Bob") ||
+		hash1.Get("Bonny") != hash2.Get("Bonny") {
+		t.Errorf("Direct matches should always return the same entry")
+	}
+
+}
+
+func BenchmarkGet8(b *testing.B)   { benchmarkGet(b, 8) }
+func BenchmarkGet32(b *testing.B)  { benchmarkGet(b, 32) }
+func BenchmarkGet128(b *testing.B) { benchmarkGet(b, 128) }
+func BenchmarkGet512(b *testing.B) { benchmarkGet(b, 512) }
+
+func benchmarkGet(b *testing.B, shards int) {
+
+	hash := New(50, nil)
+
+	var buckets []string
+	for i := 0; i < shards; i++ {
+		buckets = append(buckets, fmt.Sprintf("shard-%d", i))
+	}
+
+	hash.Add(buckets...)
+
+	b.ResetTimer()
+
+	for i := 0; i < b.N; i++ {
+		hash.Get(buckets[i&(shards-1)])
+	}
+}

+ 90 - 0
go/gopath/src/github.com/go-redis/redis/internal/error.go

@@ -0,0 +1,90 @@
+package internal
+
+import (
+	"io"
+	"net"
+	"strings"
+
+	"github.com/go-redis/redis/internal/proto"
+)
+
+func IsRetryableError(err error, retryTimeout bool) bool {
+	if err == nil {
+		return false
+	}
+	if err == io.EOF {
+		return true
+	}
+	if netErr, ok := err.(net.Error); ok {
+		if netErr.Timeout() {
+			return retryTimeout
+		}
+		return true
+	}
+	s := err.Error()
+	if s == "ERR max number of clients reached" {
+		return true
+	}
+	if strings.HasPrefix(s, "LOADING ") {
+		return true
+	}
+	if strings.HasPrefix(s, "READONLY ") {
+		return true
+	}
+	if strings.HasPrefix(s, "CLUSTERDOWN ") {
+		return true
+	}
+	return false
+}
+
+func IsRedisError(err error) bool {
+	_, ok := err.(proto.RedisError)
+	return ok
+}
+
+func IsBadConn(err error, allowTimeout bool) bool {
+	if err == nil {
+		return false
+	}
+	if IsRedisError(err) {
+		// #790
+		return IsReadOnlyError(err)
+	}
+	if allowTimeout {
+		if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
+			return false
+		}
+	}
+	return true
+}
+
+func IsMovedError(err error) (moved bool, ask bool, addr string) {
+	if !IsRedisError(err) {
+		return
+	}
+
+	s := err.Error()
+	switch {
+	case strings.HasPrefix(s, "MOVED "):
+		moved = true
+	case strings.HasPrefix(s, "ASK "):
+		ask = true
+	default:
+		return
+	}
+
+	ind := strings.LastIndex(s, " ")
+	if ind == -1 {
+		return false, false, ""
+	}
+	addr = s[ind+1:]
+	return
+}
+
+func IsLoadingError(err error) bool {
+	return strings.HasPrefix(err.Error(), "LOADING ")
+}
+
+func IsReadOnlyError(err error) bool {
+	return strings.HasPrefix(err.Error(), "READONLY ")
+}

+ 77 - 0
go/gopath/src/github.com/go-redis/redis/internal/hashtag/hashtag.go

@@ -0,0 +1,77 @@
+package hashtag
+
+import (
+	"math/rand"
+	"strings"
+)
+
+const slotNumber = 16384
+
+// CRC16 implementation according to CCITT standards.
+// Copyright 2001-2010 Georges Menie (www.menie.org)
+// Copyright 2013 The Go Authors. All rights reserved.
+// http://redis.io/topics/cluster-spec#appendix-a-crc16-reference-implementation-in-ansi-c
+var crc16tab = [256]uint16{
+	0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
+	0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
+	0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
+	0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
+	0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
+	0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
+	0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
+	0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
+	0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
+	0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
+	0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
+	0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
+	0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
+	0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
+	0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
+	0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
+	0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
+	0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
+	0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
+	0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
+	0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
+	0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
+	0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
+	0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
+	0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
+	0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
+	0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
+	0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
+	0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
+	0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
+	0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
+	0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,
+}
+
+func Key(key string) string {
+	if s := strings.IndexByte(key, '{'); s > -1 {
+		if e := strings.IndexByte(key[s+1:], '}'); e > 0 {
+			return key[s+1 : s+e+1]
+		}
+	}
+	return key
+}
+
+func RandomSlot() int {
+	return rand.Intn(slotNumber)
+}
+
+// hashSlot returns a consistent slot number between 0 and 16383
+// for any given string key.
+func Slot(key string) int {
+	if key == "" {
+		return RandomSlot()
+	}
+	key = Key(key)
+	return int(crc16sum(key)) % slotNumber
+}
+
+func crc16sum(key string) (crc uint16) {
+	for i := 0; i < len(key); i++ {
+		crc = (crc << 8) ^ crc16tab[(byte(crc>>8)^key[i])&0x00ff]
+	}
+	return
+}

+ 74 - 0
go/gopath/src/github.com/go-redis/redis/internal/hashtag/hashtag_test.go

@@ -0,0 +1,74 @@
+package hashtag
+
+import (
+	"math/rand"
+	"testing"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+func TestGinkgoSuite(t *testing.T) {
+	RegisterFailHandler(Fail)
+	RunSpecs(t, "hashtag")
+}
+
+var _ = Describe("CRC16", func() {
+
+	// http://redis.io/topics/cluster-spec#keys-distribution-model
+	It("should calculate CRC16", func() {
+		tests := []struct {
+			s string
+			n uint16
+		}{
+			{"123456789", 0x31C3},
+			{string([]byte{83, 153, 134, 118, 229, 214, 244, 75, 140, 37, 215, 215}), 21847},
+		}
+
+		for _, test := range tests {
+			Expect(crc16sum(test.s)).To(Equal(test.n), "for %s", test.s)
+		}
+	})
+
+})
+
+var _ = Describe("HashSlot", func() {
+
+	It("should calculate hash slots", func() {
+		tests := []struct {
+			key  string
+			slot int
+		}{
+			{"123456789", 12739},
+			{"{}foo", 9500},
+			{"foo{}", 5542},
+			{"foo{}{bar}", 8363},
+			{"", 10503},
+			{"", 5176},
+			{string([]byte{83, 153, 134, 118, 229, 214, 244, 75, 140, 37, 215, 215}), 5463},
+		}
+		// Empty keys receive random slot.
+		rand.Seed(100)
+
+		for _, test := range tests {
+			Expect(Slot(test.key)).To(Equal(test.slot), "for %s", test.key)
+		}
+	})
+
+	It("should extract keys from tags", func() {
+		tests := []struct {
+			one, two string
+		}{
+			{"foo{bar}", "bar"},
+			{"{foo}bar", "foo"},
+			{"{user1000}.following", "{user1000}.followers"},
+			{"foo{{bar}}zap", "{bar"},
+			{"foo{bar}{zap}", "bar"},
+		}
+
+		for _, test := range tests {
+			Expect(Slot(test.one)).To(Equal(Slot(test.two)), "for %s <-> %s", test.one, test.two)
+		}
+	})
+
+})

+ 24 - 0
go/gopath/src/github.com/go-redis/redis/internal/internal.go

@@ -0,0 +1,24 @@
+package internal
+
+import (
+	"math/rand"
+	"time"
+)
+
+// Retry backoff with jitter sleep to prevent overloaded conditions during intervals
+// https://www.awsarchitectureblog.com/2015/03/backoff.html
+func RetryBackoff(retry int, minBackoff, maxBackoff time.Duration) time.Duration {
+	if retry < 0 {
+		retry = 0
+	}
+
+	backoff := minBackoff << uint(retry)
+	if backoff > maxBackoff || backoff < minBackoff {
+		backoff = maxBackoff
+	}
+
+	if backoff == 0 {
+		return 0
+	}
+	return time.Duration(rand.Int63n(int64(backoff)))
+}

+ 18 - 0
go/gopath/src/github.com/go-redis/redis/internal/internal_test.go

@@ -0,0 +1,18 @@
+package internal
+
+import (
+	"testing"
+	"time"
+
+	. "github.com/onsi/gomega"
+)
+
+func TestRetryBackoff(t *testing.T) {
+	RegisterTestingT(t)
+
+	for i := -1; i <= 16; i++ {
+		backoff := RetryBackoff(i, time.Millisecond, 512*time.Millisecond)
+		Expect(backoff >= 0).To(BeTrue())
+		Expect(backoff <= 512*time.Millisecond).To(BeTrue())
+	}
+}

+ 8 - 0
go/gopath/src/github.com/go-redis/redis/internal/log.go

@@ -0,0 +1,8 @@
+package internal
+
+import (
+	"log"
+	"os"
+)
+
+var Logger = log.New(os.Stderr, "redis: ", log.LstdFlags|log.Lshortfile)

+ 60 - 0
go/gopath/src/github.com/go-redis/redis/internal/once.go

@@ -0,0 +1,60 @@
+/*
+Copyright 2014 The Camlistore Authors
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package internal
+
+import (
+	"sync"
+	"sync/atomic"
+)
+
+// A Once will perform a successful action exactly once.
+//
+// Unlike a sync.Once, this Once's func returns an error
+// and is re-armed on failure.
+type Once struct {
+	m    sync.Mutex
+	done uint32
+}
+
+// Do calls the function f if and only if Do has not been invoked
+// without error for this instance of Once.  In other words, given
+// 	var once Once
+// if once.Do(f) is called multiple times, only the first call will
+// invoke f, even if f has a different value in each invocation unless
+// f returns an error.  A new instance of Once is required for each
+// function to execute.
+//
+// Do is intended for initialization that must be run exactly once.  Since f
+// is niladic, it may be necessary to use a function literal to capture the
+// arguments to a function to be invoked by Do:
+// 	err := config.once.Do(func() error { return config.init(filename) })
+func (o *Once) Do(f func() error) error {
+	if atomic.LoadUint32(&o.done) == 1 {
+		return nil
+	}
+	// Slow-path.
+	o.m.Lock()
+	defer o.m.Unlock()
+	var err error
+	if o.done == 0 {
+		err = f()
+		if err == nil {
+			atomic.StoreUint32(&o.done, 1)
+		}
+	}
+	return err
+}

+ 94 - 0
go/gopath/src/github.com/go-redis/redis/internal/pool/bench_test.go

@@ -0,0 +1,94 @@
+package pool_test
+
+import (
+	"context"
+	"fmt"
+	"testing"
+	"time"
+
+	"github.com/go-redis/redis/internal/pool"
+)
+
+type poolGetPutBenchmark struct {
+	poolSize int
+}
+
+func (bm poolGetPutBenchmark) String() string {
+	return fmt.Sprintf("pool=%d", bm.poolSize)
+}
+
+func BenchmarkPoolGetPut(b *testing.B) {
+	benchmarks := []poolGetPutBenchmark{
+		{1},
+		{2},
+		{8},
+		{32},
+		{64},
+		{128},
+	}
+	for _, bm := range benchmarks {
+		b.Run(bm.String(), func(b *testing.B) {
+			connPool := pool.NewConnPool(&pool.Options{
+				Dialer:             dummyDialer,
+				PoolSize:           bm.poolSize,
+				PoolTimeout:        time.Second,
+				IdleTimeout:        time.Hour,
+				IdleCheckFrequency: time.Hour,
+			})
+
+			b.ResetTimer()
+
+			b.RunParallel(func(pb *testing.PB) {
+				for pb.Next() {
+					cn, err := connPool.Get(context.Background())
+					if err != nil {
+						b.Fatal(err)
+					}
+					connPool.Put(cn)
+				}
+			})
+		})
+	}
+}
+
+type poolGetRemoveBenchmark struct {
+	poolSize int
+}
+
+func (bm poolGetRemoveBenchmark) String() string {
+	return fmt.Sprintf("pool=%d", bm.poolSize)
+}
+
+func BenchmarkPoolGetRemove(b *testing.B) {
+	benchmarks := []poolGetRemoveBenchmark{
+		{1},
+		{2},
+		{8},
+		{32},
+		{64},
+		{128},
+	}
+	for _, bm := range benchmarks {
+		b.Run(bm.String(), func(b *testing.B) {
+			connPool := pool.NewConnPool(&pool.Options{
+				Dialer:             dummyDialer,
+				PoolSize:           bm.poolSize,
+				PoolTimeout:        time.Second,
+				IdleTimeout:        time.Hour,
+				IdleCheckFrequency: time.Hour,
+			})
+
+			b.ResetTimer()
+
+			b.RunParallel(func(pb *testing.PB) {
+				for pb.Next() {
+					cn, err := connPool.Get(context.Background())
+					if err != nil {
+						b.Fatal(err)
+					}
+					connPool.Remove(cn)
+				}
+			})
+		})
+	}
+}

+ 110 - 0
go/gopath/src/github.com/go-redis/redis/internal/pool/conn.go

@@ -0,0 +1,110 @@
+package pool
+
+import (
+	"context"
+	"net"
+	"sync/atomic"
+	"time"
+
+	"github.com/go-redis/redis/internal/proto"
+)
+
+var noDeadline = time.Time{}
+
+type Conn struct {
+	netConn net.Conn
+
+	rd *proto.Reader
+	wr *proto.Writer
+
+	Inited    bool
+	pooled    bool
+	createdAt time.Time
+	usedAt    int64 // atomic
+}
+
+func NewConn(netConn net.Conn) *Conn {
+	cn := &Conn{
+		netConn:   netConn,
+		createdAt: time.Now(),
+	}
+	cn.rd = proto.NewReader(netConn)
+	cn.wr = proto.NewWriter(netConn)
+	cn.SetUsedAt(time.Now())
+	return cn
+}
+
+func (cn *Conn) UsedAt() time.Time {
+	unix := atomic.LoadInt64(&cn.usedAt)
+	return time.Unix(unix, 0)
+}
+
+func (cn *Conn) SetUsedAt(tm time.Time) {
+	atomic.StoreInt64(&cn.usedAt, tm.Unix())
+}
+
+func (cn *Conn) SetNetConn(netConn net.Conn) {
+	cn.netConn = netConn
+	cn.rd.Reset(netConn)
+	cn.wr.Reset(netConn)
+}
+
+func (cn *Conn) Write(b []byte) (int, error) {
+	return cn.netConn.Write(b)
+}
+
+func (cn *Conn) RemoteAddr() net.Addr {
+	return cn.netConn.RemoteAddr()
+}
+
+func (cn *Conn) WithReader(ctx context.Context, timeout time.Duration, fn func(rd *proto.Reader) error) error {
+	tm := cn.deadline(ctx, timeout)
+	_ = cn.netConn.SetReadDeadline(tm)
+	return fn(cn.rd)
+}
+
+func (cn *Conn) WithWriter(
+	ctx context.Context, timeout time.Duration, fn func(wr *proto.Writer) error,
+) error {
+	tm := cn.deadline(ctx, timeout)
+	_ = cn.netConn.SetWriteDeadline(tm)
+
+	firstErr := fn(cn.wr)
+	err := cn.wr.Flush()
+	if err != nil && firstErr == nil {
+		firstErr = err
+	}
+	return firstErr
+}
+
+func (cn *Conn) Close() error {
+	return cn.netConn.Close()
+}
+
+func (cn *Conn) deadline(ctx context.Context, timeout time.Duration) time.Time {
+	tm := time.Now()
+	cn.SetUsedAt(tm)
+
+	if timeout > 0 {
+		tm = tm.Add(timeout)
+	}
+
+	if ctx != nil {
+		deadline, ok := ctx.Deadline()
+		if ok {
+			if timeout == 0 {
+				return deadline
+			}
+			if deadline.Before(tm) {
+				return deadline
+			}
+			return tm
+		}
+	}
+
+	if timeout > 0 {
+		return tm
+	}
+
+	return noDeadline
+}

+ 7 - 0
go/gopath/src/github.com/go-redis/redis/internal/pool/export_test.go

@@ -0,0 +1,7 @@
+package pool
+
+import "time"
+
+func (cn *Conn) SetCreatedAt(tm time.Time) {
+	cn.createdAt = tm
+}

+ 36 - 0
go/gopath/src/github.com/go-redis/redis/internal/pool/main_test.go

@@ -0,0 +1,36 @@
+package pool_test
+
+import (
+	"context"
+	"net"
+	"sync"
+	"testing"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+func TestGinkgoSuite(t *testing.T) {
+	RegisterFailHandler(Fail)
+	RunSpecs(t, "pool")
+}
+
+func perform(n int, cbs ...func(int)) {
+	var wg sync.WaitGroup
+	for _, cb := range cbs {
+		for i := 0; i < n; i++ {
+			wg.Add(1)
+			go func(cb func(int), i int) {
+				defer GinkgoRecover()
+				defer wg.Done()
+
+				cb(i)
+			}(cb, i)
+		}
+	}
+	wg.Wait()
+}
+
+func dummyDialer(context.Context) (net.Conn, error) {
+	return &net.TCPConn{}, nil
+}

+ 491 - 0
go/gopath/src/github.com/go-redis/redis/internal/pool/pool.go

@@ -0,0 +1,491 @@
+package pool
+
+import (
+	"context"
+	"errors"
+	"net"
+	"sync"
+	"sync/atomic"
+	"time"
+
+	"github.com/go-redis/redis/internal"
+)
+
+var ErrClosed = errors.New("redis: client is closed")
+var ErrPoolTimeout = errors.New("redis: connection pool timeout")
+
+var timers = sync.Pool{
+	New: func() interface{} {
+		t := time.NewTimer(time.Hour)
+		t.Stop()
+		return t
+	},
+}
+
+// Stats contains pool state information and accumulated stats.
+type Stats struct {
+	Hits     uint32 // number of times free connection was found in the pool
+	Misses   uint32 // number of times free connection was NOT found in the pool
+	Timeouts uint32 // number of times a wait timeout occurred
+
+	TotalConns uint32 // number of total connections in the pool
+	IdleConns  uint32 // number of idle connections in the pool
+	StaleConns uint32 // number of stale connections removed from the pool
+}
+
+type Pooler interface {
+	NewConn(context.Context) (*Conn, error)
+	CloseConn(*Conn) error
+
+	Get(context.Context) (*Conn, error)
+	Put(*Conn)
+	Remove(*Conn)
+
+	Len() int
+	IdleLen() int
+	Stats() *Stats
+
+	Close() error
+}
+
+type Options struct {
+	Dialer  func(c context.Context) (net.Conn, error)
+	OnClose func(*Conn) error
+
+	PoolSize           int
+	MinIdleConns       int
+	MaxConnAge         time.Duration
+	PoolTimeout        time.Duration
+	IdleTimeout        time.Duration
+	IdleCheckFrequency time.Duration
+}
+
+type ConnPool struct {
+	opt *Options
+
+	dialErrorsNum uint32 // atomic
+
+	lastDialErrorMu sync.RWMutex
+	lastDialError   error
+
+	queue chan struct{}
+
+	connsMu      sync.Mutex
+	conns        []*Conn
+	idleConns    []*Conn
+	poolSize     int
+	idleConnsLen int
+
+	stats Stats
+
+	_closed uint32 // atomic
+}
+
+var _ Pooler = (*ConnPool)(nil)
+
+func NewConnPool(opt *Options) *ConnPool {
+	p := &ConnPool{
+		opt: opt,
+
+		queue:     make(chan struct{}, opt.PoolSize),
+		conns:     make([]*Conn, 0, opt.PoolSize),
+		idleConns: make([]*Conn, 0, opt.PoolSize),
+	}
+
+	for i := 0; i < opt.MinIdleConns; i++ {
+		p.checkMinIdleConns()
+	}
+
+	if opt.IdleTimeout > 0 && opt.IdleCheckFrequency > 0 {
+		go p.reaper(opt.IdleCheckFrequency)
+	}
+
+	return p
+}
+
+func (p *ConnPool) checkMinIdleConns() {
+	if p.opt.MinIdleConns == 0 {
+		return
+	}
+	if p.poolSize < p.opt.PoolSize && p.idleConnsLen < p.opt.MinIdleConns {
+		p.poolSize++
+		p.idleConnsLen++
+		go p.addIdleConn()
+	}
+}
+
+func (p *ConnPool) addIdleConn() {
+	cn, err := p.newConn(context.TODO(), true)
+	if err != nil {
+		return
+	}
+
+	p.connsMu.Lock()
+	p.conns = append(p.conns, cn)
+	p.idleConns = append(p.idleConns, cn)
+	p.connsMu.Unlock()
+}
+
+func (p *ConnPool) NewConn(ctx context.Context) (*Conn, error) {
+	return p._NewConn(ctx, false)
+}
+
+func (p *ConnPool) _NewConn(ctx context.Context, pooled bool) (*Conn, error) {
+	cn, err := p.newConn(ctx, pooled)
+	if err != nil {
+		return nil, err
+	}
+
+	p.connsMu.Lock()
+	p.conns = append(p.conns, cn)
+	if pooled {
+		// If pool is full remove the cn on next Put.
+		if p.poolSize >= p.opt.PoolSize {
+			cn.pooled = false
+		} else {
+			p.poolSize++
+		}
+	}
+	p.connsMu.Unlock()
+	return cn, nil
+}
+
+func (p *ConnPool) newConn(ctx context.Context, pooled bool) (*Conn, error) {
+	if p.closed() {
+		return nil, ErrClosed
+	}
+
+	if atomic.LoadUint32(&p.dialErrorsNum) >= uint32(p.opt.PoolSize) {
+		return nil, p.getLastDialError()
+	}
+
+	netConn, err := p.opt.Dialer(ctx)
+	if err != nil {
+		p.setLastDialError(err)
+		if atomic.AddUint32(&p.dialErrorsNum, 1) == uint32(p.opt.PoolSize) {
+			go p.tryDial()
+		}
+		return nil, err
+	}
+
+	cn := NewConn(netConn)
+	cn.pooled = pooled
+	return cn, nil
+}
+
+func (p *ConnPool) tryDial() {
+	for {
+		if p.closed() {
+			return
+		}
+
+		conn, err := p.opt.Dialer(context.Background())
+		if err != nil {
+			p.setLastDialError(err)
+			time.Sleep(time.Second)
+			continue
+		}
+
+		atomic.StoreUint32(&p.dialErrorsNum, 0)
+		_ = conn.Close()
+		return
+	}
+}
+
+func (p *ConnPool) setLastDialError(err error) {
+	p.lastDialErrorMu.Lock()
+	p.lastDialError = err
+	p.lastDialErrorMu.Unlock()
+}
+
+func (p *ConnPool) getLastDialError() error {
+	p.lastDialErrorMu.RLock()
+	err := p.lastDialError
+	p.lastDialErrorMu.RUnlock()
+	return err
+}
+
+// Get returns existed connection from the pool or creates a new one.
+func (p *ConnPool) Get(ctx context.Context) (*Conn, error) {
+	if p.closed() {
+		return nil, ErrClosed
+	}
+
+	err := p.waitTurn(ctx)
+	if err != nil {
+		return nil, err
+	}
+
+	for {
+		p.connsMu.Lock()
+		cn := p.popIdle()
+		p.connsMu.Unlock()
+
+		if cn == nil {
+			break
+		}
+
+		if p.isStaleConn(cn) {
+			_ = p.CloseConn(cn)
+			continue
+		}
+
+		atomic.AddUint32(&p.stats.Hits, 1)
+		return cn, nil
+	}
+
+	atomic.AddUint32(&p.stats.Misses, 1)
+
+	newcn, err := p._NewConn(ctx, true)
+	if err != nil {
+		p.freeTurn()
+		return nil, err
+	}
+
+	return newcn, nil
+}
+
+func (p *ConnPool) getTurn() {
+	p.queue <- struct{}{}
+}
+
+func (p *ConnPool) waitTurn(ctx context.Context) error {
+	select {
+	case <-ctx.Done():
+		return ctx.Err()
+	default:
+	}
+
+	select {
+	case p.queue <- struct{}{}:
+		return nil
+	default:
+	}
+
+	timer := timers.Get().(*time.Timer)
+	timer.Reset(p.opt.PoolTimeout)
+
+	select {
+	case <-ctx.Done():
+		if !timer.Stop() {
+			<-timer.C
+		}
+		timers.Put(timer)
+		return ctx.Err()
+	case p.queue <- struct{}{}:
+		if !timer.Stop() {
+			<-timer.C
+		}
+		timers.Put(timer)
+		return nil
+	case <-timer.C:
+		timers.Put(timer)
+		atomic.AddUint32(&p.stats.Timeouts, 1)
+		return ErrPoolTimeout
+	}
+}
+
+func (p *ConnPool) freeTurn() {
+	<-p.queue
+}
+
+func (p *ConnPool) popIdle() *Conn {
+	if len(p.idleConns) == 0 {
+		return nil
+	}
+
+	idx := len(p.idleConns) - 1
+	cn := p.idleConns[idx]
+	p.idleConns = p.idleConns[:idx]
+	p.idleConnsLen--
+	p.checkMinIdleConns()
+	return cn
+}
+
+func (p *ConnPool) Put(cn *Conn) {
+	if !cn.pooled {
+		p.Remove(cn)
+		return
+	}
+
+	p.connsMu.Lock()
+	p.idleConns = append(p.idleConns, cn)
+	p.idleConnsLen++
+	p.connsMu.Unlock()
+	p.freeTurn()
+}
+
+func (p *ConnPool) Remove(cn *Conn) {
+	p.removeConnWithLock(cn)
+	p.freeTurn()
+	_ = p.closeConn(cn)
+}
+
+func (p *ConnPool) CloseConn(cn *Conn) error {
+	p.removeConnWithLock(cn)
+	return p.closeConn(cn)
+}
+
+func (p *ConnPool) removeConnWithLock(cn *Conn) {
+	p.connsMu.Lock()
+	p.removeConn(cn)
+	p.connsMu.Unlock()
+}
+
+func (p *ConnPool) removeConn(cn *Conn) {
+	for i, c := range p.conns {
+		if c == cn {
+			p.conns = append(p.conns[:i], p.conns[i+1:]...)
+			if cn.pooled {
+				p.poolSize--
+				p.checkMinIdleConns()
+			}
+			return
+		}
+	}
+}
+
+func (p *ConnPool) closeConn(cn *Conn) error {
+	if p.opt.OnClose != nil {
+		_ = p.opt.OnClose(cn)
+	}
+	return cn.Close()
+}
+
+// Len returns total number of connections.
+func (p *ConnPool) Len() int {
+	p.connsMu.Lock()
+	n := len(p.conns)
+	p.connsMu.Unlock()
+	return n
+}
+
+// IdleLen returns number of idle connections.
+func (p *ConnPool) IdleLen() int {
+	p.connsMu.Lock()
+	n := p.idleConnsLen
+	p.connsMu.Unlock()
+	return n
+}
+
+func (p *ConnPool) Stats() *Stats {
+	idleLen := p.IdleLen()
+	return &Stats{
+		Hits:     atomic.LoadUint32(&p.stats.Hits),
+		Misses:   atomic.LoadUint32(&p.stats.Misses),
+		Timeouts: atomic.LoadUint32(&p.stats.Timeouts),
+
+		TotalConns: uint32(p.Len()),
+		IdleConns:  uint32(idleLen),
+		StaleConns: atomic.LoadUint32(&p.stats.StaleConns),
+	}
+}
+
+func (p *ConnPool) closed() bool {
+	return atomic.LoadUint32(&p._closed) == 1
+}
+
+func (p *ConnPool) Filter(fn func(*Conn) bool) error {
+	var firstErr error
+	p.connsMu.Lock()
+	for _, cn := range p.conns {
+		if fn(cn) {
+			if err := p.closeConn(cn); err != nil && firstErr == nil {
+				firstErr = err
+			}
+		}
+	}
+	p.connsMu.Unlock()
+	return firstErr
+}
+
+func (p *ConnPool) Close() error {
+	if !atomic.CompareAndSwapUint32(&p._closed, 0, 1) {
+		return ErrClosed
+	}
+
+	var firstErr error
+	p.connsMu.Lock()
+	for _, cn := range p.conns {
+		if err := p.closeConn(cn); err != nil && firstErr == nil {
+			firstErr = err
+		}
+	}
+	p.conns = nil
+	p.poolSize = 0
+	p.idleConns = nil
+	p.idleConnsLen = 0
+	p.connsMu.Unlock()
+
+	return firstErr
+}
+
+func (p *ConnPool) reaper(frequency time.Duration) {
+	ticker := time.NewTicker(frequency)
+	defer ticker.Stop()
+
+	for range ticker.C {
+		if p.closed() {
+			break
+		}
+		_, err := p.ReapStaleConns()
+		if err != nil {
+			internal.Logger.Printf("ReapStaleConns failed: %s", err)
+			continue
+		}
+	}
+}
+
+func (p *ConnPool) ReapStaleConns() (int, error) {
+	var n int
+	for {
+		p.getTurn()
+
+		p.connsMu.Lock()
+		cn := p.reapStaleConn()
+		p.connsMu.Unlock()
+		p.freeTurn()
+
+		if cn != nil {
+			_ = p.closeConn(cn)
+			n++
+		} else {
+			break
+		}
+	}
+	atomic.AddUint32(&p.stats.StaleConns, uint32(n))
+	return n, nil
+}
+
+func (p *ConnPool) reapStaleConn() *Conn {
+	if len(p.idleConns) == 0 {
+		return nil
+	}
+
+	cn := p.idleConns[0]
+	if !p.isStaleConn(cn) {
+		return nil
+	}
+
+	p.idleConns = append(p.idleConns[:0], p.idleConns[1:]...)
+	p.idleConnsLen--
+	p.removeConn(cn)
+
+	return cn
+}
+
+func (p *ConnPool) isStaleConn(cn *Conn) bool {
+	if p.opt.IdleTimeout == 0 && p.opt.MaxConnAge == 0 {
+		return false
+	}
+
+	now := time.Now()
+	if p.opt.IdleTimeout > 0 && now.Sub(cn.UsedAt()) >= p.opt.IdleTimeout {
+		return true
+	}
+	if p.opt.MaxConnAge > 0 && now.Sub(cn.createdAt) >= p.opt.MaxConnAge {
+		return true
+	}
+
+	return false
+}

+ 55 - 0
go/gopath/src/github.com/go-redis/redis/internal/pool/pool_single.go

@@ -0,0 +1,55 @@
+package pool
+
+import "context"
+
+type SingleConnPool struct {
+	cn *Conn
+}
+
+var _ Pooler = (*SingleConnPool)(nil)
+
+func NewSingleConnPool(cn *Conn) *SingleConnPool {
+	return &SingleConnPool{
+		cn: cn,
+	}
+}
+
+func (p *SingleConnPool) NewConn(context.Context) (*Conn, error) {
+	panic("not implemented")
+}
+
+func (p *SingleConnPool) CloseConn(*Conn) error {
+	panic("not implemented")
+}
+
+func (p *SingleConnPool) Get(ctx context.Context) (*Conn, error) {
+	return p.cn, nil
+}
+
+func (p *SingleConnPool) Put(cn *Conn) {
+	if p.cn != cn {
+		panic("p.cn != cn")
+	}
+}
+
+func (p *SingleConnPool) Remove(cn *Conn) {
+	if p.cn != cn {
+		panic("p.cn != cn")
+	}
+}
+
+func (p *SingleConnPool) Len() int {
+	return 1
+}
+
+func (p *SingleConnPool) IdleLen() int {
+	return 0
+}
+
+func (p *SingleConnPool) Stats() *Stats {
+	return nil
+}
+
+func (p *SingleConnPool) Close() error {
+	return nil
+}

+ 112 - 0
go/gopath/src/github.com/go-redis/redis/internal/pool/pool_sticky.go

@@ -0,0 +1,112 @@
+package pool
+
+import (
+	"context"
+	"sync"
+)
+
+type StickyConnPool struct {
+	pool     *ConnPool
+	reusable bool
+
+	cn     *Conn
+	closed bool
+	mu     sync.Mutex
+}
+
+var _ Pooler = (*StickyConnPool)(nil)
+
+func NewStickyConnPool(pool *ConnPool, reusable bool) *StickyConnPool {
+	return &StickyConnPool{
+		pool:     pool,
+		reusable: reusable,
+	}
+}
+
+func (p *StickyConnPool) NewConn(context.Context) (*Conn, error) {
+	panic("not implemented")
+}
+
+func (p *StickyConnPool) CloseConn(*Conn) error {
+	panic("not implemented")
+}
+
+func (p *StickyConnPool) Get(ctx context.Context) (*Conn, error) {
+	p.mu.Lock()
+	defer p.mu.Unlock()
+
+	if p.closed {
+		return nil, ErrClosed
+	}
+	if p.cn != nil {
+		return p.cn, nil
+	}
+
+	cn, err := p.pool.Get(ctx)
+	if err != nil {
+		return nil, err
+	}
+
+	p.cn = cn
+	return cn, nil
+}
+
+func (p *StickyConnPool) putUpstream() {
+	p.pool.Put(p.cn)
+	p.cn = nil
+}
+
+func (p *StickyConnPool) Put(cn *Conn) {}
+
+func (p *StickyConnPool) removeUpstream() {
+	p.pool.Remove(p.cn)
+	p.cn = nil
+}
+
+func (p *StickyConnPool) Remove(cn *Conn) {
+	p.removeUpstream()
+}
+
+func (p *StickyConnPool) Len() int {
+	p.mu.Lock()
+	defer p.mu.Unlock()
+
+	if p.cn == nil {
+		return 0
+	}
+	return 1
+}
+
+func (p *StickyConnPool) IdleLen() int {
+	p.mu.Lock()
+	defer p.mu.Unlock()
+
+	if p.cn == nil {
+		return 1
+	}
+	return 0
+}
+
+func (p *StickyConnPool) Stats() *Stats {
+	return nil
+}
+
+func (p *StickyConnPool) Close() error {
+	p.mu.Lock()
+	defer p.mu.Unlock()
+
+	if p.closed {
+		return ErrClosed
+	}
+	p.closed = true
+
+	if p.cn != nil {
+		if p.reusable {
+			p.putUpstream()
+		} else {
+			p.removeUpstream()
+		}
+	}
+
+	return nil
+}

+ 421 - 0
go/gopath/src/github.com/go-redis/redis/internal/pool/pool_test.go

@@ -0,0 +1,421 @@
+package pool_test
+
+import (
+	"context"
+	"sync"
+	"testing"
+	"time"
+
+	"github.com/go-redis/redis/internal/pool"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("ConnPool", func() {
+	c := context.Background()
+	var connPool *pool.ConnPool
+
+	BeforeEach(func() {
+		connPool = pool.NewConnPool(&pool.Options{
+			Dialer:             dummyDialer,
+			PoolSize:           10,
+			PoolTimeout:        time.Hour,
+			IdleTimeout:        time.Millisecond,
+			IdleCheckFrequency: time.Millisecond,
+		})
+	})
+
+	AfterEach(func() {
+		connPool.Close()
+	})
+
+	It("should unblock client when conn is removed", func() {
+		// Reserve one connection.
+		cn, err := connPool.Get(c)
+		Expect(err).NotTo(HaveOccurred())
+
+		// Reserve all other connections.
+		var cns []*pool.Conn
+		for i := 0; i < 9; i++ {
+			cn, err := connPool.Get(c)
+			Expect(err).NotTo(HaveOccurred())
+			cns = append(cns, cn)
+		}
+
+		started := make(chan bool, 1)
+		done := make(chan bool, 1)
+		go func() {
+			defer GinkgoRecover()
+
+			started <- true
+			_, err := connPool.Get(c)
+			Expect(err).NotTo(HaveOccurred())
+			done <- true
+
+			connPool.Put(cn)
+		}()
+		<-started
+
+		// Check that Get is blocked.
+		select {
+		case <-done:
+			Fail("Get is not blocked")
+		case <-time.After(time.Millisecond):
+			// ok
+		}
+
+		connPool.Remove(cn)
+
+		// Check that Get is unblocked.
+		select {
+		case <-done:
+			// ok
+		case <-time.After(time.Second):
+			Fail("Get is not unblocked")
+		}
+
+		for _, cn := range cns {
+			connPool.Put(cn)
+		}
+	})
+})
+
+var _ = Describe("MinIdleConns", func() {
+	c := context.Background()
+	const poolSize = 100
+	var minIdleConns int
+	var connPool *pool.ConnPool
+
+	newConnPool := func() *pool.ConnPool {
+		connPool := pool.NewConnPool(&pool.Options{
+			Dialer:             dummyDialer,
+			PoolSize:           poolSize,
+			MinIdleConns:       minIdleConns,
+			PoolTimeout:        100 * time.Millisecond,
+			IdleTimeout:        -1,
+			IdleCheckFrequency: -1,
+		})
+		Eventually(func() int {
+			return connPool.Len()
+		}).Should(Equal(minIdleConns))
+		return connPool
+	}
+
+	assert := func() {
+		It("has idle connections when created", func() {
+			Expect(connPool.Len()).To(Equal(minIdleConns))
+			Expect(connPool.IdleLen()).To(Equal(minIdleConns))
+		})
+
+		Context("after Get", func() {
+			var cn *pool.Conn
+
+			BeforeEach(func() {
+				var err error
+				cn, err = connPool.Get(c)
+				Expect(err).NotTo(HaveOccurred())
+
+				Eventually(func() int {
+					return connPool.Len()
+				}).Should(Equal(minIdleConns + 1))
+			})
+
+			It("has idle connections", func() {
+				Expect(connPool.Len()).To(Equal(minIdleConns + 1))
+				Expect(connPool.IdleLen()).To(Equal(minIdleConns))
+			})
+
+			Context("after Remove", func() {
+				BeforeEach(func() {
+					connPool.Remove(cn)
+				})
+
+				It("has idle connections", func() {
+					Expect(connPool.Len()).To(Equal(minIdleConns))
+					Expect(connPool.IdleLen()).To(Equal(minIdleConns))
+				})
+			})
+		})
+
+		Describe("Get does not exceed pool size", func() {
+			var mu sync.RWMutex
+			var cns []*pool.Conn
+
+			BeforeEach(func() {
+				cns = make([]*pool.Conn, 0)
+
+				perform(poolSize, func(_ int) {
+					defer GinkgoRecover()
+
+					cn, err := connPool.Get(c)
+					Expect(err).NotTo(HaveOccurred())
+					mu.Lock()
+					cns = append(cns, cn)
+					mu.Unlock()
+				})
+
+				Eventually(func() int {
+					return connPool.Len()
+				}).Should(BeNumerically(">=", poolSize))
+			})
+
+			It("Get is blocked", func() {
+				done := make(chan struct{})
+				go func() {
+					connPool.Get(c)
+					close(done)
+				}()
+
+				select {
+				case <-done:
+					Fail("Get is not blocked")
+				case <-time.After(time.Millisecond):
+					// ok
+				}
+
+				select {
+				case <-done:
+					// ok
+				case <-time.After(time.Second):
+					Fail("Get is not unblocked")
+				}
+			})
+
+			Context("after Put", func() {
+				BeforeEach(func() {
+					perform(len(cns), func(i int) {
+						mu.RLock()
+						connPool.Put(cns[i])
+						mu.RUnlock()
+					})
+
+					Eventually(func() int {
+						return connPool.Len()
+					}).Should(Equal(poolSize))
+				})
+
+				It("pool.Len is back to normal", func() {
+					Expect(connPool.Len()).To(Equal(poolSize))
+					Expect(connPool.IdleLen()).To(Equal(poolSize))
+				})
+			})
+
+			Context("after Remove", func() {
+				BeforeEach(func() {
+					perform(len(cns), func(i int) {
+						mu.RLock()
+						connPool.Remove(cns[i])
+						mu.RUnlock()
+					})
+
+					Eventually(func() int {
+						return connPool.Len()
+					}).Should(Equal(minIdleConns))
+				})
+
+				It("has idle connections", func() {
+					Expect(connPool.Len()).To(Equal(minIdleConns))
+					Expect(connPool.IdleLen()).To(Equal(minIdleConns))
+				})
+			})
+		})
+	}
+
+	Context("minIdleConns = 1", func() {
+		BeforeEach(func() {
+			minIdleConns = 1
+			connPool = newConnPool()
+		})
+
+		AfterEach(func() {
+			connPool.Close()
+		})
+
+		assert()
+	})
+
+	Context("minIdleConns = 32", func() {
+		BeforeEach(func() {
+			minIdleConns = 32
+			connPool = newConnPool()
+		})
+
+		AfterEach(func() {
+			connPool.Close()
+		})
+
+		assert()
+	})
+})
+
+var _ = Describe("conns reaper", func() {
+	c := context.Background()
+
+	const idleTimeout = time.Minute
+	const maxAge = time.Hour
+
+	var connPool *pool.ConnPool
+	var conns, staleConns, closedConns []*pool.Conn
+
+	assert := func(typ string) {
+		BeforeEach(func() {
+			closedConns = nil
+			connPool = pool.NewConnPool(&pool.Options{
+				Dialer:             dummyDialer,
+				PoolSize:           10,
+				IdleTimeout:        idleTimeout,
+				MaxConnAge:         maxAge,
+				PoolTimeout:        time.Second,
+				IdleCheckFrequency: time.Hour,
+				OnClose: func(cn *pool.Conn) error {
+					closedConns = append(closedConns, cn)
+					return nil
+				},
+			})
+
+			conns = nil
+
+			// add stale connections
+			staleConns = nil
+			for i := 0; i < 3; i++ {
+				cn, err := connPool.Get(c)
+				Expect(err).NotTo(HaveOccurred())
+				switch typ {
+				case "idle":
+					cn.SetUsedAt(time.Now().Add(-2 * idleTimeout))
+				case "aged":
+					cn.SetCreatedAt(time.Now().Add(-2 * maxAge))
+				}
+				conns = append(conns, cn)
+				staleConns = append(staleConns, cn)
+			}
+
+			// add fresh connections
+			for i := 0; i < 3; i++ {
+				cn, err := connPool.Get(c)
+				Expect(err).NotTo(HaveOccurred())
+				conns = append(conns, cn)
+			}
+
+			for _, cn := range conns {
+				connPool.Put(cn)
+			}
+
+			Expect(connPool.Len()).To(Equal(6))
+			Expect(connPool.IdleLen()).To(Equal(6))
+
+			n, err := connPool.ReapStaleConns()
+			Expect(err).NotTo(HaveOccurred())
+			Expect(n).To(Equal(3))
+		})
+
+		AfterEach(func() {
+			_ = connPool.Close()
+			Expect(connPool.Len()).To(Equal(0))
+			Expect(connPool.IdleLen()).To(Equal(0))
+			Expect(len(closedConns)).To(Equal(len(conns)))
+			Expect(closedConns).To(ConsistOf(conns))
+		})
+
+		It("reaps stale connections", func() {
+			Expect(connPool.Len()).To(Equal(3))
+			Expect(connPool.IdleLen()).To(Equal(3))
+		})
+
+		It("does not reap fresh connections", func() {
+			n, err := connPool.ReapStaleConns()
+			Expect(err).NotTo(HaveOccurred())
+			Expect(n).To(Equal(0))
+		})
+
+		It("stale connections are closed", func() {
+			Expect(len(closedConns)).To(Equal(len(staleConns)))
+			Expect(closedConns).To(ConsistOf(staleConns))
+		})
+
+		It("pool is functional", func() {
+			for j := 0; j < 3; j++ {
+				var freeCns []*pool.Conn
+				for i := 0; i < 3; i++ {
+					cn, err := connPool.Get(c)
+					Expect(err).NotTo(HaveOccurred())
+					Expect(cn).NotTo(BeNil())
+					freeCns = append(freeCns, cn)
+				}
+
+				Expect(connPool.Len()).To(Equal(3))
+				Expect(connPool.IdleLen()).To(Equal(0))
+
+				cn, err := connPool.Get(c)
+				Expect(err).NotTo(HaveOccurred())
+				Expect(cn).NotTo(BeNil())
+				conns = append(conns, cn)
+
+				Expect(connPool.Len()).To(Equal(4))
+				Expect(connPool.IdleLen()).To(Equal(0))
+
+				connPool.Remove(cn)
+
+				Expect(connPool.Len()).To(Equal(3))
+				Expect(connPool.IdleLen()).To(Equal(0))
+
+				for _, cn := range freeCns {
+					connPool.Put(cn)
+				}
+
+				Expect(connPool.Len()).To(Equal(3))
+				Expect(connPool.IdleLen()).To(Equal(3))
+			}
+		})
+	}
+
+	assert("idle")
+	assert("aged")
+})
+
+var _ = Describe("race", func() {
+	c := context.Background()
+	var connPool *pool.ConnPool
+	var C, N int
+
+	BeforeEach(func() {
+		C, N = 10, 1000
+		if testing.Short() {
+			C = 4
+			N = 100
+		}
+	})
+
+	AfterEach(func() {
+		connPool.Close()
+	})
+
+	It("does not happen on Get, Put, and Remove", func() {
+		connPool = pool.NewConnPool(&pool.Options{
+			Dialer:             dummyDialer,
+			PoolSize:           10,
+			PoolTimeout:        time.Minute,
+			IdleTimeout:        time.Millisecond,
+			IdleCheckFrequency: time.Millisecond,
+		})
+
+		perform(C, func(id int) {
+			for i := 0; i < N; i++ {
+				cn, err := connPool.Get(c)
+				Expect(err).NotTo(HaveOccurred())
+				if err == nil {
+					connPool.Put(cn)
+				}
+			}
+		}, func(id int) {
+			for i := 0; i < N; i++ {
+				cn, err := connPool.Get(c)
+				Expect(err).NotTo(HaveOccurred())
+				if err == nil {
+					connPool.Remove(cn)
+				}
+			}
+		})
+	})
+})

+ 13 - 0
go/gopath/src/github.com/go-redis/redis/internal/proto/proto_test.go

@@ -0,0 +1,13 @@
+package proto_test
+
+import (
+	"testing"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+func TestGinkgoSuite(t *testing.T) {
+	RegisterFailHandler(Fail)
+	RunSpecs(t, "proto")
+}

+ 294 - 0
go/gopath/src/github.com/go-redis/redis/internal/proto/reader.go

@@ -0,0 +1,294 @@
+package proto
+
+import (
+	"bufio"
+	"fmt"
+	"io"
+	"strconv"
+
+	"github.com/go-redis/redis/internal/util"
+)
+
+const (
+	ErrorReply  = '-'
+	StatusReply = '+'
+	IntReply    = ':'
+	StringReply = '$'
+	ArrayReply  = '*'
+)
+
+//------------------------------------------------------------------------------
+
+const Nil = RedisError("redis: nil")
+
+type RedisError string
+
+func (e RedisError) Error() string { return string(e) }
+
+//------------------------------------------------------------------------------
+
+type MultiBulkParse func(*Reader, int64) (interface{}, error)
+
+type Reader struct {
+	rd   *bufio.Reader
+	_buf []byte
+}
+
+func NewReader(rd io.Reader) *Reader {
+	return &Reader{
+		rd:   bufio.NewReader(rd),
+		_buf: make([]byte, 64),
+	}
+}
+
+func (r *Reader) Reset(rd io.Reader) {
+	r.rd.Reset(rd)
+}
+
+func (r *Reader) ReadLine() ([]byte, error) {
+	line, isPrefix, err := r.rd.ReadLine()
+	if err != nil {
+		return nil, err
+	}
+	if isPrefix {
+		return nil, bufio.ErrBufferFull
+	}
+	if len(line) == 0 {
+		return nil, fmt.Errorf("redis: reply is empty")
+	}
+	if isNilReply(line) {
+		return nil, Nil
+	}
+	return line, nil
+}
+
+func (r *Reader) ReadReply(m MultiBulkParse) (interface{}, error) {
+	line, err := r.ReadLine()
+	if err != nil {
+		return nil, err
+	}
+
+	switch line[0] {
+	case ErrorReply:
+		return nil, ParseErrorReply(line)
+	case StatusReply:
+		return string(line[1:]), nil
+	case IntReply:
+		return util.ParseInt(line[1:], 10, 64)
+	case StringReply:
+		return r.readStringReply(line)
+	case ArrayReply:
+		n, err := parseArrayLen(line)
+		if err != nil {
+			return nil, err
+		}
+		if m == nil {
+			err := fmt.Errorf("redis: got %.100q, but multi bulk parser is nil", line)
+			return nil, err
+		}
+		return m(r, n)
+	}
+	return nil, fmt.Errorf("redis: can't parse %.100q", line)
+}
+
+func (r *Reader) ReadIntReply() (int64, error) {
+	line, err := r.ReadLine()
+	if err != nil {
+		return 0, err
+	}
+	switch line[0] {
+	case ErrorReply:
+		return 0, ParseErrorReply(line)
+	case IntReply:
+		return util.ParseInt(line[1:], 10, 64)
+	default:
+		return 0, fmt.Errorf("redis: can't parse int reply: %.100q", line)
+	}
+}
+
+func (r *Reader) ReadString() (string, error) {
+	line, err := r.ReadLine()
+	if err != nil {
+		return "", err
+	}
+	switch line[0] {
+	case ErrorReply:
+		return "", ParseErrorReply(line)
+	case StringReply:
+		return r.readStringReply(line)
+	case StatusReply:
+		return string(line[1:]), nil
+	case IntReply:
+		return string(line[1:]), nil
+	default:
+		return "", fmt.Errorf("redis: can't parse reply=%.100q reading string", line)
+	}
+}
+
+func (r *Reader) readStringReply(line []byte) (string, error) {
+	if isNilReply(line) {
+		return "", Nil
+	}
+
+	replyLen, err := strconv.Atoi(string(line[1:]))
+	if err != nil {
+		return "", err
+	}
+
+	b := make([]byte, replyLen+2)
+	_, err = io.ReadFull(r.rd, b)
+	if err != nil {
+		return "", err
+	}
+
+	return util.BytesToString(b[:replyLen]), nil
+}
+
+func (r *Reader) ReadArrayReply(m MultiBulkParse) (interface{}, error) {
+	line, err := r.ReadLine()
+	if err != nil {
+		return nil, err
+	}
+	switch line[0] {
+	case ErrorReply:
+		return nil, ParseErrorReply(line)
+	case ArrayReply:
+		n, err := parseArrayLen(line)
+		if err != nil {
+			return nil, err
+		}
+		return m(r, n)
+	default:
+		return nil, fmt.Errorf("redis: can't parse array reply: %.100q", line)
+	}
+}
+
+func (r *Reader) ReadArrayLen() (int64, error) {
+	line, err := r.ReadLine()
+	if err != nil {
+		return 0, err
+	}
+	switch line[0] {
+	case ErrorReply:
+		return 0, ParseErrorReply(line)
+	case ArrayReply:
+		return parseArrayLen(line)
+	default:
+		return 0, fmt.Errorf("redis: can't parse array reply: %.100q", line)
+	}
+}
+
+func (r *Reader) ReadScanReply() ([]string, uint64, error) {
+	n, err := r.ReadArrayLen()
+	if err != nil {
+		return nil, 0, err
+	}
+	if n != 2 {
+		return nil, 0, fmt.Errorf("redis: got %d elements in scan reply, expected 2", n)
+	}
+
+	cursor, err := r.ReadUint()
+	if err != nil {
+		return nil, 0, err
+	}
+
+	n, err = r.ReadArrayLen()
+	if err != nil {
+		return nil, 0, err
+	}
+
+	keys := make([]string, n)
+	for i := int64(0); i < n; i++ {
+		key, err := r.ReadString()
+		if err != nil {
+			return nil, 0, err
+		}
+		keys[i] = key
+	}
+
+	return keys, cursor, err
+}
+
+func (r *Reader) ReadInt() (int64, error) {
+	b, err := r.readTmpBytesReply()
+	if err != nil {
+		return 0, err
+	}
+	return util.ParseInt(b, 10, 64)
+}
+
+func (r *Reader) ReadUint() (uint64, error) {
+	b, err := r.readTmpBytesReply()
+	if err != nil {
+		return 0, err
+	}
+	return util.ParseUint(b, 10, 64)
+}
+
+func (r *Reader) ReadFloatReply() (float64, error) {
+	b, err := r.readTmpBytesReply()
+	if err != nil {
+		return 0, err
+	}
+	return util.ParseFloat(b, 64)
+}
+
+func (r *Reader) readTmpBytesReply() ([]byte, error) {
+	line, err := r.ReadLine()
+	if err != nil {
+		return nil, err
+	}
+	switch line[0] {
+	case ErrorReply:
+		return nil, ParseErrorReply(line)
+	case StringReply:
+		return r._readTmpBytesReply(line)
+	case StatusReply:
+		return line[1:], nil
+	default:
+		return nil, fmt.Errorf("redis: can't parse string reply: %.100q", line)
+	}
+}
+
+func (r *Reader) _readTmpBytesReply(line []byte) ([]byte, error) {
+	if isNilReply(line) {
+		return nil, Nil
+	}
+
+	replyLen, err := strconv.Atoi(string(line[1:]))
+	if err != nil {
+		return nil, err
+	}
+
+	buf := r.buf(replyLen + 2)
+	_, err = io.ReadFull(r.rd, buf)
+	if err != nil {
+		return nil, err
+	}
+
+	return buf[:replyLen], nil
+}
+
+func (r *Reader) buf(n int) []byte {
+	if d := n - cap(r._buf); d > 0 {
+		r._buf = append(r._buf, make([]byte, d)...)
+	}
+	return r._buf[:n]
+}
+
+func isNilReply(b []byte) bool {
+	return len(b) == 3 &&
+		(b[0] == StringReply || b[0] == ArrayReply) &&
+		b[1] == '-' && b[2] == '1'
+}
+
+func ParseErrorReply(line []byte) error {
+	return RedisError(string(line[1:]))
+}
+
+func parseArrayLen(line []byte) (int64, error) {
+	if isNilReply(line) {
+		return 0, Nil
+	}
+	return util.ParseInt(line[1:], 10, 64)
+}

+ 56 - 0
go/gopath/src/github.com/go-redis/redis/internal/proto/reader_test.go

@@ -0,0 +1,56 @@
+package proto_test
+
+import (
+	"bytes"
+	"testing"
+
+	"github.com/go-redis/redis/internal/proto"
+)
+
+func BenchmarkReader_ParseReply_Status(b *testing.B) {
+	benchmarkParseReply(b, "+OK\r\n", nil, false)
+}
+
+func BenchmarkReader_ParseReply_Int(b *testing.B) {
+	benchmarkParseReply(b, ":1\r\n", nil, false)
+}
+
+func BenchmarkReader_ParseReply_Error(b *testing.B) {
+	benchmarkParseReply(b, "-Error message\r\n", nil, true)
+}
+
+func BenchmarkReader_ParseReply_String(b *testing.B) {
+	benchmarkParseReply(b, "$5\r\nhello\r\n", nil, false)
+}
+
+func BenchmarkReader_ParseReply_Slice(b *testing.B) {
+	benchmarkParseReply(b, "*2\r\n$5\r\nhello\r\n$5\r\nworld\r\n", multiBulkParse, false)
+}
+
+func benchmarkParseReply(b *testing.B, reply string, m proto.MultiBulkParse, wanterr bool) {
+	buf := new(bytes.Buffer)
+	for i := 0; i < b.N; i++ {
+		buf.WriteString(reply)
+	}
+	p := proto.NewReader(buf)
+	b.ResetTimer()
+
+	for i := 0; i < b.N; i++ {
+		_, err := p.ReadReply(m)
+		if !wanterr && err != nil {
+			b.Fatal(err)
+		}
+	}
+}
+
+func multiBulkParse(p *proto.Reader, n int64) (interface{}, error) {
+	vv := make([]interface{}, 0, n)
+	for i := int64(0); i < n; i++ {
+		v, err := p.ReadReply(multiBulkParse)
+		if err != nil {
+			return nil, err
+		}
+		vv = append(vv, v)
+	}
+	return vv, nil
+}

+ 166 - 0
go/gopath/src/github.com/go-redis/redis/internal/proto/scan.go

@@ -0,0 +1,166 @@
+package proto
+
+import (
+	"encoding"
+	"fmt"
+	"reflect"
+
+	"github.com/go-redis/redis/internal/util"
+)
+
+func Scan(b []byte, v interface{}) error {
+	switch v := v.(type) {
+	case nil:
+		return fmt.Errorf("redis: Scan(nil)")
+	case *string:
+		*v = util.BytesToString(b)
+		return nil
+	case *[]byte:
+		*v = b
+		return nil
+	case *int:
+		var err error
+		*v, err = util.Atoi(b)
+		return err
+	case *int8:
+		n, err := util.ParseInt(b, 10, 8)
+		if err != nil {
+			return err
+		}
+		*v = int8(n)
+		return nil
+	case *int16:
+		n, err := util.ParseInt(b, 10, 16)
+		if err != nil {
+			return err
+		}
+		*v = int16(n)
+		return nil
+	case *int32:
+		n, err := util.ParseInt(b, 10, 32)
+		if err != nil {
+			return err
+		}
+		*v = int32(n)
+		return nil
+	case *int64:
+		n, err := util.ParseInt(b, 10, 64)
+		if err != nil {
+			return err
+		}
+		*v = n
+		return nil
+	case *uint:
+		n, err := util.ParseUint(b, 10, 64)
+		if err != nil {
+			return err
+		}
+		*v = uint(n)
+		return nil
+	case *uint8:
+		n, err := util.ParseUint(b, 10, 8)
+		if err != nil {
+			return err
+		}
+		*v = uint8(n)
+		return nil
+	case *uint16:
+		n, err := util.ParseUint(b, 10, 16)
+		if err != nil {
+			return err
+		}
+		*v = uint16(n)
+		return nil
+	case *uint32:
+		n, err := util.ParseUint(b, 10, 32)
+		if err != nil {
+			return err
+		}
+		*v = uint32(n)
+		return nil
+	case *uint64:
+		n, err := util.ParseUint(b, 10, 64)
+		if err != nil {
+			return err
+		}
+		*v = n
+		return nil
+	case *float32:
+		n, err := util.ParseFloat(b, 32)
+		if err != nil {
+			return err
+		}
+		*v = float32(n)
+		return err
+	case *float64:
+		var err error
+		*v, err = util.ParseFloat(b, 64)
+		return err
+	case *bool:
+		*v = len(b) == 1 && b[0] == '1'
+		return nil
+	case encoding.BinaryUnmarshaler:
+		return v.UnmarshalBinary(b)
+	default:
+		return fmt.Errorf(
+			"redis: can't unmarshal %T (consider implementing BinaryUnmarshaler)", v)
+	}
+}
+
+func ScanSlice(data []string, slice interface{}) error {
+	v := reflect.ValueOf(slice)
+	if !v.IsValid() {
+		return fmt.Errorf("redis: ScanSlice(nil)")
+	}
+	if v.Kind() != reflect.Ptr {
+		return fmt.Errorf("redis: ScanSlice(non-pointer %T)", slice)
+	}
+	v = v.Elem()
+	if v.Kind() != reflect.Slice {
+		return fmt.Errorf("redis: ScanSlice(non-slice %T)", slice)
+	}
+
+	next := makeSliceNextElemFunc(v)
+	for i, s := range data {
+		elem := next()
+		if err := Scan([]byte(s), elem.Addr().Interface()); err != nil {
+			err = fmt.Errorf("redis: ScanSlice index=%d value=%q failed: %s", i, s, err)
+			return err
+		}
+	}
+
+	return nil
+}
+
+func makeSliceNextElemFunc(v reflect.Value) func() reflect.Value {
+	elemType := v.Type().Elem()
+
+	if elemType.Kind() == reflect.Ptr {
+		elemType = elemType.Elem()
+		return func() reflect.Value {
+			if v.Len() < v.Cap() {
+				v.Set(v.Slice(0, v.Len()+1))
+				elem := v.Index(v.Len() - 1)
+				if elem.IsNil() {
+					elem.Set(reflect.New(elemType))
+				}
+				return elem.Elem()
+			}
+
+			elem := reflect.New(elemType)
+			v.Set(reflect.Append(v, elem))
+			return elem.Elem()
+		}
+	}
+
+	zero := reflect.Zero(elemType)
+	return func() reflect.Value {
+		if v.Len() < v.Cap() {
+			v.Set(v.Slice(0, v.Len()+1))
+			return v.Index(v.Len() - 1)
+		}
+
+		v.Set(reflect.Append(v, zero))
+		return v.Index(v.Len() - 1)
+	}
+}

+ 48 - 0
go/gopath/src/github.com/go-redis/redis/internal/proto/scan_test.go

@@ -0,0 +1,48 @@
+package proto
+
+import (
+	"encoding/json"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+type testScanSliceStruct struct {
+	ID   int
+	Name string
+}
+
+func (s *testScanSliceStruct) MarshalBinary() ([]byte, error) {
+	return json.Marshal(s)
+}
+
+func (s *testScanSliceStruct) UnmarshalBinary(b []byte) error {
+	return json.Unmarshal(b, s)
+}
+
+var _ = Describe("ScanSlice", func() {
+	data := []string{
+		`{"ID":-1,"Name":"Back Yu"}`,
+		`{"ID":1,"Name":"szyhf"}`,
+	}
+
+	It("[]testScanSliceStruct", func() {
+		var slice []testScanSliceStruct
+		err := ScanSlice(data, &slice)
+		Expect(err).NotTo(HaveOccurred())
+		Expect(slice).To(Equal([]testScanSliceStruct{
+			{-1, "Back Yu"},
+			{1, "szyhf"},
+		}))
+	})
+
+	It("var testContainer []*testScanSliceStruct", func() {
+		var slice []*testScanSliceStruct
+		err := ScanSlice(data, &slice)
+		Expect(err).NotTo(HaveOccurred())
+		Expect(slice).To(Equal([]*testScanSliceStruct{
+			{-1, "Back Yu"},
+			{1, "szyhf"},
+		}))
+	})
+})

+ 93 - 0
go/gopath/src/github.com/go-redis/redis/internal/proto/write_buffer_test.go

@@ -0,0 +1,93 @@
+package proto_test
+
+import (
+	"bytes"
+	"encoding"
+	"io/ioutil"
+	"testing"
+	"time"
+
+	"github.com/go-redis/redis/internal/proto"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+type MyType struct{}
+
+var _ encoding.BinaryMarshaler = (*MyType)(nil)
+
+func (t *MyType) MarshalBinary() ([]byte, error) {
+	return []byte("hello"), nil
+}
+
+var _ = Describe("WriteBuffer", func() {
+	var buf *bytes.Buffer
+	var wr *proto.Writer
+
+	BeforeEach(func() {
+		buf = new(bytes.Buffer)
+		wr = proto.NewWriter(buf)
+	})
+
+	It("should write args", func() {
+		err := wr.WriteArgs([]interface{}{
+			"string",
+			12,
+			34.56,
+			[]byte{'b', 'y', 't', 'e', 's'},
+			true,
+			nil,
+		})
+		Expect(err).NotTo(HaveOccurred())
+
+		err = wr.Flush()
+		Expect(err).NotTo(HaveOccurred())
+
+		Expect(buf.Bytes()).To(Equal([]byte("*6\r\n" +
+			"$6\r\nstring\r\n" +
+			"$2\r\n12\r\n" +
+			"$5\r\n34.56\r\n" +
+			"$5\r\nbytes\r\n" +
+			"$1\r\n1\r\n" +
+			"$0\r\n" +
+			"\r\n")))
+	})
+
+	It("should append time", func() {
+		err := wr.WriteArgs([]interface{}{time.Unix(1414141414, 0).UTC()})
+		Expect(err).NotTo(HaveOccurred())
+
+		err = wr.Flush()
+		Expect(err).NotTo(HaveOccurred())
+
+		Expect(buf.Len()).To(Equal(31))
+	})
+
+	It("should append marshalable args", func() {
+		err := wr.WriteArgs([]interface{}{&MyType{}})
+		Expect(err).NotTo(HaveOccurred())
+
+		err = wr.Flush()
+		Expect(err).NotTo(HaveOccurred())
+
+		Expect(buf.Len()).To(Equal(15))
+	})
+})
+
+func BenchmarkWriteBuffer_Append(b *testing.B) {
+	buf := proto.NewWriter(ioutil.Discard)
+	args := []interface{}{"hello", "world", "foo", "bar"}
+
+	for i := 0; i < b.N; i++ {
+		err := buf.WriteArgs(args)
+		if err != nil {
+			panic(err)
+		}
+
+		err = buf.Flush()
+		if err != nil {
+			panic(err)
+		}
+	}
+}

+ 161 - 0
go/gopath/src/github.com/go-redis/redis/internal/proto/writer.go

@@ -0,0 +1,161 @@
+package proto
+
+import (
+	"bufio"
+	"encoding"
+	"fmt"
+	"io"
+	"strconv"
+	"time"
+
+	"github.com/go-redis/redis/internal/util"
+)
+
+type Writer struct {
+	wr *bufio.Writer
+
+	lenBuf []byte
+	numBuf []byte
+}
+
+func NewWriter(wr io.Writer) *Writer {
+	return &Writer{
+		wr: bufio.NewWriter(wr),
+
+		lenBuf: make([]byte, 64),
+		numBuf: make([]byte, 64),
+	}
+}
+
+func (w *Writer) WriteArgs(args []interface{}) error {
+	err := w.wr.WriteByte(ArrayReply)
+	if err != nil {
+		return err
+	}
+
+	err = w.writeLen(len(args))
+	if err != nil {
+		return err
+	}
+
+	for _, arg := range args {
+		err := w.writeArg(arg)
+		if err != nil {
+			return err
+		}
+	}
+
+	return nil
+}
+
+func (w *Writer) writeLen(n int) error {
+	w.lenBuf = strconv.AppendUint(w.lenBuf[:0], uint64(n), 10)
+	w.lenBuf = append(w.lenBuf, '\r', '\n')
+	_, err := w.wr.Write(w.lenBuf)
+	return err
+}
+
+func (w *Writer) writeArg(v interface{}) error {
+	switch v := v.(type) {
+	case nil:
+		return w.string("")
+	case string:
+		return w.string(v)
+	case []byte:
+		return w.bytes(v)
+	case int:
+		return w.int(int64(v))
+	case int8:
+		return w.int(int64(v))
+	case int16:
+		return w.int(int64(v))
+	case int32:
+		return w.int(int64(v))
+	case int64:
+		return w.int(v)
+	case uint:
+		return w.uint(uint64(v))
+	case uint8:
+		return w.uint(uint64(v))
+	case uint16:
+		return w.uint(uint64(v))
+	case uint32:
+		return w.uint(uint64(v))
+	case uint64:
+		return w.uint(v)
+	case float32:
+		return w.float(float64(v))
+	case float64:
+		return w.float(v)
+	case bool:
+		if v {
+			return w.int(1)
+		}
+		return w.int(0)
+	case time.Time:
+		return w.string(v.Format(time.RFC3339))
+	case encoding.BinaryMarshaler:
+		b, err := v.MarshalBinary()
+		if err != nil {
+			return err
+		}
+		return w.bytes(b)
+	default:
+		return fmt.Errorf(
+			"redis: can't marshal %T (implement encoding.BinaryMarshaler)", v)
+	}
+}
+
+func (w *Writer) bytes(b []byte) error {
+	err := w.wr.WriteByte(StringReply)
+	if err != nil {
+		return err
+	}
+
+	err = w.writeLen(len(b))
+	if err != nil {
+		return err
+	}
+
+	_, err = w.wr.Write(b)
+	if err != nil {
+		return err
+	}
+
+	return w.crlf()
+}
+
+func (w *Writer) string(s string) error {
+	return w.bytes(util.StringToBytes(s))
+}
+
+func (w *Writer) uint(n uint64) error {
+	w.numBuf = strconv.AppendUint(w.numBuf[:0], n, 10)
+	return w.bytes(w.numBuf)
+}
+
+func (w *Writer) int(n int64) error {
+	w.numBuf = strconv.AppendInt(w.numBuf[:0], n, 10)
+	return w.bytes(w.numBuf)
+}
+
+func (w *Writer) float(f float64) error {
+	w.numBuf = strconv.AppendFloat(w.numBuf[:0], f, 'f', -1, 64)
+	return w.bytes(w.numBuf)
+}
+
+func (w *Writer) crlf() error {
+	err := w.wr.WriteByte('\r')
+	if err != nil {
+		return err
+	}
+	return w.wr.WriteByte('\n')
+}
+
+func (w *Writer) Reset(wr io.Writer) {
+	w.wr.Reset(wr)
+}
+
+func (w *Writer) Flush() error {
+	return w.wr.Flush()
+}

+ 29 - 0
go/gopath/src/github.com/go-redis/redis/internal/util.go

@@ -0,0 +1,29 @@
+package internal
+
+import "github.com/go-redis/redis/internal/util"
+
+func ToLower(s string) string {
+	if isLower(s) {
+		return s
+	}
+
+	b := make([]byte, len(s))
+	for i := range b {
+		c := s[i]
+		if c >= 'A' && c <= 'Z' {
+			c += 'a' - 'A'
+		}
+		b[i] = c
+	}
+	return util.BytesToString(b)
+}
+
+func isLower(s string) bool {
+	for i := 0; i < len(s); i++ {
+		c := s[i]
+		if c >= 'A' && c <= 'Z' {
+			return false
+		}
+	}
+	return true
+}

+ 11 - 0
go/gopath/src/github.com/go-redis/redis/internal/util/safe.go

@@ -0,0 +1,11 @@
+// +build appengine
+
+package util
+
+func BytesToString(b []byte) string {
+	return string(b)
+}
+
+func StringToBytes(s string) []byte {
+	return []byte(s)
+}

+ 19 - 0
go/gopath/src/github.com/go-redis/redis/internal/util/strconv.go

@@ -0,0 +1,19 @@
+package util
+
+import "strconv"
+
+func Atoi(b []byte) (int, error) {
+	return strconv.Atoi(BytesToString(b))
+}
+
+func ParseInt(b []byte, base int, bitSize int) (int64, error) {
+	return strconv.ParseInt(BytesToString(b), base, bitSize)
+}
+
+func ParseUint(b []byte, base int, bitSize int) (uint64, error) {
+	return strconv.ParseUint(BytesToString(b), base, bitSize)
+}
+
+func ParseFloat(b []byte, bitSize int) (float64, error) {
+	return strconv.ParseFloat(BytesToString(b), bitSize)
+}

+ 22 - 0
go/gopath/src/github.com/go-redis/redis/internal/util/unsafe.go

@@ -0,0 +1,22 @@
+// +build !appengine
+
+package util
+
+import (
+	"unsafe"
+)
+
+// BytesToString converts byte slice to string.
+func BytesToString(b []byte) string {
+	return *(*string)(unsafe.Pointer(&b))
+}
+
+// StringToBytes converts string to byte slice.
+func StringToBytes(s string) []byte {
+	return *(*[]byte)(unsafe.Pointer(
+		&struct {
+			string
+			Cap int
+		}{s, len(s)},
+	))
+}

+ 65 - 0
go/gopath/src/github.com/go-redis/redis/internal_test.go

@@ -0,0 +1,65 @@
+package redis
+
+import (
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("newClusterState", func() {
+	var state *clusterState
+
+	createClusterState := func(slots []ClusterSlot) *clusterState {
+		nodes := newClusterNodes(&ClusterOptions{})
+		state, err := newClusterState(nodes, slots, "10.10.10.10:1234")
+		Expect(err).NotTo(HaveOccurred())
+		return state
+	}
+
+	Describe("sorting", func() {
+		BeforeEach(func() {
+			state = createClusterState([]ClusterSlot{{
+				Start: 1000,
+				End:   1999,
+			}, {
+				Start: 0,
+				End:   999,
+			}, {
+				Start: 2000,
+				End:   2999,
+			}})
+		})
+
+		It("sorts slots", func() {
+			Expect(state.slots).To(Equal([]*clusterSlot{
+				{start: 0, end: 999, nodes: nil},
+				{start: 1000, end: 1999, nodes: nil},
+				{start: 2000, end: 2999, nodes: nil},
+			}))
+		})
+	})
+
+	Describe("loopback", func() {
+		BeforeEach(func() {
+			state = createClusterState([]ClusterSlot{{
+				Nodes: []ClusterNode{{Addr: "127.0.0.1:7001"}},
+			}, {
+				Nodes: []ClusterNode{{Addr: "127.0.0.1:7002"}},
+			}, {
+				Nodes: []ClusterNode{{Addr: "1.2.3.4:1234"}},
+			}, {
+				Nodes: []ClusterNode{{Addr: ":1234"}},
+			}})
+		})
+
+		It("replaces loopback hosts in addresses", func() {
+			slotAddr := func(slot *clusterSlot) string {
+				return slot.nodes[0].Client.Options().Addr
+			}
+
+			Expect(slotAddr(state.slots[0])).To(Equal("10.10.10.10:7001"))
+			Expect(slotAddr(state.slots[1])).To(Equal("10.10.10.10:7002"))
+			Expect(slotAddr(state.slots[2])).To(Equal("1.2.3.4:1234"))
+			Expect(slotAddr(state.slots[3])).To(Equal(":1234"))
+		})
+	})
+})

+ 75 - 0
go/gopath/src/github.com/go-redis/redis/iterator.go

@@ -0,0 +1,75 @@
+package redis
+
+import (
+	"sync"
+)
+
+// ScanIterator is used to incrementally iterate over a collection of elements.
+// It's safe for concurrent use by multiple goroutines.
+type ScanIterator struct {
+	mu  sync.Mutex // protects Scanner and pos
+	cmd *ScanCmd
+	pos int
+}
+
+// Err returns the last iterator error, if any.
+func (it *ScanIterator) Err() error {
+	it.mu.Lock()
+	err := it.cmd.Err()
+	it.mu.Unlock()
+	return err
+}
+
+// Next advances the cursor and returns true if more values can be read.
+func (it *ScanIterator) Next() bool {
+	it.mu.Lock()
+	defer it.mu.Unlock()
+
+	// Instantly return on errors.
+	if it.cmd.Err() != nil {
+		return false
+	}
+
+	// Advance cursor, check if we are still within range.
+	if it.pos < len(it.cmd.page) {
+		it.pos++
+		return true
+	}
+
+	for {
+		// Return if there is no more data to fetch.
+		if it.cmd.cursor == 0 {
+			return false
+		}
+
+		// Fetch next page.
+		if it.cmd._args[0] == "scan" {
+			it.cmd._args[1] = it.cmd.cursor
+		} else {
+			it.cmd._args[2] = it.cmd.cursor
+		}
+
+		err := it.cmd.process(it.cmd)
+		if err != nil {
+			return false
+		}
+
+		it.pos = 1
+
+		// Redis can occasionally return empty page.
+		if len(it.cmd.page) > 0 {
+			return true
+		}
+	}
+}
+
+// Val returns the key/field at the current cursor position.
+func (it *ScanIterator) Val() string {
+	var v string
+	it.mu.Lock()
+	if it.cmd.Err() == nil && it.pos > 0 && it.pos <= len(it.cmd.page) {
+		v = it.cmd.page[it.pos-1]
+	}
+	it.mu.Unlock()
+	return v
+}

+ 136 - 0
go/gopath/src/github.com/go-redis/redis/iterator_test.go

@@ -0,0 +1,136 @@
+package redis_test
+
+import (
+	"fmt"
+
+	"github.com/go-redis/redis"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("ScanIterator", func() {
+	var client *redis.Client
+
+	var seed = func(n int) error {
+		pipe := client.Pipeline()
+		for i := 1; i <= n; i++ {
+			pipe.Set(fmt.Sprintf("K%02d", i), "x", 0).Err()
+		}
+		_, err := pipe.Exec()
+		return err
+	}
+
+	var extraSeed = func(n int, m int) error {
+		pipe := client.Pipeline()
+		for i := 1; i <= m; i++ {
+			pipe.Set(fmt.Sprintf("A%02d", i), "x", 0).Err()
+		}
+		for i := 1; i <= n; i++ {
+			pipe.Set(fmt.Sprintf("K%02d", i), "x", 0).Err()
+		}
+		_, err := pipe.Exec()
+		return err
+	}
+
+	var hashKey = "K_HASHTEST"
+	var hashSeed = func(n int) error {
+		pipe := client.Pipeline()
+		for i := 1; i <= n; i++ {
+			pipe.HSet(hashKey, fmt.Sprintf("K%02d", i), "x").Err()
+		}
+		_, err := pipe.Exec()
+		return err
+	}
+
+	BeforeEach(func() {
+		client = redis.NewClient(redisOptions())
+		Expect(client.FlushDB().Err()).NotTo(HaveOccurred())
+	})
+
+	AfterEach(func() {
+		Expect(client.Close()).NotTo(HaveOccurred())
+	})
+
+	It("should scan across empty DBs", func() {
+		iter := client.Scan(0, "", 10).Iterator()
+		Expect(iter.Next()).To(BeFalse())
+		Expect(iter.Err()).NotTo(HaveOccurred())
+	})
+
+	It("should scan across one page", func() {
+		Expect(seed(7)).NotTo(HaveOccurred())
+
+		var vals []string
+		iter := client.Scan(0, "", 0).Iterator()
+		for iter.Next() {
+			vals = append(vals, iter.Val())
+		}
+		Expect(iter.Err()).NotTo(HaveOccurred())
+		Expect(vals).To(ConsistOf([]string{"K01", "K02", "K03", "K04", "K05", "K06", "K07"}))
+	})
+
+	It("should scan across multiple pages", func() {
+		Expect(seed(71)).NotTo(HaveOccurred())
+
+		var vals []string
+		iter := client.Scan(0, "", 10).Iterator()
+		for iter.Next() {
+			vals = append(vals, iter.Val())
+		}
+		Expect(iter.Err()).NotTo(HaveOccurred())
+		Expect(vals).To(HaveLen(71))
+		Expect(vals).To(ContainElement("K01"))
+		Expect(vals).To(ContainElement("K71"))
+	})
+
+	It("should hscan across multiple pages", func() {
+		Expect(hashSeed(71)).NotTo(HaveOccurred())
+
+		var vals []string
+		iter := client.HScan(hashKey, 0, "", 10).Iterator()
+		for iter.Next() {
+			vals = append(vals, iter.Val())
+		}
+		Expect(iter.Err()).NotTo(HaveOccurred())
+		Expect(vals).To(HaveLen(71 * 2))
+		Expect(vals).To(ContainElement("K01"))
+		Expect(vals).To(ContainElement("K71"))
+	})
+
+	It("should scan to page borders", func() {
+		Expect(seed(20)).NotTo(HaveOccurred())
+
+		var vals []string
+		iter := client.Scan(0, "", 10).Iterator()
+		for iter.Next() {
+			vals = append(vals, iter.Val())
+		}
+		Expect(iter.Err()).NotTo(HaveOccurred())
+		Expect(vals).To(HaveLen(20))
+	})
+
+	It("should scan with match", func() {
+		Expect(seed(33)).NotTo(HaveOccurred())
+
+		var vals []string
+		iter := client.Scan(0, "K*2*", 10).Iterator()
+		for iter.Next() {
+			vals = append(vals, iter.Val())
+		}
+		Expect(iter.Err()).NotTo(HaveOccurred())
+		Expect(vals).To(HaveLen(13))
+	})
+
+	It("should scan with match across empty pages", func() {
+		Expect(extraSeed(2, 10)).NotTo(HaveOccurred())
+
+		var vals []string
+		iter := client.Scan(0, "K*", 1).Iterator()
+		for iter.Next() {
+			vals = append(vals, iter.Val())
+		}
+		Expect(iter.Err()).NotTo(HaveOccurred())
+		Expect(vals).To(HaveLen(2))
+	})
+})

+ 364 - 0
go/gopath/src/github.com/go-redis/redis/main_test.go

@@ -0,0 +1,364 @@
+package redis_test
+
+import (
+	"errors"
+	"fmt"
+	"net"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"sync"
+	"testing"
+	"time"
+
+	"github.com/go-redis/redis"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+const (
+	redisPort          = "6380"
+	redisAddr          = ":" + redisPort
+	redisSecondaryPort = "6381"
+)
+
+const (
+	ringShard1Port = "6390"
+	ringShard2Port = "6391"
+	ringShard3Port = "6392"
+)
+
+const (
+	sentinelName       = "mymaster"
+	sentinelMasterPort = "8123"
+	sentinelSlave1Port = "8124"
+	sentinelSlave2Port = "8125"
+	sentinelPort       = "8126"
+)
+
+var (
+	redisMain                                                *redisProcess
+	ringShard1, ringShard2, ringShard3                       *redisProcess
+	sentinelMaster, sentinelSlave1, sentinelSlave2, sentinel *redisProcess
+)
+
+var cluster = &clusterScenario{
+	ports:     []string{"8220", "8221", "8222", "8223", "8224", "8225"},
+	nodeIDs:   make([]string, 6),
+	processes: make(map[string]*redisProcess, 6),
+	clients:   make(map[string]*redis.Client, 6),
+}
+
+var _ = BeforeSuite(func() {
+	var err error
+
+	redisMain, err = startRedis(redisPort)
+	Expect(err).NotTo(HaveOccurred())
+
+	ringShard1, err = startRedis(ringShard1Port)
+	Expect(err).NotTo(HaveOccurred())
+
+	ringShard2, err = startRedis(ringShard2Port)
+	Expect(err).NotTo(HaveOccurred())
+
+	ringShard3, err = startRedis(ringShard3Port)
+	Expect(err).NotTo(HaveOccurred())
+
+	sentinelMaster, err = startRedis(sentinelMasterPort)
+	Expect(err).NotTo(HaveOccurred())
+
+	sentinel, err = startSentinel(sentinelPort, sentinelName, sentinelMasterPort)
+	Expect(err).NotTo(HaveOccurred())
+
+	sentinelSlave1, err = startRedis(
+		sentinelSlave1Port, "--slaveof", "127.0.0.1", sentinelMasterPort)
+	Expect(err).NotTo(HaveOccurred())
+
+	sentinelSlave2, err = startRedis(
+		sentinelSlave2Port, "--slaveof", "127.0.0.1", sentinelMasterPort)
+	Expect(err).NotTo(HaveOccurred())
+
+	Expect(startCluster(cluster)).NotTo(HaveOccurred())
+})
+
+var _ = AfterSuite(func() {
+	Expect(redisMain.Close()).NotTo(HaveOccurred())
+
+	Expect(ringShard1.Close()).NotTo(HaveOccurred())
+	Expect(ringShard2.Close()).NotTo(HaveOccurred())
+	Expect(ringShard3.Close()).NotTo(HaveOccurred())
+
+	Expect(sentinel.Close()).NotTo(HaveOccurred())
+	Expect(sentinelSlave1.Close()).NotTo(HaveOccurred())
+	Expect(sentinelSlave2.Close()).NotTo(HaveOccurred())
+	Expect(sentinelMaster.Close()).NotTo(HaveOccurred())
+
+	Expect(stopCluster(cluster)).NotTo(HaveOccurred())
+})
+
+func TestGinkgoSuite(t *testing.T) {
+	RegisterFailHandler(Fail)
+	RunSpecs(t, "go-redis")
+}
+
+//------------------------------------------------------------------------------
+
+func redisOptions() *redis.Options {
+	return &redis.Options{
+		Addr:               redisAddr,
+		DB:                 15,
+		DialTimeout:        10 * time.Second,
+		ReadTimeout:        30 * time.Second,
+		WriteTimeout:       30 * time.Second,
+		PoolSize:           10,
+		PoolTimeout:        30 * time.Second,
+		IdleTimeout:        time.Minute,
+		IdleCheckFrequency: 100 * time.Millisecond,
+	}
+}
+
+func redisClusterOptions() *redis.ClusterOptions {
+	return &redis.ClusterOptions{
+		DialTimeout:        10 * time.Second,
+		ReadTimeout:        30 * time.Second,
+		WriteTimeout:       30 * time.Second,
+		PoolSize:           10,
+		PoolTimeout:        30 * time.Second,
+		IdleTimeout:        time.Minute,
+		IdleCheckFrequency: 100 * time.Millisecond,
+	}
+}
+
+func redisRingOptions() *redis.RingOptions {
+	return &redis.RingOptions{
+		Addrs: map[string]string{
+			"ringShardOne": ":" + ringShard1Port,
+			"ringShardTwo": ":" + ringShard2Port,
+		},
+		DialTimeout:        10 * time.Second,
+		ReadTimeout:        30 * time.Second,
+		WriteTimeout:       30 * time.Second,
+		PoolSize:           10,
+		PoolTimeout:        30 * time.Second,
+		IdleTimeout:        time.Minute,
+		IdleCheckFrequency: 100 * time.Millisecond,
+	}
+}
+
+func performAsync(n int, cbs ...func(int)) *sync.WaitGroup {
+	var wg sync.WaitGroup
+	for _, cb := range cbs {
+		for i := 0; i < n; i++ {
+			wg.Add(1)
+			go func(cb func(int), i int) {
+				defer GinkgoRecover()
+				defer wg.Done()
+
+				cb(i)
+			}(cb, i)
+		}
+	}
+	return &wg
+}
+
+func perform(n int, cbs ...func(int)) {
+	wg := performAsync(n, cbs...)
+	wg.Wait()
+}
+
+func eventually(fn func() error, timeout time.Duration) error {
+	errCh := make(chan error, 1)
+	done := make(chan struct{})
+	exit := make(chan struct{})
+
+	go func() {
+		for {
+			err := fn()
+			if err == nil {
+				close(done)
+				return
+			}
+
+			select {
+			case errCh <- err:
+			default:
+			}
+
+			select {
+			case <-exit:
+				return
+			case <-time.After(timeout / 100):
+			}
+		}
+	}()
+
+	select {
+	case <-done:
+		return nil
+	case <-time.After(timeout):
+		close(exit)
+		select {
+		case err := <-errCh:
+			return err
+		default:
+			return fmt.Errorf("timeout after %s without an error", timeout)
+		}
+	}
+}
+
+func execCmd(name string, args ...string) (*os.Process, error) {
+	cmd := exec.Command(name, args...)
+	if testing.Verbose() {
+		cmd.Stdout = os.Stdout
+		cmd.Stderr = os.Stderr
+	}
+	return cmd.Process, cmd.Start()
+}
+
+func connectTo(port string) (*redis.Client, error) {
+	client := redis.NewClient(&redis.Options{
+		Addr: ":" + port,
+	})
+
+	err := eventually(func() error {
+		return client.Ping().Err()
+	}, 30*time.Second)
+	if err != nil {
+		return nil, err
+	}
+
+	return client, nil
+}
+
+type redisProcess struct {
+	*os.Process
+	*redis.Client
+}
+
+func (p *redisProcess) Close() error {
+	if err := p.Kill(); err != nil {
+		return err
+	}
+
+	err := eventually(func() error {
+		if err := p.Client.Ping().Err(); err != nil {
+			return nil
+		}
+		return errors.New("client is not shutdown")
+	}, 10*time.Second)
+	if err != nil {
+		return err
+	}
+
+	p.Client.Close()
+	return nil
+}
+
+var (
+	redisServerBin, _  = filepath.Abs(filepath.Join("testdata", "redis", "src", "redis-server"))
+	redisServerConf, _ = filepath.Abs(filepath.Join("testdata", "redis.conf"))
+)
+
+func redisDir(port string) (string, error) {
+	dir, err := filepath.Abs(filepath.Join("testdata", "instances", port))
+	if err != nil {
+		return "", err
+	}
+	if err := os.RemoveAll(dir); err != nil {
+		return "", err
+	}
+	if err := os.MkdirAll(dir, 0775); err != nil {
+		return "", err
+	}
+	return dir, nil
+}
+
+func startRedis(port string, args ...string) (*redisProcess, error) {
+	dir, err := redisDir(port)
+	if err != nil {
+		return nil, err
+	}
+	if err = exec.Command("cp", "-f", redisServerConf, dir).Run(); err != nil {
+		return nil, err
+	}
+
+	baseArgs := []string{filepath.Join(dir, "redis.conf"), "--port", port, "--dir", dir}
+	process, err := execCmd(redisServerBin, append(baseArgs, args...)...)
+	if err != nil {
+		return nil, err
+	}
+
+	client, err := connectTo(port)
+	if err != nil {
+		process.Kill()
+		return nil, err
+	}
+	return &redisProcess{process, client}, err
+}
+
+func startSentinel(port, masterName, masterPort string) (*redisProcess, error) {
+	dir, err := redisDir(port)
+	if err != nil {
+		return nil, err
+	}
+	process, err := execCmd(redisServerBin, os.DevNull, "--sentinel", "--port", port, "--dir", dir)
+	if err != nil {
+		return nil, err
+	}
+	client, err := connectTo(port)
+	if err != nil {
+		process.Kill()
+		return nil, err
+	}
+	for _, cmd := range []*redis.StatusCmd{
+		redis.NewStatusCmd("SENTINEL", "MONITOR", masterName, "127.0.0.1", masterPort, "1"),
+		redis.NewStatusCmd("SENTINEL", "SET", masterName, "down-after-milliseconds", "500"),
+		redis.NewStatusCmd("SENTINEL", "SET", masterName, "failover-timeout", "1000"),
+		redis.NewStatusCmd("SENTINEL", "SET", masterName, "parallel-syncs", "1"),
+	} {
+		client.Process(cmd)
+		if err := cmd.Err(); err != nil {
+			process.Kill()
+			return nil, err
+		}
+	}
+	return &redisProcess{process, client}, nil
+}
+
+//------------------------------------------------------------------------------
+
+type badConnError string
+
+func (e badConnError) Error() string   { return string(e) }
+func (e badConnError) Timeout() bool   { return false }
+func (e badConnError) Temporary() bool { return false }
+
+type badConn struct {
+	net.TCPConn
+
+	readDelay, writeDelay time.Duration
+	readErr, writeErr     error
+}
+
+var _ net.Conn = &badConn{}
+
+func (cn *badConn) Read([]byte) (int, error) {
+	if cn.readDelay != 0 {
+		time.Sleep(cn.readDelay)
+	}
+	if cn.readErr != nil {
+		return 0, cn.readErr
+	}
+	return 0, badConnError("bad connection")
+}
+
+func (cn *badConn) Write([]byte) (int, error) {
+	if cn.writeDelay != 0 {
+		time.Sleep(cn.writeDelay)
+	}
+	if cn.writeErr != nil {
+		return 0, cn.writeErr
+	}
+	return 0, badConnError("bad connection")
+}

+ 228 - 0
go/gopath/src/github.com/go-redis/redis/options.go

@@ -0,0 +1,228 @@
+package redis
+
+import (
+	"context"
+	"crypto/tls"
+	"errors"
+	"fmt"
+	"net"
+	"net/url"
+	"runtime"
+	"strconv"
+	"strings"
+	"time"
+
+	"github.com/go-redis/redis/internal/pool"
+)
+
+// Limiter is the interface of a rate limiter or a circuit breaker.
+type Limiter interface {
+	// Allow returns nil if operation is allowed or an error otherwise.
+	// If operation is allowed client must ReportResult of the operation
+	// whether it is a success or a failure.
+	Allow() error
+	// ReportResult reports the result of previously allowed operation.
+	// nil indicates a success, non-nil error indicates a failure.
+	ReportResult(result error)
+}
+
+type Options struct {
+	// The network type, either tcp or unix.
+	// Default is tcp.
+	Network string
+	// host:port address.
+	Addr string
+
+	// Dialer creates new network connection and has priority over
+	// Network and Addr options.
+	Dialer func(ctx context.Context, network, addr string) (net.Conn, error)
+
+	// Hook that is called when new connection is established.
+	OnConnect func(*Conn) error
+
+	// Optional password. Must match the password specified in the
+	// requirepass server configuration option.
+	Password string
+	// Database to be selected after connecting to the server.
+	DB int
+
+	// Maximum number of retries before giving up.
+	// Default is to not retry failed commands.
+	MaxRetries int
+	// Minimum backoff between each retry.
+	// Default is 8 milliseconds; -1 disables backoff.
+	MinRetryBackoff time.Duration
+	// Maximum backoff between each retry.
+	// Default is 512 milliseconds; -1 disables backoff.
+	MaxRetryBackoff time.Duration
+
+	// Dial timeout for establishing new connections.
+	// Default is 5 seconds.
+	DialTimeout time.Duration
+	// Timeout for socket reads. If reached, commands will fail
+	// with a timeout instead of blocking. Use value -1 for no timeout and 0 for default.
+	// Default is 3 seconds.
+	ReadTimeout time.Duration
+	// Timeout for socket writes. If reached, commands will fail
+	// with a timeout instead of blocking.
+	// Default is ReadTimeout.
+	WriteTimeout time.Duration
+
+	// Maximum number of socket connections.
+	// Default is 10 connections per every CPU as reported by runtime.NumCPU.
+	PoolSize int
+	// Minimum number of idle connections which is useful when establishing
+	// new connection is slow.
+	MinIdleConns int
+	// Connection age at which client retires (closes) the connection.
+	// Default is to not close aged connections.
+	MaxConnAge time.Duration
+	// Amount of time client waits for connection if all connections
+	// are busy before returning an error.
+	// Default is ReadTimeout + 1 second.
+	PoolTimeout time.Duration
+	// Amount of time after which client closes idle connections.
+	// Should be less than server's timeout.
+	// Default is 5 minutes. -1 disables idle timeout check.
+	IdleTimeout time.Duration
+	// Frequency of idle checks made by idle connections reaper.
+	// Default is 1 minute. -1 disables idle connections reaper,
+	// but idle connections are still discarded by the client
+	// if IdleTimeout is set.
+	IdleCheckFrequency time.Duration
+
+	// Enables read only queries on slave nodes.
+	readOnly bool
+
+	// TLS Config to use. When set TLS will be negotiated.
+	TLSConfig *tls.Config
+}
+
+func (opt *Options) init() {
+	if opt.Network == "" {
+		opt.Network = "tcp"
+	}
+	if opt.Addr == "" {
+		opt.Addr = "localhost:6379"
+	}
+	if opt.Dialer == nil {
+		opt.Dialer = func(ctx context.Context, network, addr string) (net.Conn, error) {
+			netDialer := &net.Dialer{
+				Timeout:   opt.DialTimeout,
+				KeepAlive: 5 * time.Minute,
+			}
+			if opt.TLSConfig == nil {
+				return netDialer.Dial(network, addr)
+			}
+			return tls.DialWithDialer(netDialer, opt.Network, opt.Addr, opt.TLSConfig)
+		}
+	}
+	if opt.PoolSize == 0 {
+		opt.PoolSize = 10 * runtime.NumCPU()
+	}
+	if opt.DialTimeout == 0 {
+		opt.DialTimeout = 5 * time.Second
+	}
+	switch opt.ReadTimeout {
+	case -1:
+		opt.ReadTimeout = 0
+	case 0:
+		opt.ReadTimeout = 3 * time.Second
+	}
+	switch opt.WriteTimeout {
+	case -1:
+		opt.WriteTimeout = 0
+	case 0:
+		opt.WriteTimeout = opt.ReadTimeout
+	}
+	if opt.PoolTimeout == 0 {
+		opt.PoolTimeout = opt.ReadTimeout + time.Second
+	}
+	if opt.IdleTimeout == 0 {
+		opt.IdleTimeout = 5 * time.Minute
+	}
+	if opt.IdleCheckFrequency == 0 {
+		opt.IdleCheckFrequency = time.Minute
+	}
+
+	switch opt.MinRetryBackoff {
+	case -1:
+		opt.MinRetryBackoff = 0
+	case 0:
+		opt.MinRetryBackoff = 8 * time.Millisecond
+	}
+	switch opt.MaxRetryBackoff {
+	case -1:
+		opt.MaxRetryBackoff = 0
+	case 0:
+		opt.MaxRetryBackoff = 512 * time.Millisecond
+	}
+}
+
+// ParseURL parses an URL into Options that can be used to connect to Redis.
+func ParseURL(redisURL string) (*Options, error) {
+	o := &Options{Network: "tcp"}
+	u, err := url.Parse(redisURL)
+	if err != nil {
+		return nil, err
+	}
+
+	if u.Scheme != "redis" && u.Scheme != "rediss" {
+		return nil, errors.New("invalid redis URL scheme: " + u.Scheme)
+	}
+
+	if u.User != nil {
+		if p, ok := u.User.Password(); ok {
+			o.Password = p
+		}
+	}
+
+	if len(u.Query()) > 0 {
+		return nil, errors.New("no options supported")
+	}
+
+	h, p, err := net.SplitHostPort(u.Host)
+	if err != nil {
+		h = u.Host
+	}
+	if h == "" {
+		h = "localhost"
+	}
+	if p == "" {
+		p = "6379"
+	}
+	o.Addr = net.JoinHostPort(h, p)
+
+	f := strings.FieldsFunc(u.Path, func(r rune) bool {
+		return r == '/'
+	})
+	switch len(f) {
+	case 0:
+		o.DB = 0
+	case 1:
+		if o.DB, err = strconv.Atoi(f[0]); err != nil {
+			return nil, fmt.Errorf("invalid redis database number: %q", f[0])
+		}
+	default:
+		return nil, errors.New("invalid redis URL path: " + u.Path)
+	}
+
+	if u.Scheme == "rediss" {
+		o.TLSConfig = &tls.Config{ServerName: h}
+	}
+	return o, nil
+}
+
+func newConnPool(opt *Options) *pool.ConnPool {
+	return pool.NewConnPool(&pool.Options{
+		Dialer: func(c context.Context) (net.Conn, error) {
+			return opt.Dialer(c, opt.Network, opt.Addr)
+		},
+		PoolSize:           opt.PoolSize,
+		MinIdleConns:       opt.MinIdleConns,
+		MaxConnAge:         opt.MaxConnAge,
+		PoolTimeout:        opt.PoolTimeout,
+		IdleTimeout:        opt.IdleTimeout,
+		IdleCheckFrequency: opt.IdleCheckFrequency,
+	})
+}

+ 119 - 0
go/gopath/src/github.com/go-redis/redis/options_test.go

@@ -0,0 +1,119 @@
+// +build go1.7
+
+package redis
+
+import (
+	"errors"
+	"testing"
+	"time"
+)
+
+func TestParseURL(t *testing.T) {
+	cases := []struct {
+		u    string
+		addr string
+		db   int
+		tls  bool
+		err  error
+	}{
+		{
+			"redis://localhost:123/1",
+			"localhost:123",
+			1, false, nil,
+		},
+		{
+			"redis://localhost:123",
+			"localhost:123",
+			0, false, nil,
+		},
+		{
+			"redis://localhost/1",
+			"localhost:6379",
+			1, false, nil,
+		},
+		{
+			"redis://12345",
+			"12345:6379",
+			0, false, nil,
+		},
+		{
+			"rediss://localhost:123",
+			"localhost:123",
+			0, true, nil,
+		},
+		{
+			"redis://localhost/?abc=123",
+			"",
+			0, false, errors.New("no options supported"),
+		},
+		{
+			"http://google.com",
+			"",
+			0, false, errors.New("invalid redis URL scheme: http"),
+		},
+		{
+			"redis://localhost/1/2/3/4",
+			"",
+			0, false, errors.New("invalid redis URL path: /1/2/3/4"),
+		},
+		{
+			"12345",
+			"",
+			0, false, errors.New("invalid redis URL scheme: "),
+		},
+		{
+			"redis://localhost/iamadatabase",
+			"",
+			0, false, errors.New(`invalid redis database number: "iamadatabase"`),
+		},
+	}
+
+	for _, c := range cases {
+		t.Run(c.u, func(t *testing.T) {
+			o, err := ParseURL(c.u)
+			if c.err == nil && err != nil {
+				t.Fatalf("unexpected error: %q", err)
+				return
+			}
+			if c.err != nil && err != nil {
+				if c.err.Error() != err.Error() {
+					t.Fatalf("got %q, expected %q", err, c.err)
+				}
+				return
+			}
+			if o.Addr != c.addr {
+				t.Errorf("got %q, want %q", o.Addr, c.addr)
+			}
+			if o.DB != c.db {
+				t.Errorf("got %q, expected %q", o.DB, c.db)
+			}
+			if c.tls && o.TLSConfig == nil {
+				t.Errorf("got nil TLSConfig, expected a TLSConfig")
+			}
+		})
+	}
+}
+
+// Test ReadTimeout option initialization, including special values -1 and 0.
+// And also test behaviour of WriteTimeout option, when it is not explicitly set and use
+// ReadTimeout value.
+func TestReadTimeoutOptions(t *testing.T) {
+	testDataInputOutputMap := map[time.Duration]time.Duration{
+		-1: 0 * time.Second,
+		0:  3 * time.Second,
+		1:  1 * time.Nanosecond,
+		3:  3 * time.Nanosecond,
+	}
+
+	for in, out := range testDataInputOutputMap {
+		o := &Options{ReadTimeout: in}
+		o.init()
+		if o.ReadTimeout != out {
+			t.Errorf("got %d instead of %d as ReadTimeout option", o.ReadTimeout, out)
+		}
+
+		if o.WriteTimeout != o.ReadTimeout {
+			t.Errorf("got %d instead of %d as WriteTimeout option", o.WriteTimeout, o.ReadTimeout)
+		}
+	}
+}

+ 142 - 0
go/gopath/src/github.com/go-redis/redis/pipeline.go

@@ -0,0 +1,142 @@
+package redis
+
+import (
+	"context"
+	"sync"
+
+	"github.com/go-redis/redis/internal/pool"
+)
+
+type pipelineExecer func(context.Context, []Cmder) error
+
+// Pipeliner is an mechanism to realise Redis Pipeline technique.
+//
+// Pipelining is a technique to extremely speed up processing by packing
+// operations to batches, send them at once to Redis and read a replies in a
+// singe step.
+// See https://redis.io/topics/pipelining
+//
+// Pay attention, that Pipeline is not a transaction, so you can get unexpected
+// results in case of big pipelines and small read/write timeouts.
+// Redis client has retransmission logic in case of timeouts, pipeline
+// can be retransmitted and commands can be executed more then once.
+// To avoid this: it is good idea to use reasonable bigger read/write timeouts
+// depends of your batch size and/or use TxPipeline.
+type Pipeliner interface {
+	StatefulCmdable
+	Do(args ...interface{}) *Cmd
+	Process(cmd Cmder) error
+	Close() error
+	Discard() error
+	Exec() ([]Cmder, error)
+	ExecContext(ctx context.Context) ([]Cmder, error)
+}
+
+var _ Pipeliner = (*Pipeline)(nil)
+
+// Pipeline implements pipelining as described in
+// http://redis.io/topics/pipelining. It's safe for concurrent use
+// by multiple goroutines.
+type Pipeline struct {
+	cmdable
+	statefulCmdable
+
+	ctx  context.Context
+	exec pipelineExecer
+
+	mu     sync.Mutex
+	cmds   []Cmder
+	closed bool
+}
+
+func (c *Pipeline) init() {
+	c.cmdable = c.Process
+	c.statefulCmdable = c.Process
+}
+
+func (c *Pipeline) Do(args ...interface{}) *Cmd {
+	cmd := NewCmd(args...)
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// Process queues the cmd for later execution.
+func (c *Pipeline) Process(cmd Cmder) error {
+	c.mu.Lock()
+	c.cmds = append(c.cmds, cmd)
+	c.mu.Unlock()
+	return nil
+}
+
+// Close closes the pipeline, releasing any open resources.
+func (c *Pipeline) Close() error {
+	c.mu.Lock()
+	_ = c.discard()
+	c.closed = true
+	c.mu.Unlock()
+	return nil
+}
+
+// Discard resets the pipeline and discards queued commands.
+func (c *Pipeline) Discard() error {
+	c.mu.Lock()
+	err := c.discard()
+	c.mu.Unlock()
+	return err
+}
+
+func (c *Pipeline) discard() error {
+	if c.closed {
+		return pool.ErrClosed
+	}
+	c.cmds = c.cmds[:0]
+	return nil
+}
+
+// Exec executes all previously queued commands using one
+// client-server roundtrip.
+//
+// Exec always returns list of commands and error of the first failed
+// command if any.
+func (c *Pipeline) Exec() ([]Cmder, error) {
+	return c.ExecContext(c.ctx)
+}
+
+func (c *Pipeline) ExecContext(ctx context.Context) ([]Cmder, error) {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	if c.closed {
+		return nil, pool.ErrClosed
+	}
+
+	if len(c.cmds) == 0 {
+		return nil, nil
+	}
+
+	cmds := c.cmds
+	c.cmds = nil
+
+	return cmds, c.exec(ctx, cmds)
+}
+
+func (c *Pipeline) Pipelined(fn func(Pipeliner) error) ([]Cmder, error) {
+	if err := fn(c); err != nil {
+		return nil, err
+	}
+	cmds, err := c.Exec()
+	_ = c.Close()
+	return cmds, err
+}
+
+func (c *Pipeline) Pipeline() Pipeliner {
+	return c
+}
+
+func (c *Pipeline) TxPipelined(fn func(Pipeliner) error) ([]Cmder, error) {
+	return c.Pipelined(fn)
+}
+
+func (c *Pipeline) TxPipeline() Pipeliner {
+	return c
+}

+ 87 - 0
go/gopath/src/github.com/go-redis/redis/pipeline_test.go

@@ -0,0 +1,87 @@
+package redis_test
+
+import (
+	"github.com/go-redis/redis"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("pipelining", func() {
+	var client *redis.Client
+	var pipe *redis.Pipeline
+
+	BeforeEach(func() {
+		client = redis.NewClient(redisOptions())
+		Expect(client.FlushDB().Err()).NotTo(HaveOccurred())
+	})
+
+	AfterEach(func() {
+		Expect(client.Close()).NotTo(HaveOccurred())
+	})
+
+	It("supports block style", func() {
+		var get *redis.StringCmd
+		cmds, err := client.Pipelined(func(pipe redis.Pipeliner) error {
+			get = pipe.Get("foo")
+			return nil
+		})
+		Expect(err).To(Equal(redis.Nil))
+		Expect(cmds).To(HaveLen(1))
+		Expect(cmds[0]).To(Equal(get))
+		Expect(get.Err()).To(Equal(redis.Nil))
+		Expect(get.Val()).To(Equal(""))
+	})
+
+	assertPipeline := func() {
+		It("returns no errors when there are no commands", func() {
+			_, err := pipe.Exec()
+			Expect(err).NotTo(HaveOccurred())
+		})
+
+		It("discards queued commands", func() {
+			pipe.Get("key")
+			pipe.Discard()
+			cmds, err := pipe.Exec()
+			Expect(err).NotTo(HaveOccurred())
+			Expect(cmds).To(BeNil())
+		})
+
+		It("handles val/err", func() {
+			err := client.Set("key", "value", 0).Err()
+			Expect(err).NotTo(HaveOccurred())
+
+			get := pipe.Get("key")
+			cmds, err := pipe.Exec()
+			Expect(err).NotTo(HaveOccurred())
+			Expect(cmds).To(HaveLen(1))
+
+			val, err := get.Result()
+			Expect(err).NotTo(HaveOccurred())
+			Expect(val).To(Equal("value"))
+		})
+
+		It("supports custom command", func() {
+			pipe.Do("ping")
+			cmds, err := pipe.Exec()
+			Expect(err).NotTo(HaveOccurred())
+			Expect(cmds).To(HaveLen(1))
+		})
+	}
+
+	Describe("Pipeline", func() {
+		BeforeEach(func() {
+			pipe = client.Pipeline().(*redis.Pipeline)
+		})
+
+		assertPipeline()
+	})
+
+	Describe("TxPipeline", func() {
+		BeforeEach(func() {
+			pipe = client.TxPipeline().(*redis.Pipeline)
+		})
+
+		assertPipeline()
+	})
+})

+ 150 - 0
go/gopath/src/github.com/go-redis/redis/pool_test.go

@@ -0,0 +1,150 @@
+package redis_test
+
+import (
+	"context"
+	"time"
+
+	"github.com/go-redis/redis"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("pool", func() {
+	var client *redis.Client
+
+	BeforeEach(func() {
+		opt := redisOptions()
+		opt.MinIdleConns = 0
+		opt.MaxConnAge = 0
+		opt.IdleTimeout = time.Second
+		client = redis.NewClient(opt)
+	})
+
+	AfterEach(func() {
+		Expect(client.Close()).NotTo(HaveOccurred())
+	})
+
+	It("respects max size", func() {
+		perform(1000, func(id int) {
+			val, err := client.Ping().Result()
+			Expect(err).NotTo(HaveOccurred())
+			Expect(val).To(Equal("PONG"))
+		})
+
+		pool := client.Pool()
+		Expect(pool.Len()).To(BeNumerically("<=", 10))
+		Expect(pool.IdleLen()).To(BeNumerically("<=", 10))
+		Expect(pool.Len()).To(Equal(pool.IdleLen()))
+	})
+
+	It("respects max size on multi", func() {
+		perform(1000, func(id int) {
+			var ping *redis.StatusCmd
+
+			err := client.Watch(func(tx *redis.Tx) error {
+				cmds, err := tx.Pipelined(func(pipe redis.Pipeliner) error {
+					ping = pipe.Ping()
+					return nil
+				})
+				Expect(err).NotTo(HaveOccurred())
+				Expect(cmds).To(HaveLen(1))
+				return err
+			})
+			Expect(err).NotTo(HaveOccurred())
+
+			Expect(ping.Err()).NotTo(HaveOccurred())
+			Expect(ping.Val()).To(Equal("PONG"))
+		})
+
+		pool := client.Pool()
+		Expect(pool.Len()).To(BeNumerically("<=", 10))
+		Expect(pool.IdleLen()).To(BeNumerically("<=", 10))
+		Expect(pool.Len()).To(Equal(pool.IdleLen()))
+	})
+
+	It("respects max size on pipelines", func() {
+		perform(1000, func(id int) {
+			pipe := client.Pipeline()
+			ping := pipe.Ping()
+			cmds, err := pipe.Exec()
+			Expect(err).NotTo(HaveOccurred())
+			Expect(cmds).To(HaveLen(1))
+			Expect(ping.Err()).NotTo(HaveOccurred())
+			Expect(ping.Val()).To(Equal("PONG"))
+			Expect(pipe.Close()).NotTo(HaveOccurred())
+		})
+
+		pool := client.Pool()
+		Expect(pool.Len()).To(BeNumerically("<=", 10))
+		Expect(pool.IdleLen()).To(BeNumerically("<=", 10))
+		Expect(pool.Len()).To(Equal(pool.IdleLen()))
+	})
+
+	It("removes broken connections", func() {
+		cn, err := client.Pool().Get(context.Background())
+		Expect(err).NotTo(HaveOccurred())
+		cn.SetNetConn(&badConn{})
+		client.Pool().Put(cn)
+
+		err = client.Ping().Err()
+		Expect(err).To(MatchError("bad connection"))
+
+		val, err := client.Ping().Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(val).To(Equal("PONG"))
+
+		pool := client.Pool()
+		Expect(pool.Len()).To(Equal(1))
+		Expect(pool.IdleLen()).To(Equal(1))
+
+		stats := pool.Stats()
+		Expect(stats.Hits).To(Equal(uint32(1)))
+		Expect(stats.Misses).To(Equal(uint32(2)))
+		Expect(stats.Timeouts).To(Equal(uint32(0)))
+	})
+
+	It("reuses connections", func() {
+		for i := 0; i < 100; i++ {
+			val, err := client.Ping().Result()
+			Expect(err).NotTo(HaveOccurred())
+			Expect(val).To(Equal("PONG"))
+		}
+
+		pool := client.Pool()
+		Expect(pool.Len()).To(Equal(1))
+		Expect(pool.IdleLen()).To(Equal(1))
+
+		stats := pool.Stats()
+		Expect(stats.Hits).To(Equal(uint32(99)))
+		Expect(stats.Misses).To(Equal(uint32(1)))
+		Expect(stats.Timeouts).To(Equal(uint32(0)))
+	})
+
+	It("removes idle connections", func() {
+		err := client.Ping().Err()
+		Expect(err).NotTo(HaveOccurred())
+
+		stats := client.PoolStats()
+		Expect(stats).To(Equal(&redis.PoolStats{
+			Hits:       0,
+			Misses:     1,
+			Timeouts:   0,
+			TotalConns: 1,
+			IdleConns:  1,
+			StaleConns: 0,
+		}))
+
+		time.Sleep(2 * time.Second)
+
+		stats = client.PoolStats()
+		Expect(stats).To(Equal(&redis.PoolStats{
+			Hits:       0,
+			Misses:     1,
+			Timeouts:   0,
+			TotalConns: 0,
+			IdleConns:  0,
+			StaleConns: 1,
+		}))
+	})
+})

+ 592 - 0
go/gopath/src/github.com/go-redis/redis/pubsub.go

@@ -0,0 +1,592 @@
+package redis
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"strings"
+	"sync"
+	"time"
+
+	"github.com/go-redis/redis/internal"
+	"github.com/go-redis/redis/internal/pool"
+	"github.com/go-redis/redis/internal/proto"
+)
+
+const pingTimeout = 30 * time.Second
+
+var errPingTimeout = errors.New("redis: ping timeout")
+
+// PubSub implements Pub/Sub commands as described in
+// http://redis.io/topics/pubsub. Message receiving is NOT safe
+// for concurrent use by multiple goroutines.
+//
+// PubSub automatically reconnects to Redis Server and resubscribes
+// to the channels in case of network errors.
+type PubSub struct {
+	opt *Options
+
+	newConn   func([]string) (*pool.Conn, error)
+	closeConn func(*pool.Conn) error
+
+	mu       sync.Mutex
+	cn       *pool.Conn
+	channels map[string]struct{}
+	patterns map[string]struct{}
+
+	closed bool
+	exit   chan struct{}
+
+	cmd *Cmd
+
+	chOnce sync.Once
+	msgCh  chan *Message
+	allCh  chan interface{}
+	ping   chan struct{}
+}
+
+func (c *PubSub) String() string {
+	channels := mapKeys(c.channels)
+	channels = append(channels, mapKeys(c.patterns)...)
+	return fmt.Sprintf("PubSub(%s)", strings.Join(channels, ", "))
+}
+
+func (c *PubSub) init() {
+	c.exit = make(chan struct{})
+}
+
+func (c *PubSub) connWithLock() (*pool.Conn, error) {
+	c.mu.Lock()
+	cn, err := c.conn(nil)
+	c.mu.Unlock()
+	return cn, err
+}
+
+func (c *PubSub) conn(newChannels []string) (*pool.Conn, error) {
+	if c.closed {
+		return nil, pool.ErrClosed
+	}
+	if c.cn != nil {
+		return c.cn, nil
+	}
+
+	channels := mapKeys(c.channels)
+	channels = append(channels, newChannels...)
+
+	cn, err := c.newConn(channels)
+	if err != nil {
+		return nil, err
+	}
+
+	if err := c.resubscribe(cn); err != nil {
+		_ = c.closeConn(cn)
+		return nil, err
+	}
+
+	c.cn = cn
+	return cn, nil
+}
+
+func (c *PubSub) writeCmd(ctx context.Context, cn *pool.Conn, cmd Cmder) error {
+	return cn.WithWriter(ctx, c.opt.WriteTimeout, func(wr *proto.Writer) error {
+		return writeCmd(wr, cmd)
+	})
+}
+
+func (c *PubSub) resubscribe(cn *pool.Conn) error {
+	var firstErr error
+
+	if len(c.channels) > 0 {
+		firstErr = c._subscribe(cn, "subscribe", mapKeys(c.channels))
+	}
+
+	if len(c.patterns) > 0 {
+		err := c._subscribe(cn, "psubscribe", mapKeys(c.patterns))
+		if err != nil && firstErr == nil {
+			firstErr = err
+		}
+	}
+
+	return firstErr
+}
+
+func mapKeys(m map[string]struct{}) []string {
+	s := make([]string, len(m))
+	i := 0
+	for k := range m {
+		s[i] = k
+		i++
+	}
+	return s
+}
+
+func (c *PubSub) _subscribe(
+	cn *pool.Conn, redisCmd string, channels []string,
+) error {
+	args := make([]interface{}, 0, 1+len(channels))
+	args = append(args, redisCmd)
+	for _, channel := range channels {
+		args = append(args, channel)
+	}
+	cmd := NewSliceCmd(args...)
+	return c.writeCmd(context.TODO(), cn, cmd)
+}
+
+func (c *PubSub) releaseConnWithLock(cn *pool.Conn, err error, allowTimeout bool) {
+	c.mu.Lock()
+	c.releaseConn(cn, err, allowTimeout)
+	c.mu.Unlock()
+}
+
+func (c *PubSub) releaseConn(cn *pool.Conn, err error, allowTimeout bool) {
+	if c.cn != cn {
+		return
+	}
+	if internal.IsBadConn(err, allowTimeout) {
+		c.reconnect(err)
+	}
+}
+
+func (c *PubSub) reconnect(reason error) {
+	_ = c.closeTheCn(reason)
+	_, _ = c.conn(nil)
+}
+
+func (c *PubSub) closeTheCn(reason error) error {
+	if c.cn == nil {
+		return nil
+	}
+	if !c.closed {
+		internal.Logger.Printf("redis: discarding bad PubSub connection: %s", reason)
+	}
+	err := c.closeConn(c.cn)
+	c.cn = nil
+	return err
+}
+
+func (c *PubSub) Close() error {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	if c.closed {
+		return pool.ErrClosed
+	}
+	c.closed = true
+	close(c.exit)
+
+	return c.closeTheCn(pool.ErrClosed)
+}
+
+// Subscribe the client to the specified channels. It returns
+// empty subscription if there are no channels.
+func (c *PubSub) Subscribe(channels ...string) error {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	err := c.subscribe("subscribe", channels...)
+	if c.channels == nil {
+		c.channels = make(map[string]struct{})
+	}
+	for _, s := range channels {
+		c.channels[s] = struct{}{}
+	}
+	return err
+}
+
+// PSubscribe the client to the given patterns. It returns
+// empty subscription if there are no patterns.
+func (c *PubSub) PSubscribe(patterns ...string) error {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	err := c.subscribe("psubscribe", patterns...)
+	if c.patterns == nil {
+		c.patterns = make(map[string]struct{})
+	}
+	for _, s := range patterns {
+		c.patterns[s] = struct{}{}
+	}
+	return err
+}
+
+// Unsubscribe the client from the given channels, or from all of
+// them if none is given.
+func (c *PubSub) Unsubscribe(channels ...string) error {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	for _, channel := range channels {
+		delete(c.channels, channel)
+	}
+	err := c.subscribe("unsubscribe", channels...)
+	return err
+}
+
+// PUnsubscribe the client from the given patterns, or from all of
+// them if none is given.
+func (c *PubSub) PUnsubscribe(patterns ...string) error {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	for _, pattern := range patterns {
+		delete(c.patterns, pattern)
+	}
+	err := c.subscribe("punsubscribe", patterns...)
+	return err
+}
+
+func (c *PubSub) subscribe(redisCmd string, channels ...string) error {
+	cn, err := c.conn(channels)
+	if err != nil {
+		return err
+	}
+
+	err = c._subscribe(cn, redisCmd, channels)
+	c.releaseConn(cn, err, false)
+	return err
+}
+
+func (c *PubSub) Ping(payload ...string) error {
+	args := []interface{}{"ping"}
+	if len(payload) == 1 {
+		args = append(args, payload[0])
+	}
+	cmd := NewCmd(args...)
+
+	cn, err := c.connWithLock()
+	if err != nil {
+		return err
+	}
+
+	err = c.writeCmd(context.TODO(), cn, cmd)
+	c.releaseConnWithLock(cn, err, false)
+	return err
+}
+
+// Subscription received after a successful subscription to channel.
+type Subscription struct {
+	// Can be "subscribe", "unsubscribe", "psubscribe" or "punsubscribe".
+	Kind string
+	// Channel name we have subscribed to.
+	Channel string
+	// Number of channels we are currently subscribed to.
+	Count int
+}
+
+func (m *Subscription) String() string {
+	return fmt.Sprintf("%s: %s", m.Kind, m.Channel)
+}
+
+// Message received as result of a PUBLISH command issued by another client.
+type Message struct {
+	Channel string
+	Pattern string
+	Payload string
+}
+
+func (m *Message) String() string {
+	return fmt.Sprintf("Message<%s: %s>", m.Channel, m.Payload)
+}
+
+// Pong received as result of a PING command issued by another client.
+type Pong struct {
+	Payload string
+}
+
+func (p *Pong) String() string {
+	if p.Payload != "" {
+		return fmt.Sprintf("Pong<%s>", p.Payload)
+	}
+	return "Pong"
+}
+
+func (c *PubSub) newMessage(reply interface{}) (interface{}, error) {
+	switch reply := reply.(type) {
+	case string:
+		return &Pong{
+			Payload: reply,
+		}, nil
+	case []interface{}:
+		switch kind := reply[0].(string); kind {
+		case "subscribe", "unsubscribe", "psubscribe", "punsubscribe":
+			return &Subscription{
+				Kind:    kind,
+				Channel: reply[1].(string),
+				Count:   int(reply[2].(int64)),
+			}, nil
+		case "message":
+			return &Message{
+				Channel: reply[1].(string),
+				Payload: reply[2].(string),
+			}, nil
+		case "pmessage":
+			return &Message{
+				Pattern: reply[1].(string),
+				Channel: reply[2].(string),
+				Payload: reply[3].(string),
+			}, nil
+		case "pong":
+			return &Pong{
+				Payload: reply[1].(string),
+			}, nil
+		default:
+			return nil, fmt.Errorf("redis: unsupported pubsub message: %q", kind)
+		}
+	default:
+		return nil, fmt.Errorf("redis: unsupported pubsub message: %#v", reply)
+	}
+}
+
+// ReceiveTimeout acts like Receive but returns an error if message
+// is not received in time. This is low-level API and in most cases
+// Channel should be used instead.
+func (c *PubSub) ReceiveTimeout(timeout time.Duration) (interface{}, error) {
+	if c.cmd == nil {
+		c.cmd = NewCmd()
+	}
+
+	cn, err := c.connWithLock()
+	if err != nil {
+		return nil, err
+	}
+
+	err = cn.WithReader(context.TODO(), timeout, func(rd *proto.Reader) error {
+		return c.cmd.readReply(rd)
+	})
+
+	c.releaseConnWithLock(cn, err, timeout > 0)
+	if err != nil {
+		return nil, err
+	}
+
+	return c.newMessage(c.cmd.Val())
+}
+
+// Receive returns a message as a Subscription, Message, Pong or error.
+// See PubSub example for details. This is low-level API and in most cases
+// Channel should be used instead.
+func (c *PubSub) Receive() (interface{}, error) {
+	return c.ReceiveTimeout(0)
+}
+
+// ReceiveMessage returns a Message or error ignoring Subscription and Pong
+// messages. This is low-level API and in most cases Channel should be used
+// instead.
+func (c *PubSub) ReceiveMessage() (*Message, error) {
+	for {
+		msg, err := c.Receive()
+		if err != nil {
+			return nil, err
+		}
+
+		switch msg := msg.(type) {
+		case *Subscription:
+			// Ignore.
+		case *Pong:
+			// Ignore.
+		case *Message:
+			return msg, nil
+		default:
+			err := fmt.Errorf("redis: unknown message: %T", msg)
+			return nil, err
+		}
+	}
+}
+
+// Channel returns a Go channel for concurrently receiving messages.
+// The channel is closed together with the PubSub. If the Go channel
+// is blocked full for 30 seconds the message is dropped.
+// Receive* APIs can not be used after channel is created.
+//
+// go-redis periodically sends ping messages to test connection health
+// and re-subscribes if ping can not not received for 30 seconds.
+func (c *PubSub) Channel() <-chan *Message {
+	return c.ChannelSize(100)
+}
+
+// ChannelSize is like Channel, but creates a Go channel
+// with specified buffer size.
+func (c *PubSub) ChannelSize(size int) <-chan *Message {
+	c.chOnce.Do(func() {
+		c.initPing()
+		c.initMsgChan(size)
+	})
+	if c.msgCh == nil {
+		err := fmt.Errorf("redis: Channel can't be called after ChannelWithSubscriptions")
+		panic(err)
+	}
+	if cap(c.msgCh) != size {
+		err := fmt.Errorf("redis: PubSub.Channel size can not be changed once created")
+		panic(err)
+	}
+	return c.msgCh
+}
+
+// ChannelWithSubscriptions is like Channel, but message type can be either
+// *Subscription or *Message. Subscription messages can be used to detect
+// reconnections.
+//
+// ChannelWithSubscriptions can not be used together with Channel or ChannelSize.
+func (c *PubSub) ChannelWithSubscriptions(size int) <-chan interface{} {
+	c.chOnce.Do(func() {
+		c.initPing()
+		c.initAllChan(size)
+	})
+	if c.allCh == nil {
+		err := fmt.Errorf("redis: ChannelWithSubscriptions can't be called after Channel")
+		panic(err)
+	}
+	if cap(c.allCh) != size {
+		err := fmt.Errorf("redis: PubSub.Channel size can not be changed once created")
+		panic(err)
+	}
+	return c.allCh
+}
+
+func (c *PubSub) initPing() {
+	c.ping = make(chan struct{}, 1)
+	go func() {
+		timer := time.NewTimer(pingTimeout)
+		timer.Stop()
+
+		healthy := true
+		for {
+			timer.Reset(pingTimeout)
+			select {
+			case <-c.ping:
+				healthy = true
+				if !timer.Stop() {
+					<-timer.C
+				}
+			case <-timer.C:
+				pingErr := c.Ping()
+				if healthy {
+					healthy = false
+				} else {
+					if pingErr == nil {
+						pingErr = errPingTimeout
+					}
+					c.mu.Lock()
+					c.reconnect(pingErr)
+					c.mu.Unlock()
+				}
+			case <-c.exit:
+				return
+			}
+		}
+	}()
+}
+
+// initMsgChan must be in sync with initAllChan.
+func (c *PubSub) initMsgChan(size int) {
+	c.msgCh = make(chan *Message, size)
+	go func() {
+		timer := time.NewTimer(pingTimeout)
+		timer.Stop()
+
+		var errCount int
+		for {
+			msg, err := c.Receive()
+			if err != nil {
+				if err == pool.ErrClosed {
+					close(c.msgCh)
+					return
+				}
+				if errCount > 0 {
+					time.Sleep(c.retryBackoff(errCount))
+				}
+				errCount++
+				continue
+			}
+
+			errCount = 0
+
+			// Any message is as good as a ping.
+			select {
+			case c.ping <- struct{}{}:
+			default:
+			}
+
+			switch msg := msg.(type) {
+			case *Subscription:
+				// Ignore.
+			case *Pong:
+				// Ignore.
+			case *Message:
+				timer.Reset(pingTimeout)
+				select {
+				case c.msgCh <- msg:
+					if !timer.Stop() {
+						<-timer.C
+					}
+				case <-timer.C:
+					internal.Logger.Printf(
+						"redis: %s channel is full for %s (message is dropped)", c, pingTimeout)
+				}
+			default:
+				internal.Logger.Printf("redis: unknown message type: %T", msg)
+			}
+		}
+	}()
+}
+
+// initAllChan must be in sync with initMsgChan.
+func (c *PubSub) initAllChan(size int) {
+	c.allCh = make(chan interface{}, size)
+	go func() {
+		timer := time.NewTimer(pingTimeout)
+		timer.Stop()
+
+		var errCount int
+		for {
+			msg, err := c.Receive()
+			if err != nil {
+				if err == pool.ErrClosed {
+					close(c.allCh)
+					return
+				}
+				if errCount > 0 {
+					time.Sleep(c.retryBackoff(errCount))
+				}
+				errCount++
+				continue
+			}
+
+			errCount = 0
+
+			// Any message is as good as a ping.
+			select {
+			case c.ping <- struct{}{}:
+			default:
+			}
+
+			switch msg := msg.(type) {
+			case *Subscription:
+				c.sendMessage(msg, timer)
+			case *Pong:
+				// Ignore.
+			case *Message:
+				c.sendMessage(msg, timer)
+			default:
+				internal.Logger.Printf("redis: unknown message type: %T", msg)
+			}
+		}
+	}()
+}
+
+func (c *PubSub) sendMessage(msg interface{}, timer *time.Timer) {
+	timer.Reset(pingTimeout)
+	select {
+	case c.allCh <- msg:
+		if !timer.Stop() {
+			<-timer.C
+		}
+	case <-timer.C:
+		internal.Logger.Printf(
+			"redis: %s channel is full for %s (message is dropped)", c, pingTimeout)
+	}
+}
+
+func (c *PubSub) retryBackoff(attempt int) time.Duration {
+	return internal.RetryBackoff(attempt, c.opt.MinRetryBackoff, c.opt.MaxRetryBackoff)
+}

+ 446 - 0
go/gopath/src/github.com/go-redis/redis/pubsub_test.go

@@ -0,0 +1,446 @@
+package redis_test
+
+import (
+	"io"
+	"net"
+	"sync"
+	"time"
+
+	"github.com/go-redis/redis"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("PubSub", func() {
+	var client *redis.Client
+
+	BeforeEach(func() {
+		opt := redisOptions()
+		opt.MinIdleConns = 0
+		opt.MaxConnAge = 0
+		client = redis.NewClient(opt)
+		Expect(client.FlushDB().Err()).NotTo(HaveOccurred())
+	})
+
+	AfterEach(func() {
+		Expect(client.Close()).NotTo(HaveOccurred())
+	})
+
+	It("implements Stringer", func() {
+		pubsub := client.PSubscribe("mychannel*")
+		defer pubsub.Close()
+
+		Expect(pubsub.String()).To(Equal("PubSub(mychannel*)"))
+	})
+
+	It("should support pattern matching", func() {
+		pubsub := client.PSubscribe("mychannel*")
+		defer pubsub.Close()
+
+		{
+			msgi, err := pubsub.ReceiveTimeout(time.Second)
+			Expect(err).NotTo(HaveOccurred())
+			subscr := msgi.(*redis.Subscription)
+			Expect(subscr.Kind).To(Equal("psubscribe"))
+			Expect(subscr.Channel).To(Equal("mychannel*"))
+			Expect(subscr.Count).To(Equal(1))
+		}
+
+		{
+			msgi, err := pubsub.ReceiveTimeout(time.Second)
+			Expect(err.(net.Error).Timeout()).To(Equal(true))
+			Expect(msgi).To(BeNil())
+		}
+
+		n, err := client.Publish("mychannel1", "hello").Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(n).To(Equal(int64(1)))
+
+		Expect(pubsub.PUnsubscribe("mychannel*")).NotTo(HaveOccurred())
+
+		{
+			msgi, err := pubsub.ReceiveTimeout(time.Second)
+			Expect(err).NotTo(HaveOccurred())
+			subscr := msgi.(*redis.Message)
+			Expect(subscr.Channel).To(Equal("mychannel1"))
+			Expect(subscr.Pattern).To(Equal("mychannel*"))
+			Expect(subscr.Payload).To(Equal("hello"))
+		}
+
+		{
+			msgi, err := pubsub.ReceiveTimeout(time.Second)
+			Expect(err).NotTo(HaveOccurred())
+			subscr := msgi.(*redis.Subscription)
+			Expect(subscr.Kind).To(Equal("punsubscribe"))
+			Expect(subscr.Channel).To(Equal("mychannel*"))
+			Expect(subscr.Count).To(Equal(0))
+		}
+
+		stats := client.PoolStats()
+		Expect(stats.Misses).To(Equal(uint32(1)))
+	})
+
+	It("should pub/sub channels", func() {
+		channels, err := client.PubSubChannels("mychannel*").Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(channels).To(BeEmpty())
+
+		pubsub := client.Subscribe("mychannel", "mychannel2")
+		defer pubsub.Close()
+
+		channels, err = client.PubSubChannels("mychannel*").Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(channels).To(ConsistOf([]string{"mychannel", "mychannel2"}))
+
+		channels, err = client.PubSubChannels("").Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(channels).To(BeEmpty())
+
+		channels, err = client.PubSubChannels("*").Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(len(channels)).To(BeNumerically(">=", 2))
+	})
+
+	It("should return the numbers of subscribers", func() {
+		pubsub := client.Subscribe("mychannel", "mychannel2")
+		defer pubsub.Close()
+
+		channels, err := client.PubSubNumSub("mychannel", "mychannel2", "mychannel3").Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(channels).To(Equal(map[string]int64{
+			"mychannel":  1,
+			"mychannel2": 1,
+			"mychannel3": 0,
+		}))
+	})
+
+	It("should return the numbers of subscribers by pattern", func() {
+		num, err := client.PubSubNumPat().Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(num).To(Equal(int64(0)))
+
+		pubsub := client.PSubscribe("*")
+		defer pubsub.Close()
+
+		num, err = client.PubSubNumPat().Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(num).To(Equal(int64(1)))
+	})
+
+	It("should pub/sub", func() {
+		pubsub := client.Subscribe("mychannel", "mychannel2")
+		defer pubsub.Close()
+
+		{
+			msgi, err := pubsub.ReceiveTimeout(time.Second)
+			Expect(err).NotTo(HaveOccurred())
+			subscr := msgi.(*redis.Subscription)
+			Expect(subscr.Kind).To(Equal("subscribe"))
+			Expect(subscr.Channel).To(Equal("mychannel"))
+			Expect(subscr.Count).To(Equal(1))
+		}
+
+		{
+			msgi, err := pubsub.ReceiveTimeout(time.Second)
+			Expect(err).NotTo(HaveOccurred())
+			subscr := msgi.(*redis.Subscription)
+			Expect(subscr.Kind).To(Equal("subscribe"))
+			Expect(subscr.Channel).To(Equal("mychannel2"))
+			Expect(subscr.Count).To(Equal(2))
+		}
+
+		{
+			msgi, err := pubsub.ReceiveTimeout(time.Second)
+			Expect(err.(net.Error).Timeout()).To(Equal(true))
+			Expect(msgi).NotTo(HaveOccurred())
+		}
+
+		n, err := client.Publish("mychannel", "hello").Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(n).To(Equal(int64(1)))
+
+		n, err = client.Publish("mychannel2", "hello2").Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(n).To(Equal(int64(1)))
+
+		Expect(pubsub.Unsubscribe("mychannel", "mychannel2")).NotTo(HaveOccurred())
+
+		{
+			msgi, err := pubsub.ReceiveTimeout(time.Second)
+			Expect(err).NotTo(HaveOccurred())
+			msg := msgi.(*redis.Message)
+			Expect(msg.Channel).To(Equal("mychannel"))
+			Expect(msg.Payload).To(Equal("hello"))
+		}
+
+		{
+			msgi, err := pubsub.ReceiveTimeout(time.Second)
+			Expect(err).NotTo(HaveOccurred())
+			msg := msgi.(*redis.Message)
+			Expect(msg.Channel).To(Equal("mychannel2"))
+			Expect(msg.Payload).To(Equal("hello2"))
+		}
+
+		{
+			msgi, err := pubsub.ReceiveTimeout(time.Second)
+			Expect(err).NotTo(HaveOccurred())
+			subscr := msgi.(*redis.Subscription)
+			Expect(subscr.Kind).To(Equal("unsubscribe"))
+			Expect(subscr.Channel).To(Equal("mychannel"))
+			Expect(subscr.Count).To(Equal(1))
+		}
+
+		{
+			msgi, err := pubsub.ReceiveTimeout(time.Second)
+			Expect(err).NotTo(HaveOccurred())
+			subscr := msgi.(*redis.Subscription)
+			Expect(subscr.Kind).To(Equal("unsubscribe"))
+			Expect(subscr.Channel).To(Equal("mychannel2"))
+			Expect(subscr.Count).To(Equal(0))
+		}
+
+		stats := client.PoolStats()
+		Expect(stats.Misses).To(Equal(uint32(1)))
+	})
+
+	It("should ping/pong", func() {
+		pubsub := client.Subscribe("mychannel")
+		defer pubsub.Close()
+
+		_, err := pubsub.ReceiveTimeout(time.Second)
+		Expect(err).NotTo(HaveOccurred())
+
+		err = pubsub.Ping("")
+		Expect(err).NotTo(HaveOccurred())
+
+		msgi, err := pubsub.ReceiveTimeout(time.Second)
+		Expect(err).NotTo(HaveOccurred())
+		pong := msgi.(*redis.Pong)
+		Expect(pong.Payload).To(Equal(""))
+	})
+
+	It("should ping/pong with payload", func() {
+		pubsub := client.Subscribe("mychannel")
+		defer pubsub.Close()
+
+		_, err := pubsub.ReceiveTimeout(time.Second)
+		Expect(err).NotTo(HaveOccurred())
+
+		err = pubsub.Ping("hello")
+		Expect(err).NotTo(HaveOccurred())
+
+		msgi, err := pubsub.ReceiveTimeout(time.Second)
+		Expect(err).NotTo(HaveOccurred())
+		pong := msgi.(*redis.Pong)
+		Expect(pong.Payload).To(Equal("hello"))
+	})
+
+	It("should multi-ReceiveMessage", func() {
+		pubsub := client.Subscribe("mychannel")
+		defer pubsub.Close()
+
+		subscr, err := pubsub.ReceiveTimeout(time.Second)
+		Expect(err).NotTo(HaveOccurred())
+		Expect(subscr).To(Equal(&redis.Subscription{
+			Kind:    "subscribe",
+			Channel: "mychannel",
+			Count:   1,
+		}))
+
+		err = client.Publish("mychannel", "hello").Err()
+		Expect(err).NotTo(HaveOccurred())
+
+		err = client.Publish("mychannel", "world").Err()
+		Expect(err).NotTo(HaveOccurred())
+
+		msg, err := pubsub.ReceiveMessage()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(msg.Channel).To(Equal("mychannel"))
+		Expect(msg.Payload).To(Equal("hello"))
+
+		msg, err = pubsub.ReceiveMessage()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(msg.Channel).To(Equal("mychannel"))
+		Expect(msg.Payload).To(Equal("world"))
+	})
+
+	It("returns an error when subscribe fails", func() {
+		pubsub := client.Subscribe()
+		defer pubsub.Close()
+
+		pubsub.SetNetConn(&badConn{
+			readErr:  io.EOF,
+			writeErr: io.EOF,
+		})
+
+		err := pubsub.Subscribe("mychannel")
+		Expect(err).To(MatchError("EOF"))
+
+		err = pubsub.Subscribe("mychannel")
+		Expect(err).NotTo(HaveOccurred())
+	})
+
+	expectReceiveMessageOnError := func(pubsub *redis.PubSub) {
+		pubsub.SetNetConn(&badConn{
+			readErr:  io.EOF,
+			writeErr: io.EOF,
+		})
+
+		step := make(chan struct{}, 3)
+
+		go func() {
+			defer GinkgoRecover()
+
+			Eventually(step).Should(Receive())
+			err := client.Publish("mychannel", "hello").Err()
+			Expect(err).NotTo(HaveOccurred())
+			step <- struct{}{}
+		}()
+
+		_, err := pubsub.ReceiveMessage()
+		Expect(err).To(Equal(io.EOF))
+		step <- struct{}{}
+
+		msg, err := pubsub.ReceiveMessage()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(msg.Channel).To(Equal("mychannel"))
+		Expect(msg.Payload).To(Equal("hello"))
+
+		Eventually(step).Should(Receive())
+	}
+
+	It("Subscribe should reconnect on ReceiveMessage error", func() {
+		pubsub := client.Subscribe("mychannel")
+		defer pubsub.Close()
+
+		subscr, err := pubsub.ReceiveTimeout(time.Second)
+		Expect(err).NotTo(HaveOccurred())
+		Expect(subscr).To(Equal(&redis.Subscription{
+			Kind:    "subscribe",
+			Channel: "mychannel",
+			Count:   1,
+		}))
+
+		expectReceiveMessageOnError(pubsub)
+	})
+
+	It("PSubscribe should reconnect on ReceiveMessage error", func() {
+		pubsub := client.PSubscribe("mychannel")
+		defer pubsub.Close()
+
+		subscr, err := pubsub.ReceiveTimeout(time.Second)
+		Expect(err).NotTo(HaveOccurred())
+		Expect(subscr).To(Equal(&redis.Subscription{
+			Kind:    "psubscribe",
+			Channel: "mychannel",
+			Count:   1,
+		}))
+
+		expectReceiveMessageOnError(pubsub)
+	})
+
+	It("should return on Close", func() {
+		pubsub := client.Subscribe("mychannel")
+		defer pubsub.Close()
+
+		var wg sync.WaitGroup
+		wg.Add(1)
+		go func() {
+			defer GinkgoRecover()
+
+			wg.Done()
+			defer wg.Done()
+
+			_, err := pubsub.ReceiveMessage()
+			Expect(err).To(HaveOccurred())
+			Expect(err.Error()).To(SatisfyAny(
+				Equal("redis: client is closed"),
+				ContainSubstring("use of closed network connection"),
+			))
+		}()
+
+		wg.Wait()
+		wg.Add(1)
+
+		Expect(pubsub.Close()).NotTo(HaveOccurred())
+
+		wg.Wait()
+	})
+
+	It("should ReceiveMessage without a subscription", func() {
+		timeout := 100 * time.Millisecond
+
+		pubsub := client.Subscribe()
+		defer pubsub.Close()
+
+		var wg sync.WaitGroup
+		wg.Add(1)
+		go func() {
+			defer GinkgoRecover()
+			defer wg.Done()
+
+			time.Sleep(timeout)
+
+			err := pubsub.Subscribe("mychannel")
+			Expect(err).NotTo(HaveOccurred())
+
+			time.Sleep(timeout)
+
+			err = client.Publish("mychannel", "hello").Err()
+			Expect(err).NotTo(HaveOccurred())
+		}()
+
+		msg, err := pubsub.ReceiveMessage()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(msg.Channel).To(Equal("mychannel"))
+		Expect(msg.Payload).To(Equal("hello"))
+
+		wg.Wait()
+	})
+
+	It("handles big message payload", func() {
+		pubsub := client.Subscribe("mychannel")
+		defer pubsub.Close()
+
+		ch := pubsub.Channel()
+
+		bigVal := bigVal()
+		err := client.Publish("mychannel", bigVal).Err()
+		Expect(err).NotTo(HaveOccurred())
+
+		var msg *redis.Message
+		Eventually(ch).Should(Receive(&msg))
+		Expect(msg.Channel).To(Equal("mychannel"))
+		Expect(msg.Payload).To(Equal(string(bigVal)))
+	})
+
+	It("supports concurrent Ping and Receive", func() {
+		const N = 100
+
+		pubsub := client.Subscribe("mychannel")
+		defer pubsub.Close()
+
+		done := make(chan struct{})
+		go func() {
+			defer GinkgoRecover()
+
+			for i := 0; i < N; i++ {
+				_, err := pubsub.ReceiveTimeout(5 * time.Second)
+				Expect(err).NotTo(HaveOccurred())
+			}
+			close(done)
+		}()
+
+		for i := 0; i < N; i++ {
+			err := pubsub.Ping()
+			Expect(err).NotTo(HaveOccurred())
+		}
+
+		select {
+		case <-done:
+		case <-time.After(30 * time.Second):
+			Fail("timeout")
+		}
+	})
+})

+ 347 - 0
go/gopath/src/github.com/go-redis/redis/race_test.go

@@ -0,0 +1,347 @@
+package redis_test
+
+import (
+	"bytes"
+	"fmt"
+	"net"
+	"strconv"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"github.com/go-redis/redis"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("races", func() {
+	var client *redis.Client
+	var C, N int
+
+	BeforeEach(func() {
+		client = redis.NewClient(redisOptions())
+		Expect(client.FlushDB().Err()).To(BeNil())
+
+		C, N = 10, 1000
+		if testing.Short() {
+			C = 4
+			N = 100
+		}
+	})
+
+	AfterEach(func() {
+		err := client.Close()
+		Expect(err).NotTo(HaveOccurred())
+	})
+
+	It("should echo", func() {
+		perform(C, func(id int) {
+			for i := 0; i < N; i++ {
+				msg := fmt.Sprintf("echo %d %d", id, i)
+				echo, err := client.Echo(msg).Result()
+				Expect(err).NotTo(HaveOccurred())
+				Expect(echo).To(Equal(msg))
+			}
+		})
+	})
+
+	It("should incr", func() {
+		key := "TestIncrFromGoroutines"
+
+		perform(C, func(id int) {
+			for i := 0; i < N; i++ {
+				err := client.Incr(key).Err()
+				Expect(err).NotTo(HaveOccurred())
+			}
+		})
+
+		val, err := client.Get(key).Int64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(val).To(Equal(int64(C * N)))
+	})
+
+	It("should handle many keys", func() {
+		perform(C, func(id int) {
+			for i := 0; i < N; i++ {
+				err := client.Set(
+					fmt.Sprintf("keys.key-%d-%d", id, i),
+					fmt.Sprintf("hello-%d-%d", id, i),
+					0,
+				).Err()
+				Expect(err).NotTo(HaveOccurred())
+			}
+		})
+
+		keys := client.Keys("keys.*")
+		Expect(keys.Err()).NotTo(HaveOccurred())
+		Expect(len(keys.Val())).To(Equal(C * N))
+	})
+
+	It("should handle many keys 2", func() {
+		perform(C, func(id int) {
+			keys := []string{"non-existent-key"}
+			for i := 0; i < N; i++ {
+				key := fmt.Sprintf("keys.key-%d", i)
+				keys = append(keys, key)
+
+				err := client.Set(key, fmt.Sprintf("hello-%d", i), 0).Err()
+				Expect(err).NotTo(HaveOccurred())
+			}
+			keys = append(keys, "non-existent-key")
+
+			vals, err := client.MGet(keys...).Result()
+			Expect(err).NotTo(HaveOccurred())
+			Expect(len(vals)).To(Equal(N + 2))
+
+			for i := 0; i < N; i++ {
+				Expect(vals[i+1]).To(Equal(fmt.Sprintf("hello-%d", i)))
+			}
+
+			Expect(vals[0]).To(BeNil())
+			Expect(vals[N+1]).To(BeNil())
+		})
+	})
+
+	It("should handle big vals in Get", func() {
+		C, N = 4, 100
+
+		bigVal := bigVal()
+
+		err := client.Set("key", bigVal, 0).Err()
+		Expect(err).NotTo(HaveOccurred())
+
+		// Reconnect to get new connection.
+		Expect(client.Close()).To(BeNil())
+		client = redis.NewClient(redisOptions())
+
+		perform(C, func(id int) {
+			for i := 0; i < N; i++ {
+				got, err := client.Get("key").Bytes()
+				Expect(err).NotTo(HaveOccurred())
+				Expect(got).To(Equal(bigVal))
+			}
+		})
+	})
+
+	It("should handle big vals in Set", func() {
+		C, N = 4, 100
+
+		bigVal := bigVal()
+		perform(C, func(id int) {
+			for i := 0; i < N; i++ {
+				err := client.Set("key", bigVal, 0).Err()
+				Expect(err).NotTo(HaveOccurred())
+			}
+		})
+	})
+
+	It("should select db", func() {
+		err := client.Set("db", 1, 0).Err()
+		Expect(err).NotTo(HaveOccurred())
+
+		perform(C, func(id int) {
+			opt := redisOptions()
+			opt.DB = id
+			client := redis.NewClient(opt)
+			for i := 0; i < N; i++ {
+				err := client.Set("db", id, 0).Err()
+				Expect(err).NotTo(HaveOccurred())
+
+				n, err := client.Get("db").Int64()
+				Expect(err).NotTo(HaveOccurred())
+				Expect(n).To(Equal(int64(id)))
+			}
+			err := client.Close()
+			Expect(err).NotTo(HaveOccurred())
+		})
+
+		n, err := client.Get("db").Int64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(n).To(Equal(int64(1)))
+	})
+
+	It("should select DB with read timeout", func() {
+		perform(C, func(id int) {
+			opt := redisOptions()
+			opt.DB = id
+			opt.ReadTimeout = time.Nanosecond
+			client := redis.NewClient(opt)
+
+			perform(C, func(id int) {
+				err := client.Ping().Err()
+				Expect(err).To(HaveOccurred())
+				Expect(err.(net.Error).Timeout()).To(BeTrue())
+			})
+
+			err := client.Close()
+			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++ {
+				err := client.Watch(func(tx *redis.Tx) error {
+					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.Pipelined(func(pipe redis.Pipeliner) error {
+						pipe.Set("key", strconv.FormatInt(num+1, 10), 0)
+						return nil
+					})
+					Expect(cmds).To(HaveLen(1))
+					return err
+				}, "key")
+				if err == redis.TxFailedErr {
+					i--
+					continue
+				}
+				Expect(err).NotTo(HaveOccurred())
+			}
+		})
+
+		val, err := client.Get("key").Int64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(val).To(Equal(int64(C * N)))
+	})
+
+	It("should Pipeline", func() {
+		perform(C, func(id int) {
+			pipe := client.Pipeline()
+			for i := 0; i < N; i++ {
+				pipe.Echo(fmt.Sprint(i))
+			}
+
+			cmds, err := pipe.Exec()
+			Expect(err).NotTo(HaveOccurred())
+			Expect(cmds).To(HaveLen(N))
+
+			for i := 0; i < N; i++ {
+				Expect(cmds[i].(*redis.StringCmd).Val()).To(Equal(fmt.Sprint(i)))
+			}
+		})
+	})
+
+	It("should Pipeline", func() {
+		pipe := client.Pipeline()
+		perform(N, func(id int) {
+			pipe.Incr("key")
+		})
+
+		cmds, err := pipe.Exec()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(cmds).To(HaveLen(N))
+
+		n, err := client.Get("key").Int64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(n).To(Equal(int64(N)))
+	})
+
+	It("should TxPipeline", func() {
+		pipe := client.TxPipeline()
+		perform(N, func(id int) {
+			pipe.Incr("key")
+		})
+
+		cmds, err := pipe.Exec()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(cmds).To(HaveLen(N))
+
+		n, err := client.Get("key").Int64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(n).To(Equal(int64(N)))
+	})
+
+	It("should BLPop", func() {
+		var received uint32
+		wg := performAsync(C, func(id int) {
+			for {
+				v, err := client.BLPop(3*time.Second, "list").Result()
+				if err != nil {
+					break
+				}
+				Expect(v).To(Equal([]string{"list", "hello"}))
+				atomic.AddUint32(&received, 1)
+			}
+		})
+
+		perform(C, func(id int) {
+			for i := 0; i < N; i++ {
+				err := client.LPush("list", "hello").Err()
+				Expect(err).NotTo(HaveOccurred())
+			}
+		})
+
+		wg.Wait()
+		Expect(received).To(Equal(uint32(C * N)))
+	})
+})
+
+var _ = Describe("cluster races", func() {
+	var client *redis.ClusterClient
+	var C, N int
+
+	BeforeEach(func() {
+		opt := redisClusterOptions()
+		client = cluster.clusterClient(opt)
+
+		C, N = 10, 1000
+		if testing.Short() {
+			C = 4
+			N = 100
+		}
+	})
+
+	AfterEach(func() {
+		err := client.Close()
+		Expect(err).NotTo(HaveOccurred())
+	})
+
+	It("should echo", func() {
+		perform(C, func(id int) {
+			for i := 0; i < N; i++ {
+				msg := fmt.Sprintf("echo %d %d", id, i)
+				echo, err := client.Echo(msg).Result()
+				Expect(err).NotTo(HaveOccurred())
+				Expect(echo).To(Equal(msg))
+			}
+		})
+	})
+
+	It("should get", func() {
+		perform(C, func(id int) {
+			for i := 0; i < N; i++ {
+				key := fmt.Sprintf("key_%d_%d", id, i)
+				_, err := client.Get(key).Result()
+				Expect(err).To(Equal(redis.Nil))
+			}
+		})
+	})
+
+	It("should incr", func() {
+		key := "TestIncrFromGoroutines"
+
+		perform(C, func(id int) {
+			for i := 0; i < N; i++ {
+				err := client.Incr(key).Err()
+				Expect(err).NotTo(HaveOccurred())
+			}
+		})
+
+		val, err := client.Get(key).Int64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(val).To(Equal(int64(C * N)))
+	})
+})
+
+func bigVal() []byte {
+	return bytes.Repeat([]byte{'*'}, 1<<17) // 128kb
+}

+ 690 - 0
go/gopath/src/github.com/go-redis/redis/redis.go

@@ -0,0 +1,690 @@
+package redis
+
+import (
+	"context"
+	"fmt"
+	"log"
+	"time"
+
+	"github.com/go-redis/redis/internal"
+	"github.com/go-redis/redis/internal/pool"
+	"github.com/go-redis/redis/internal/proto"
+)
+
+// Nil reply Redis returns when key does not exist.
+const Nil = proto.Nil
+
+func SetLogger(logger *log.Logger) {
+	internal.Logger = logger
+}
+
+//------------------------------------------------------------------------------
+
+type Hook interface {
+	BeforeProcess(ctx context.Context, cmd Cmder) (context.Context, error)
+	AfterProcess(ctx context.Context, cmd Cmder) error
+
+	BeforeProcessPipeline(ctx context.Context, cmds []Cmder) (context.Context, error)
+	AfterProcessPipeline(ctx context.Context, cmds []Cmder) error
+}
+
+type hooks struct {
+	hooks []Hook
+}
+
+func (hs *hooks) AddHook(hook Hook) {
+	hs.hooks = append(hs.hooks, hook)
+}
+
+func (hs hooks) process(
+	ctx context.Context, cmd Cmder, fn func(context.Context, Cmder) error,
+) error {
+	ctx, err := hs.beforeProcess(ctx, cmd)
+	if err != nil {
+		return err
+	}
+
+	cmdErr := fn(ctx, cmd)
+
+	_, err = hs.afterProcess(ctx, cmd)
+	if err != nil {
+		return err
+	}
+
+	return cmdErr
+}
+
+func (hs hooks) beforeProcess(ctx context.Context, cmd Cmder) (context.Context, error) {
+	for _, h := range hs.hooks {
+		var err error
+		ctx, err = h.BeforeProcess(ctx, cmd)
+		if err != nil {
+			return nil, err
+		}
+	}
+	return ctx, nil
+}
+
+func (hs hooks) afterProcess(ctx context.Context, cmd Cmder) (context.Context, error) {
+	var firstErr error
+	for _, h := range hs.hooks {
+		err := h.AfterProcess(ctx, cmd)
+		if err != nil && firstErr == nil {
+			firstErr = err
+		}
+	}
+	return ctx, firstErr
+}
+
+func (hs hooks) processPipeline(
+	ctx context.Context, cmds []Cmder, fn func(context.Context, []Cmder) error,
+) error {
+	ctx, err := hs.beforeProcessPipeline(ctx, cmds)
+	if err != nil {
+		return err
+	}
+
+	cmdsErr := fn(ctx, cmds)
+
+	_, err = hs.afterProcessPipeline(ctx, cmds)
+	if err != nil {
+		return err
+	}
+
+	return cmdsErr
+}
+
+func (hs hooks) beforeProcessPipeline(ctx context.Context, cmds []Cmder) (context.Context, error) {
+	for _, h := range hs.hooks {
+		var err error
+		ctx, err = h.BeforeProcessPipeline(ctx, cmds)
+		if err != nil {
+			return nil, err
+		}
+	}
+	return ctx, nil
+}
+
+func (hs hooks) afterProcessPipeline(ctx context.Context, cmds []Cmder) (context.Context, error) {
+	var firstErr error
+	for _, h := range hs.hooks {
+		err := h.AfterProcessPipeline(ctx, cmds)
+		if err != nil && firstErr == nil {
+			firstErr = err
+		}
+	}
+	return ctx, firstErr
+}
+
+//------------------------------------------------------------------------------
+
+type baseClient struct {
+	opt      *Options
+	connPool pool.Pooler
+	limiter  Limiter
+
+	onClose func() error // hook called when client is closed
+}
+
+func (c *baseClient) String() string {
+	return fmt.Sprintf("Redis<%s db:%d>", c.getAddr(), c.opt.DB)
+}
+
+func (c *baseClient) newConn(ctx context.Context) (*pool.Conn, error) {
+	cn, err := c.connPool.NewConn(ctx)
+	if err != nil {
+		return nil, err
+	}
+
+	err = c.initConn(ctx, cn)
+	if err != nil {
+		_ = c.connPool.CloseConn(cn)
+		return nil, err
+	}
+
+	return cn, nil
+}
+
+func (c *baseClient) getConn(ctx context.Context) (*pool.Conn, error) {
+	if c.limiter != nil {
+		err := c.limiter.Allow()
+		if err != nil {
+			return nil, err
+		}
+	}
+
+	cn, err := c._getConn(ctx)
+	if err != nil {
+		if c.limiter != nil {
+			c.limiter.ReportResult(err)
+		}
+		return nil, err
+	}
+	return cn, nil
+}
+
+func (c *baseClient) _getConn(ctx context.Context) (*pool.Conn, error) {
+	cn, err := c.connPool.Get(ctx)
+	if err != nil {
+		return nil, err
+	}
+
+	err = c.initConn(ctx, cn)
+	if err != nil {
+		c.connPool.Remove(cn)
+		return nil, err
+	}
+
+	return cn, nil
+}
+
+func (c *baseClient) releaseConn(cn *pool.Conn, err error) {
+	if c.limiter != nil {
+		c.limiter.ReportResult(err)
+	}
+
+	if internal.IsBadConn(err, false) {
+		c.connPool.Remove(cn)
+	} else {
+		c.connPool.Put(cn)
+	}
+}
+
+func (c *baseClient) releaseConnStrict(cn *pool.Conn, err error) {
+	if c.limiter != nil {
+		c.limiter.ReportResult(err)
+	}
+
+	if err == nil || internal.IsRedisError(err) {
+		c.connPool.Put(cn)
+	} else {
+		c.connPool.Remove(cn)
+	}
+}
+
+func (c *baseClient) initConn(ctx context.Context, cn *pool.Conn) error {
+	if cn.Inited {
+		return nil
+	}
+	cn.Inited = true
+
+	if c.opt.Password == "" &&
+		c.opt.DB == 0 &&
+		!c.opt.readOnly &&
+		c.opt.OnConnect == nil {
+		return nil
+	}
+
+	conn := newConn(ctx, c.opt, cn)
+	_, err := conn.Pipelined(func(pipe Pipeliner) error {
+		if c.opt.Password != "" {
+			pipe.Auth(c.opt.Password)
+		}
+
+		if c.opt.DB > 0 {
+			pipe.Select(c.opt.DB)
+		}
+
+		if c.opt.readOnly {
+			pipe.ReadOnly()
+		}
+
+		return nil
+	})
+	if err != nil {
+		return err
+	}
+
+	if c.opt.OnConnect != nil {
+		return c.opt.OnConnect(conn)
+	}
+	return nil
+}
+
+func (c *baseClient) process(ctx context.Context, cmd Cmder) error {
+	for attempt := 0; attempt <= c.opt.MaxRetries; attempt++ {
+		if attempt > 0 {
+			time.Sleep(c.retryBackoff(attempt))
+		}
+
+		cn, err := c.getConn(ctx)
+		if err != nil {
+			cmd.setErr(err)
+			if internal.IsRetryableError(err, true) {
+				continue
+			}
+			return err
+		}
+
+		err = cn.WithWriter(ctx, c.opt.WriteTimeout, func(wr *proto.Writer) error {
+			return writeCmd(wr, cmd)
+		})
+		if err != nil {
+			c.releaseConn(cn, err)
+			cmd.setErr(err)
+			if internal.IsRetryableError(err, true) {
+				continue
+			}
+			return err
+		}
+
+		err = cn.WithReader(ctx, c.cmdTimeout(cmd), cmd.readReply)
+		c.releaseConn(cn, err)
+		if err != nil && internal.IsRetryableError(err, cmd.readTimeout() == nil) {
+			continue
+		}
+
+		return err
+	}
+
+	return cmd.Err()
+}
+
+func (c *baseClient) retryBackoff(attempt int) time.Duration {
+	return internal.RetryBackoff(attempt, c.opt.MinRetryBackoff, c.opt.MaxRetryBackoff)
+}
+
+func (c *baseClient) cmdTimeout(cmd Cmder) time.Duration {
+	if timeout := cmd.readTimeout(); timeout != nil {
+		t := *timeout
+		if t == 0 {
+			return 0
+		}
+		return t + 10*time.Second
+	}
+	return c.opt.ReadTimeout
+}
+
+// Close closes the client, releasing any open resources.
+//
+// It is rare to Close a Client, as the Client is meant to be
+// long-lived and shared between many goroutines.
+func (c *baseClient) Close() error {
+	var firstErr error
+	if c.onClose != nil {
+		if err := c.onClose(); err != nil {
+			firstErr = err
+		}
+	}
+	if err := c.connPool.Close(); err != nil && firstErr == nil {
+		firstErr = err
+	}
+	return firstErr
+}
+
+func (c *baseClient) getAddr() string {
+	return c.opt.Addr
+}
+
+func (c *baseClient) processPipeline(ctx context.Context, cmds []Cmder) error {
+	return c.generalProcessPipeline(ctx, cmds, c.pipelineProcessCmds)
+}
+
+func (c *baseClient) processTxPipeline(ctx context.Context, cmds []Cmder) error {
+	return c.generalProcessPipeline(ctx, cmds, c.txPipelineProcessCmds)
+}
+
+type pipelineProcessor func(context.Context, *pool.Conn, []Cmder) (bool, error)
+
+func (c *baseClient) generalProcessPipeline(
+	ctx context.Context, cmds []Cmder, p pipelineProcessor,
+) error {
+	for attempt := 0; attempt <= c.opt.MaxRetries; attempt++ {
+		if attempt > 0 {
+			time.Sleep(c.retryBackoff(attempt))
+		}
+
+		cn, err := c.getConn(ctx)
+		if err != nil {
+			setCmdsErr(cmds, err)
+			return err
+		}
+
+		canRetry, err := p(ctx, cn, cmds)
+		c.releaseConnStrict(cn, err)
+
+		if !canRetry || !internal.IsRetryableError(err, true) {
+			break
+		}
+	}
+	return cmdsFirstErr(cmds)
+}
+
+func (c *baseClient) pipelineProcessCmds(
+	ctx context.Context, cn *pool.Conn, cmds []Cmder,
+) (bool, error) {
+	err := cn.WithWriter(ctx, c.opt.WriteTimeout, func(wr *proto.Writer) error {
+		return writeCmd(wr, cmds...)
+	})
+	if err != nil {
+		setCmdsErr(cmds, err)
+		return true, err
+	}
+
+	err = cn.WithReader(ctx, c.opt.ReadTimeout, func(rd *proto.Reader) error {
+		return pipelineReadCmds(rd, cmds)
+	})
+	return true, err
+}
+
+func pipelineReadCmds(rd *proto.Reader, cmds []Cmder) error {
+	for _, cmd := range cmds {
+		err := cmd.readReply(rd)
+		if err != nil && !internal.IsRedisError(err) {
+			return err
+		}
+	}
+	return nil
+}
+
+func (c *baseClient) txPipelineProcessCmds(
+	ctx context.Context, cn *pool.Conn, cmds []Cmder,
+) (bool, error) {
+	err := cn.WithWriter(ctx, c.opt.WriteTimeout, func(wr *proto.Writer) error {
+		return txPipelineWriteMulti(wr, cmds)
+	})
+	if err != nil {
+		setCmdsErr(cmds, err)
+		return true, err
+	}
+
+	err = cn.WithReader(ctx, c.opt.ReadTimeout, func(rd *proto.Reader) error {
+		err := txPipelineReadQueued(rd, cmds)
+		if err != nil {
+			setCmdsErr(cmds, err)
+			return err
+		}
+		return pipelineReadCmds(rd, cmds)
+	})
+	return false, err
+}
+
+func txPipelineWriteMulti(wr *proto.Writer, 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(wr, multiExec...)
+}
+
+func txPipelineReadQueued(rd *proto.Reader, cmds []Cmder) error {
+	// Parse queued replies.
+	var statusCmd StatusCmd
+	err := statusCmd.readReply(rd)
+	if err != nil {
+		return err
+	}
+
+	for range cmds {
+		err = statusCmd.readReply(rd)
+		if err != nil && !internal.IsRedisError(err) {
+			return err
+		}
+	}
+
+	// Parse number of replies.
+	line, err := 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
+}
+
+//------------------------------------------------------------------------------
+
+type client struct {
+	baseClient
+	cmdable
+	hooks
+}
+
+// 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 {
+	*client
+	ctx context.Context
+}
+
+// NewClient returns a client to the Redis Server specified by Options.
+func NewClient(opt *Options) *Client {
+	opt.init()
+
+	c := Client{
+		client: &client{
+			baseClient: baseClient{
+				opt:      opt,
+				connPool: newConnPool(opt),
+			},
+		},
+		ctx: context.Background(),
+	}
+	c.init()
+
+	return &c
+}
+
+func (c *Client) init() {
+	c.cmdable = c.Process
+}
+
+func (c *Client) Context() context.Context {
+	return c.ctx
+}
+
+func (c *Client) WithContext(ctx context.Context) *Client {
+	if ctx == nil {
+		panic("nil context")
+	}
+	clone := *c
+	clone.ctx = ctx
+	clone.init()
+	return &clone
+}
+
+// Do creates a Cmd from the args and processes the cmd.
+func (c *Client) Do(args ...interface{}) *Cmd {
+	return c.DoContext(c.ctx, args...)
+}
+
+func (c *Client) DoContext(ctx context.Context, args ...interface{}) *Cmd {
+	cmd := NewCmd(args...)
+	_ = c.ProcessContext(ctx, cmd)
+	return cmd
+}
+
+func (c *Client) Process(cmd Cmder) error {
+	return c.ProcessContext(c.ctx, cmd)
+}
+
+func (c *Client) ProcessContext(ctx context.Context, cmd Cmder) error {
+	return c.hooks.process(ctx, cmd, c.baseClient.process)
+}
+
+func (c *Client) processPipeline(ctx context.Context, cmds []Cmder) error {
+	return c.hooks.processPipeline(ctx, cmds, c.baseClient.processPipeline)
+}
+
+func (c *Client) processTxPipeline(ctx context.Context, cmds []Cmder) error {
+	return c.hooks.processPipeline(ctx, cmds, c.baseClient.processTxPipeline)
+}
+
+// Options returns read-only Options that were used to create the client.
+func (c *Client) Options() *Options {
+	return c.opt
+}
+
+func (c *Client) SetLimiter(l Limiter) *Client {
+	c.limiter = l
+	return c
+}
+
+type PoolStats pool.Stats
+
+// PoolStats returns connection pool stats.
+func (c *Client) PoolStats() *PoolStats {
+	stats := c.connPool.Stats()
+	return (*PoolStats)(stats)
+}
+
+func (c *Client) Pipelined(fn func(Pipeliner) error) ([]Cmder, error) {
+	return c.Pipeline().Pipelined(fn)
+}
+
+func (c *Client) Pipeline() Pipeliner {
+	pipe := Pipeline{
+		ctx:  c.ctx,
+		exec: c.processPipeline,
+	}
+	pipe.init()
+	return &pipe
+}
+
+func (c *Client) 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 *Client) TxPipeline() Pipeliner {
+	pipe := Pipeline{
+		ctx:  c.ctx,
+		exec: c.processTxPipeline,
+	}
+	pipe.init()
+	return &pipe
+}
+
+func (c *Client) pubSub() *PubSub {
+	pubsub := &PubSub{
+		opt: c.opt,
+
+		newConn: func(channels []string) (*pool.Conn, error) {
+			return c.newConn(context.TODO())
+		},
+		closeConn: c.connPool.CloseConn,
+	}
+	pubsub.init()
+	return pubsub
+}
+
+// Subscribe subscribes the client to the specified channels.
+// Channels can be omitted to create empty subscription.
+// Note that this method does not wait on a response from Redis, so the
+// subscription may not be active immediately. To force the connection to wait,
+// you may call the Receive() method on the returned *PubSub like so:
+//
+//    sub := client.Subscribe(queryResp)
+//    iface, err := sub.Receive()
+//    if err != nil {
+//        // handle error
+//    }
+//
+//    // Should be *Subscription, but others are possible if other actions have been
+//    // taken on sub since it was created.
+//    switch iface.(type) {
+//    case *Subscription:
+//        // subscribe succeeded
+//    case *Message:
+//        // received first message
+//    case *Pong:
+//        // pong received
+//    default:
+//        // handle error
+//    }
+//
+//    ch := sub.Channel()
+func (c *Client) Subscribe(channels ...string) *PubSub {
+	pubsub := c.pubSub()
+	if len(channels) > 0 {
+		_ = pubsub.Subscribe(channels...)
+	}
+	return pubsub
+}
+
+// PSubscribe subscribes the client to the given patterns.
+// Patterns can be omitted to create empty subscription.
+func (c *Client) PSubscribe(channels ...string) *PubSub {
+	pubsub := c.pubSub()
+	if len(channels) > 0 {
+		_ = pubsub.PSubscribe(channels...)
+	}
+	return pubsub
+}
+
+//------------------------------------------------------------------------------
+
+type conn struct {
+	baseClient
+	cmdable
+	statefulCmdable
+}
+
+// Conn is like Client, but its pool contains single connection.
+type Conn struct {
+	*conn
+	ctx context.Context
+}
+
+func newConn(ctx context.Context, opt *Options, cn *pool.Conn) *Conn {
+	c := Conn{
+		conn: &conn{
+			baseClient: baseClient{
+				opt:      opt,
+				connPool: pool.NewSingleConnPool(cn),
+			},
+		},
+		ctx: ctx,
+	}
+	c.cmdable = c.Process
+	c.statefulCmdable = c.Process
+	return &c
+}
+
+func (c *Conn) Process(cmd Cmder) error {
+	return c.ProcessContext(c.ctx, cmd)
+}
+
+func (c *Conn) ProcessContext(ctx context.Context, cmd Cmder) error {
+	return c.baseClient.process(ctx, cmd)
+}
+
+func (c *Conn) Pipelined(fn func(Pipeliner) error) ([]Cmder, error) {
+	return c.Pipeline().Pipelined(fn)
+}
+
+func (c *Conn) Pipeline() Pipeliner {
+	pipe := Pipeline{
+		ctx:  c.ctx,
+		exec: c.processPipeline,
+	}
+	pipe.init()
+	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{
+		ctx:  c.ctx,
+		exec: c.processTxPipeline,
+	}
+	pipe.init()
+	return &pipe
+}

+ 344 - 0
go/gopath/src/github.com/go-redis/redis/redis_test.go

@@ -0,0 +1,344 @@
+package redis_test
+
+import (
+	"bytes"
+	"context"
+	"net"
+	"time"
+
+	"github.com/go-redis/redis"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("Client", func() {
+	var client *redis.Client
+
+	BeforeEach(func() {
+		client = redis.NewClient(redisOptions())
+		Expect(client.FlushDB().Err()).NotTo(HaveOccurred())
+	})
+
+	AfterEach(func() {
+		client.Close()
+	})
+
+	It("supports WithContext", func() {
+		c, cancel := context.WithCancel(context.Background())
+		cancel()
+
+		err := client.WithContext(c).Ping().Err()
+		Expect(err).To(MatchError("context canceled"))
+	})
+
+	It("should Stringer", func() {
+		Expect(client.String()).To(Equal("Redis<:6380 db:15>"))
+	})
+
+	It("should ping", func() {
+		val, err := client.Ping().Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(val).To(Equal("PONG"))
+	})
+
+	It("should return pool stats", func() {
+		Expect(client.PoolStats()).To(BeAssignableToTypeOf(&redis.PoolStats{}))
+	})
+
+	It("should support custom dialers", func() {
+		custom := redis.NewClient(&redis.Options{
+			Network: "tcp",
+			Addr:    redisAddr,
+			Dialer: func(ctx context.Context, network, addr string) (net.Conn, error) {
+				return net.Dial(network, addr)
+			},
+		})
+
+		val, err := custom.Ping().Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(val).To(Equal("PONG"))
+		Expect(custom.Close()).NotTo(HaveOccurred())
+	})
+
+	It("should close", func() {
+		Expect(client.Close()).NotTo(HaveOccurred())
+		err := client.Ping().Err()
+		Expect(err).To(MatchError("redis: client is closed"))
+	})
+
+	It("should close pubsub without closing the client", func() {
+		pubsub := client.Subscribe()
+		Expect(pubsub.Close()).NotTo(HaveOccurred())
+
+		_, err := pubsub.Receive()
+		Expect(err).To(MatchError("redis: client is closed"))
+		Expect(client.Ping().Err()).NotTo(HaveOccurred())
+	})
+
+	It("should close Tx without closing the client", func() {
+		err := client.Watch(func(tx *redis.Tx) error {
+			_, err := tx.Pipelined(func(pipe redis.Pipeliner) error {
+				pipe.Ping()
+				return nil
+			})
+			return err
+		})
+		Expect(err).NotTo(HaveOccurred())
+
+		Expect(client.Ping().Err()).NotTo(HaveOccurred())
+	})
+
+	It("should close pipeline without closing the client", func() {
+		pipeline := client.Pipeline()
+		Expect(pipeline.Close()).NotTo(HaveOccurred())
+
+		pipeline.Ping()
+		_, err := pipeline.Exec()
+		Expect(err).To(MatchError("redis: client is closed"))
+
+		Expect(client.Ping().Err()).NotTo(HaveOccurred())
+	})
+
+	It("should close pubsub when client is closed", func() {
+		pubsub := client.Subscribe()
+		Expect(client.Close()).NotTo(HaveOccurred())
+
+		_, err := pubsub.Receive()
+		Expect(err).To(MatchError("redis: client is closed"))
+
+		Expect(pubsub.Close()).NotTo(HaveOccurred())
+	})
+
+	It("should close pipeline when client is closed", func() {
+		pipeline := client.Pipeline()
+		Expect(client.Close()).NotTo(HaveOccurred())
+		Expect(pipeline.Close()).NotTo(HaveOccurred())
+	})
+
+	It("should select DB", func() {
+		db2 := redis.NewClient(&redis.Options{
+			Addr: redisAddr,
+			DB:   2,
+		})
+		Expect(db2.FlushDB().Err()).NotTo(HaveOccurred())
+		Expect(db2.Get("db").Err()).To(Equal(redis.Nil))
+		Expect(db2.Set("db", 2, 0).Err()).NotTo(HaveOccurred())
+
+		n, err := db2.Get("db").Int64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(n).To(Equal(int64(2)))
+
+		Expect(client.Get("db").Err()).To(Equal(redis.Nil))
+
+		Expect(db2.FlushDB().Err()).NotTo(HaveOccurred())
+		Expect(db2.Close()).NotTo(HaveOccurred())
+	})
+
+	It("processes custom commands", func() {
+		cmd := redis.NewCmd("PING")
+		_ = client.Process(cmd)
+
+		// Flush buffers.
+		Expect(client.Echo("hello").Err()).NotTo(HaveOccurred())
+
+		Expect(cmd.Err()).NotTo(HaveOccurred())
+		Expect(cmd.Val()).To(Equal("PONG"))
+	})
+
+	It("should retry command on network error", func() {
+		Expect(client.Close()).NotTo(HaveOccurred())
+
+		client = redis.NewClient(&redis.Options{
+			Addr:       redisAddr,
+			MaxRetries: 1,
+		})
+
+		// Put bad connection in the pool.
+		cn, err := client.Pool().Get(context.Background())
+		Expect(err).NotTo(HaveOccurred())
+
+		cn.SetNetConn(&badConn{})
+		client.Pool().Put(cn)
+
+		err = client.Ping().Err()
+		Expect(err).NotTo(HaveOccurred())
+	})
+
+	It("should retry with backoff", func() {
+		clientNoRetry := redis.NewClient(&redis.Options{
+			Addr:       ":1234",
+			MaxRetries: 0,
+		})
+		defer clientNoRetry.Close()
+
+		clientRetry := redis.NewClient(&redis.Options{
+			Addr:            ":1234",
+			MaxRetries:      5,
+			MaxRetryBackoff: 128 * time.Millisecond,
+		})
+		defer clientRetry.Close()
+
+		startNoRetry := time.Now()
+		err := clientNoRetry.Ping().Err()
+		Expect(err).To(HaveOccurred())
+		elapseNoRetry := time.Since(startNoRetry)
+
+		startRetry := time.Now()
+		err = clientRetry.Ping().Err()
+		Expect(err).To(HaveOccurred())
+		elapseRetry := time.Since(startRetry)
+
+		Expect(elapseRetry).To(BeNumerically(">", elapseNoRetry, 10*time.Millisecond))
+	})
+
+	It("should update conn.UsedAt on read/write", func() {
+		cn, err := client.Pool().Get(context.Background())
+		Expect(err).NotTo(HaveOccurred())
+		Expect(cn.UsedAt).NotTo(BeZero())
+		createdAt := cn.UsedAt()
+
+		client.Pool().Put(cn)
+		Expect(cn.UsedAt().Equal(createdAt)).To(BeTrue())
+
+		time.Sleep(time.Second)
+
+		err = client.Ping().Err()
+		Expect(err).NotTo(HaveOccurred())
+
+		cn, err = client.Pool().Get(context.Background())
+		Expect(err).NotTo(HaveOccurred())
+		Expect(cn).NotTo(BeNil())
+		Expect(cn.UsedAt().After(createdAt)).To(BeTrue())
+	})
+
+	It("should process command with special chars", func() {
+		set := client.Set("key", "hello1\r\nhello2\r\n", 0)
+		Expect(set.Err()).NotTo(HaveOccurred())
+		Expect(set.Val()).To(Equal("OK"))
+
+		get := client.Get("key")
+		Expect(get.Err()).NotTo(HaveOccurred())
+		Expect(get.Val()).To(Equal("hello1\r\nhello2\r\n"))
+	})
+
+	It("should handle big vals", func() {
+		bigVal := bytes.Repeat([]byte{'*'}, 2e6)
+
+		err := client.Set("key", bigVal, 0).Err()
+		Expect(err).NotTo(HaveOccurred())
+
+		// Reconnect to get new connection.
+		Expect(client.Close()).NotTo(HaveOccurred())
+		client = redis.NewClient(redisOptions())
+
+		got, err := client.Get("key").Bytes()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(got).To(Equal(bigVal))
+	})
+})
+
+var _ = Describe("Client timeout", func() {
+	var opt *redis.Options
+	var client *redis.Client
+
+	AfterEach(func() {
+		Expect(client.Close()).NotTo(HaveOccurred())
+	})
+
+	testTimeout := func() {
+		It("Ping timeouts", func() {
+			err := client.Ping().Err()
+			Expect(err).To(HaveOccurred())
+			Expect(err.(net.Error).Timeout()).To(BeTrue())
+		})
+
+		It("Pipeline timeouts", func() {
+			_, err := client.Pipelined(func(pipe redis.Pipeliner) error {
+				pipe.Ping()
+				return nil
+			})
+			Expect(err).To(HaveOccurred())
+			Expect(err.(net.Error).Timeout()).To(BeTrue())
+		})
+
+		It("Subscribe timeouts", func() {
+			if opt.WriteTimeout == 0 {
+				return
+			}
+
+			pubsub := client.Subscribe()
+			defer pubsub.Close()
+
+			err := pubsub.Subscribe("_")
+			Expect(err).To(HaveOccurred())
+			Expect(err.(net.Error).Timeout()).To(BeTrue())
+		})
+
+		It("Tx timeouts", func() {
+			err := client.Watch(func(tx *redis.Tx) error {
+				return tx.Ping().Err()
+			})
+			Expect(err).To(HaveOccurred())
+			Expect(err.(net.Error).Timeout()).To(BeTrue())
+		})
+
+		It("Tx Pipeline timeouts", func() {
+			err := client.Watch(func(tx *redis.Tx) error {
+				_, err := tx.Pipelined(func(pipe redis.Pipeliner) error {
+					pipe.Ping()
+					return nil
+				})
+				return err
+			})
+			Expect(err).To(HaveOccurred())
+			Expect(err.(net.Error).Timeout()).To(BeTrue())
+		})
+	}
+
+	Context("read timeout", func() {
+		BeforeEach(func() {
+			opt = redisOptions()
+			opt.ReadTimeout = time.Nanosecond
+			opt.WriteTimeout = -1
+			client = redis.NewClient(opt)
+		})
+
+		testTimeout()
+	})
+
+	Context("write timeout", func() {
+		BeforeEach(func() {
+			opt = redisOptions()
+			opt.ReadTimeout = -1
+			opt.WriteTimeout = time.Nanosecond
+			client = redis.NewClient(opt)
+		})
+
+		testTimeout()
+	})
+})
+
+var _ = Describe("Client OnConnect", func() {
+	var client *redis.Client
+
+	BeforeEach(func() {
+		opt := redisOptions()
+		opt.DB = 0
+		opt.OnConnect = func(cn *redis.Conn) error {
+			return cn.ClientSetName("on_connect").Err()
+		}
+
+		client = redis.NewClient(opt)
+	})
+
+	AfterEach(func() {
+		Expect(client.Close()).NotTo(HaveOccurred())
+	})
+
+	It("calls OnConnect", func() {
+		name, err := client.ClientGetName().Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(name).To(Equal("on_connect"))
+	})
+})

+ 148 - 0
go/gopath/src/github.com/go-redis/redis/result.go

@@ -0,0 +1,148 @@
+package redis
+
+import "time"
+
+// NewCmdResult returns a Cmd initialised with val and err for testing
+func NewCmdResult(val interface{}, err error) *Cmd {
+	var cmd Cmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewSliceResult returns a SliceCmd initialised with val and err for testing
+func NewSliceResult(val []interface{}, err error) *SliceCmd {
+	var cmd SliceCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewStatusResult returns a StatusCmd initialised with val and err for testing
+func NewStatusResult(val string, err error) *StatusCmd {
+	var cmd StatusCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewIntResult returns an IntCmd initialised with val and err for testing
+func NewIntResult(val int64, err error) *IntCmd {
+	var cmd IntCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewDurationResult returns a DurationCmd initialised with val and err for testing
+func NewDurationResult(val time.Duration, err error) *DurationCmd {
+	var cmd DurationCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewBoolResult returns a BoolCmd initialised with val and err for testing
+func NewBoolResult(val bool, err error) *BoolCmd {
+	var cmd BoolCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewStringResult returns a StringCmd initialised with val and err for testing
+func NewStringResult(val string, err error) *StringCmd {
+	var cmd StringCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewFloatResult returns a FloatCmd initialised with val and err for testing
+func NewFloatResult(val float64, err error) *FloatCmd {
+	var cmd FloatCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewStringSliceResult returns a StringSliceCmd initialised with val and err for testing
+func NewStringSliceResult(val []string, err error) *StringSliceCmd {
+	var cmd StringSliceCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewBoolSliceResult returns a BoolSliceCmd initialised with val and err for testing
+func NewBoolSliceResult(val []bool, err error) *BoolSliceCmd {
+	var cmd BoolSliceCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewStringStringMapResult returns a StringStringMapCmd initialised with val and err for testing
+func NewStringStringMapResult(val map[string]string, err error) *StringStringMapCmd {
+	var cmd StringStringMapCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewStringIntMapCmdResult returns a StringIntMapCmd initialised with val and err for testing
+func NewStringIntMapCmdResult(val map[string]int64, err error) *StringIntMapCmd {
+	var cmd StringIntMapCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewZSliceCmdResult returns a ZSliceCmd initialised with val and err for testing
+func NewZSliceCmdResult(val []Z, err error) *ZSliceCmd {
+	var cmd ZSliceCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewZWithKeyCmdResult returns a NewZWithKeyCmd initialised with val and err for testing
+func NewZWithKeyCmdResult(val *ZWithKey, err error) *ZWithKeyCmd {
+	var cmd ZWithKeyCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewScanCmdResult returns a ScanCmd initialised with val and err for testing
+func NewScanCmdResult(keys []string, cursor uint64, err error) *ScanCmd {
+	var cmd ScanCmd
+	cmd.page = keys
+	cmd.cursor = cursor
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewClusterSlotsCmdResult returns a ClusterSlotsCmd initialised with val and err for testing
+func NewClusterSlotsCmdResult(val []ClusterSlot, err error) *ClusterSlotsCmd {
+	var cmd ClusterSlotsCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewGeoLocationCmdResult returns a GeoLocationCmd initialised with val and err for testing
+func NewGeoLocationCmdResult(val []GeoLocation, err error) *GeoLocationCmd {
+	var cmd GeoLocationCmd
+	cmd.locations = val
+	cmd.setErr(err)
+	return &cmd
+}
+
+// NewCommandsInfoCmdResult returns a CommandsInfoCmd initialised with val and err for testing
+func NewCommandsInfoCmdResult(val map[string]*CommandInfo, err error) *CommandsInfoCmd {
+	var cmd CommandsInfoCmd
+	cmd.val = val
+	cmd.setErr(err)
+	return &cmd
+}

+ 725 - 0
go/gopath/src/github.com/go-redis/redis/ring.go

@@ -0,0 +1,725 @@
+package redis
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"math/rand"
+	"strconv"
+	"sync"
+	"sync/atomic"
+	"time"
+
+	"github.com/go-redis/redis/internal"
+	"github.com/go-redis/redis/internal/consistenthash"
+	"github.com/go-redis/redis/internal/hashtag"
+	"github.com/go-redis/redis/internal/pool"
+)
+
+// Hash is type of hash function used in consistent hash.
+type Hash consistenthash.Hash
+
+var errRingShardsDown = errors.New("redis: all ring shards are down")
+
+// RingOptions are used to configure a ring client and should be
+// passed to NewRing.
+type RingOptions struct {
+	// Map of name => host:port addresses of ring shards.
+	Addrs map[string]string
+
+	// Map of name => password of ring shards, to allow different shards to have
+	// different passwords. It will be ignored if the Password field is set.
+	Passwords map[string]string
+
+	// Frequency of PING commands sent to check shards availability.
+	// Shard is considered down after 3 subsequent failed checks.
+	HeartbeatFrequency time.Duration
+
+	// Hash function used in consistent hash.
+	// Default is crc32.ChecksumIEEE.
+	Hash Hash
+
+	// Number of replicas in consistent hash.
+	// Default is 100 replicas.
+	//
+	// Higher number of replicas will provide less deviation, that is keys will be
+	// distributed to nodes more evenly.
+	//
+	// Following is deviation for common nreplicas:
+	//  --------------------------------------------------------
+	//  | nreplicas | standard error | 99% confidence interval |
+	//  |     10    |     0.3152     |      (0.37, 1.98)       |
+	//  |    100    |     0.0997     |      (0.76, 1.28)       |
+	//  |   1000    |     0.0316     |      (0.92, 1.09)       |
+	//  --------------------------------------------------------
+	//
+	//  See https://arxiv.org/abs/1406.2294 for reference
+	HashReplicas int
+
+	// Following options are copied from Options struct.
+
+	OnConnect func(*Conn) error
+
+	DB       int
+	Password string
+
+	MaxRetries      int
+	MinRetryBackoff time.Duration
+	MaxRetryBackoff time.Duration
+
+	DialTimeout  time.Duration
+	ReadTimeout  time.Duration
+	WriteTimeout time.Duration
+
+	PoolSize           int
+	MinIdleConns       int
+	MaxConnAge         time.Duration
+	PoolTimeout        time.Duration
+	IdleTimeout        time.Duration
+	IdleCheckFrequency time.Duration
+}
+
+func (opt *RingOptions) init() {
+	if opt.HeartbeatFrequency == 0 {
+		opt.HeartbeatFrequency = 500 * time.Millisecond
+	}
+
+	if opt.HashReplicas == 0 {
+		opt.HashReplicas = 100
+	}
+
+	switch opt.MinRetryBackoff {
+	case -1:
+		opt.MinRetryBackoff = 0
+	case 0:
+		opt.MinRetryBackoff = 8 * time.Millisecond
+	}
+	switch opt.MaxRetryBackoff {
+	case -1:
+		opt.MaxRetryBackoff = 0
+	case 0:
+		opt.MaxRetryBackoff = 512 * time.Millisecond
+	}
+}
+
+func (opt *RingOptions) clientOptions(shard string) *Options {
+	return &Options{
+		OnConnect: opt.OnConnect,
+
+		DB:       opt.DB,
+		Password: opt.getPassword(shard),
+
+		DialTimeout:  opt.DialTimeout,
+		ReadTimeout:  opt.ReadTimeout,
+		WriteTimeout: opt.WriteTimeout,
+
+		PoolSize:           opt.PoolSize,
+		MinIdleConns:       opt.MinIdleConns,
+		MaxConnAge:         opt.MaxConnAge,
+		PoolTimeout:        opt.PoolTimeout,
+		IdleTimeout:        opt.IdleTimeout,
+		IdleCheckFrequency: opt.IdleCheckFrequency,
+	}
+}
+
+func (opt *RingOptions) getPassword(shard string) string {
+	if opt.Password == "" {
+		return opt.Passwords[shard]
+	}
+	return opt.Password
+}
+
+//------------------------------------------------------------------------------
+
+type ringShard struct {
+	Client *Client
+	down   int32
+}
+
+func (shard *ringShard) String() string {
+	var state string
+	if shard.IsUp() {
+		state = "up"
+	} else {
+		state = "down"
+	}
+	return fmt.Sprintf("%s is %s", shard.Client, state)
+}
+
+func (shard *ringShard) IsDown() bool {
+	const threshold = 3
+	return atomic.LoadInt32(&shard.down) >= threshold
+}
+
+func (shard *ringShard) IsUp() bool {
+	return !shard.IsDown()
+}
+
+// Vote votes to set shard state and returns true if state was changed.
+func (shard *ringShard) Vote(up bool) bool {
+	if up {
+		changed := shard.IsDown()
+		atomic.StoreInt32(&shard.down, 0)
+		return changed
+	}
+
+	if shard.IsDown() {
+		return false
+	}
+
+	atomic.AddInt32(&shard.down, 1)
+	return shard.IsDown()
+}
+
+//------------------------------------------------------------------------------
+
+type ringShards struct {
+	opt *RingOptions
+
+	mu     sync.RWMutex
+	hash   *consistenthash.Map
+	shards map[string]*ringShard // read only
+	list   []*ringShard          // read only
+	len    int
+	closed bool
+}
+
+func newRingShards(opt *RingOptions) *ringShards {
+	return &ringShards{
+		opt: opt,
+
+		hash:   newConsistentHash(opt),
+		shards: make(map[string]*ringShard),
+	}
+}
+
+func (c *ringShards) Add(name string, cl *Client) {
+	shard := &ringShard{Client: cl}
+	c.hash.Add(name)
+	c.shards[name] = shard
+	c.list = append(c.list, shard)
+}
+
+func (c *ringShards) List() []*ringShard {
+	c.mu.RLock()
+	list := c.list
+	c.mu.RUnlock()
+	return list
+}
+
+func (c *ringShards) Hash(key string) string {
+	c.mu.RLock()
+	hash := c.hash.Get(key)
+	c.mu.RUnlock()
+	return hash
+}
+
+func (c *ringShards) GetByKey(key string) (*ringShard, error) {
+	key = hashtag.Key(key)
+
+	c.mu.RLock()
+
+	if c.closed {
+		c.mu.RUnlock()
+		return nil, pool.ErrClosed
+	}
+
+	hash := c.hash.Get(key)
+	if hash == "" {
+		c.mu.RUnlock()
+		return nil, errRingShardsDown
+	}
+
+	shard := c.shards[hash]
+	c.mu.RUnlock()
+
+	return shard, nil
+}
+
+func (c *ringShards) GetByHash(name string) (*ringShard, error) {
+	if name == "" {
+		return c.Random()
+	}
+
+	c.mu.RLock()
+	shard := c.shards[name]
+	c.mu.RUnlock()
+	return shard, nil
+}
+
+func (c *ringShards) Random() (*ringShard, error) {
+	return c.GetByKey(strconv.Itoa(rand.Int()))
+}
+
+// heartbeat monitors state of each shard in the ring.
+func (c *ringShards) Heartbeat(frequency time.Duration) {
+	ticker := time.NewTicker(frequency)
+	defer ticker.Stop()
+	for range ticker.C {
+		var rebalance bool
+
+		c.mu.RLock()
+
+		if c.closed {
+			c.mu.RUnlock()
+			break
+		}
+
+		shards := c.list
+		c.mu.RUnlock()
+
+		for _, shard := range shards {
+			err := shard.Client.Ping().Err()
+			if shard.Vote(err == nil || err == pool.ErrPoolTimeout) {
+				internal.Logger.Printf("ring shard state changed: %s", shard)
+				rebalance = true
+			}
+		}
+
+		if rebalance {
+			c.rebalance()
+		}
+	}
+}
+
+// rebalance removes dead shards from the Ring.
+func (c *ringShards) rebalance() {
+	c.mu.RLock()
+	shards := c.shards
+	c.mu.RUnlock()
+
+	hash := newConsistentHash(c.opt)
+	var shardsNum int
+	for name, shard := range shards {
+		if shard.IsUp() {
+			hash.Add(name)
+			shardsNum++
+		}
+	}
+
+	c.mu.Lock()
+	c.hash = hash
+	c.len = shardsNum
+	c.mu.Unlock()
+}
+
+func (c *ringShards) Len() int {
+	c.mu.RLock()
+	l := c.len
+	c.mu.RUnlock()
+	return l
+}
+
+func (c *ringShards) Close() error {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	if c.closed {
+		return nil
+	}
+	c.closed = true
+
+	var firstErr error
+	for _, shard := range c.shards {
+		if err := shard.Client.Close(); err != nil && firstErr == nil {
+			firstErr = err
+		}
+	}
+	c.hash = nil
+	c.shards = nil
+	c.list = nil
+
+	return firstErr
+}
+
+//------------------------------------------------------------------------------
+
+type ring struct {
+	cmdable
+	hooks
+	opt           *RingOptions
+	shards        *ringShards
+	cmdsInfoCache *cmdsInfoCache //nolint:structcheck
+}
+
+// Ring is a Redis client that uses consistent hashing to distribute
+// keys across multiple Redis servers (shards). It's safe for
+// concurrent use by multiple goroutines.
+//
+// Ring monitors the state of each shard and removes dead shards from
+// the ring. When a shard comes online it is added back to the ring. This
+// gives you maximum availability and partition tolerance, but no
+// consistency between different shards or even clients. Each client
+// uses shards that are available to the client and does not do any
+// coordination when shard state is changed.
+//
+// Ring should be used when you need multiple Redis servers for caching
+// and can tolerate losing data when one of the servers dies.
+// Otherwise you should use Redis Cluster.
+type Ring struct {
+	*ring
+	ctx context.Context
+}
+
+func NewRing(opt *RingOptions) *Ring {
+	opt.init()
+
+	ring := Ring{
+		ring: &ring{
+			opt:    opt,
+			shards: newRingShards(opt),
+		},
+		ctx: context.Background(),
+	}
+	ring.init()
+
+	ring.cmdsInfoCache = newCmdsInfoCache(ring.cmdsInfo)
+
+	for name, addr := range opt.Addrs {
+		clopt := opt.clientOptions(name)
+		clopt.Addr = addr
+		ring.shards.Add(name, NewClient(clopt))
+	}
+
+	go ring.shards.Heartbeat(opt.HeartbeatFrequency)
+
+	return &ring
+}
+
+func (c *Ring) init() {
+	c.cmdable = c.Process
+}
+
+func (c *Ring) Context() context.Context {
+	return c.ctx
+}
+
+func (c *Ring) WithContext(ctx context.Context) *Ring {
+	if ctx == nil {
+		panic("nil context")
+	}
+	clone := *c
+	clone.ctx = ctx
+	clone.init()
+	return &clone
+}
+
+// Do creates a Cmd from the args and processes the cmd.
+func (c *Ring) Do(args ...interface{}) *Cmd {
+	return c.DoContext(c.ctx, args...)
+}
+
+func (c *Ring) DoContext(ctx context.Context, args ...interface{}) *Cmd {
+	cmd := NewCmd(args...)
+	_ = c.ProcessContext(ctx, cmd)
+	return cmd
+}
+
+func (c *Ring) Process(cmd Cmder) error {
+	return c.ProcessContext(c.ctx, cmd)
+}
+
+func (c *Ring) ProcessContext(ctx context.Context, cmd Cmder) error {
+	return c.hooks.process(ctx, cmd, c.process)
+}
+
+// Options returns read-only Options that were used to create the client.
+func (c *Ring) Options() *RingOptions {
+	return c.opt
+}
+
+func (c *Ring) retryBackoff(attempt int) time.Duration {
+	return internal.RetryBackoff(attempt, c.opt.MinRetryBackoff, c.opt.MaxRetryBackoff)
+}
+
+// PoolStats returns accumulated connection pool stats.
+func (c *Ring) PoolStats() *PoolStats {
+	shards := c.shards.List()
+	var acc PoolStats
+	for _, shard := range shards {
+		s := shard.Client.connPool.Stats()
+		acc.Hits += s.Hits
+		acc.Misses += s.Misses
+		acc.Timeouts += s.Timeouts
+		acc.TotalConns += s.TotalConns
+		acc.IdleConns += s.IdleConns
+	}
+	return &acc
+}
+
+// Len returns the current number of shards in the ring.
+func (c *Ring) Len() int {
+	return c.shards.Len()
+}
+
+// Subscribe subscribes the client to the specified channels.
+func (c *Ring) Subscribe(channels ...string) *PubSub {
+	if len(channels) == 0 {
+		panic("at least one channel is required")
+	}
+
+	shard, err := c.shards.GetByKey(channels[0])
+	if err != nil {
+		// TODO: return PubSub with sticky error
+		panic(err)
+	}
+	return shard.Client.Subscribe(channels...)
+}
+
+// PSubscribe subscribes the client to the given patterns.
+func (c *Ring) PSubscribe(channels ...string) *PubSub {
+	if len(channels) == 0 {
+		panic("at least one channel is required")
+	}
+
+	shard, err := c.shards.GetByKey(channels[0])
+	if err != nil {
+		// TODO: return PubSub with sticky error
+		panic(err)
+	}
+	return shard.Client.PSubscribe(channels...)
+}
+
+// ForEachShard concurrently calls the fn on each live shard in the ring.
+// It returns the first error if any.
+func (c *Ring) ForEachShard(fn func(client *Client) error) error {
+	shards := c.shards.List()
+	var wg sync.WaitGroup
+	errCh := make(chan error, 1)
+	for _, shard := range shards {
+		if shard.IsDown() {
+			continue
+		}
+
+		wg.Add(1)
+		go func(shard *ringShard) {
+			defer wg.Done()
+			err := fn(shard.Client)
+			if err != nil {
+				select {
+				case errCh <- err:
+				default:
+				}
+			}
+		}(shard)
+	}
+	wg.Wait()
+
+	select {
+	case err := <-errCh:
+		return err
+	default:
+		return nil
+	}
+}
+
+func (c *Ring) cmdsInfo() (map[string]*CommandInfo, error) {
+	shards := c.shards.List()
+	firstErr := errRingShardsDown
+	for _, shard := range shards {
+		cmdsInfo, err := shard.Client.Command().Result()
+		if err == nil {
+			return cmdsInfo, nil
+		}
+		if firstErr == nil {
+			firstErr = err
+		}
+	}
+	return nil, firstErr
+}
+
+func (c *Ring) cmdInfo(name string) *CommandInfo {
+	cmdsInfo, err := c.cmdsInfoCache.Get()
+	if err != nil {
+		return nil
+	}
+	info := cmdsInfo[name]
+	if info == nil {
+		internal.Logger.Printf("info for cmd=%s not found", name)
+	}
+	return info
+}
+
+func (c *Ring) cmdShard(cmd Cmder) (*ringShard, error) {
+	cmdInfo := c.cmdInfo(cmd.Name())
+	pos := cmdFirstKeyPos(cmd, cmdInfo)
+	if pos == 0 {
+		return c.shards.Random()
+	}
+	firstKey := cmd.stringArg(pos)
+	return c.shards.GetByKey(firstKey)
+}
+
+func (c *Ring) process(ctx context.Context, cmd Cmder) error {
+	for attempt := 0; attempt <= c.opt.MaxRetries; attempt++ {
+		if attempt > 0 {
+			time.Sleep(c.retryBackoff(attempt))
+		}
+
+		shard, err := c.cmdShard(cmd)
+		if err != nil {
+			cmd.setErr(err)
+			return err
+		}
+
+		err = shard.Client.ProcessContext(ctx, cmd)
+		if err == nil {
+			return nil
+		}
+		if !internal.IsRetryableError(err, cmd.readTimeout() == nil) {
+			return err
+		}
+	}
+	return cmd.Err()
+}
+
+func (c *Ring) Pipelined(fn func(Pipeliner) error) ([]Cmder, error) {
+	return c.Pipeline().Pipelined(fn)
+}
+
+func (c *Ring) Pipeline() Pipeliner {
+	pipe := Pipeline{
+		ctx:  c.ctx,
+		exec: c.processPipeline,
+	}
+	pipe.init()
+	return &pipe
+}
+
+func (c *Ring) processPipeline(ctx context.Context, cmds []Cmder) error {
+	return c.hooks.processPipeline(ctx, cmds, func(ctx context.Context, cmds []Cmder) error {
+		return c.generalProcessPipeline(ctx, cmds, false)
+	})
+}
+
+func (c *Ring) TxPipelined(fn func(Pipeliner) error) ([]Cmder, error) {
+	return c.TxPipeline().Pipelined(fn)
+}
+
+func (c *Ring) TxPipeline() Pipeliner {
+	pipe := Pipeline{
+		ctx:  c.ctx,
+		exec: c.processTxPipeline,
+	}
+	pipe.init()
+	return &pipe
+}
+
+func (c *Ring) processTxPipeline(ctx context.Context, cmds []Cmder) error {
+	return c.hooks.processPipeline(ctx, cmds, func(ctx context.Context, cmds []Cmder) error {
+		return c.generalProcessPipeline(ctx, cmds, true)
+	})
+}
+
+func (c *Ring) generalProcessPipeline(
+	ctx context.Context, cmds []Cmder, tx bool,
+) error {
+	cmdsMap := make(map[string][]Cmder)
+	for _, cmd := range cmds {
+		cmdInfo := c.cmdInfo(cmd.Name())
+		hash := cmd.stringArg(cmdFirstKeyPos(cmd, cmdInfo))
+		if hash != "" {
+			hash = c.shards.Hash(hashtag.Key(hash))
+		}
+		cmdsMap[hash] = append(cmdsMap[hash], cmd)
+	}
+
+	for attempt := 0; attempt <= c.opt.MaxRetries; attempt++ {
+		if attempt > 0 {
+			time.Sleep(c.retryBackoff(attempt))
+		}
+
+		var mu sync.Mutex
+		var failedCmdsMap map[string][]Cmder
+		var wg sync.WaitGroup
+
+		for hash, cmds := range cmdsMap {
+			wg.Add(1)
+			go func(hash string, cmds []Cmder) {
+				defer wg.Done()
+
+				shard, err := c.shards.GetByHash(hash)
+				if err != nil {
+					setCmdsErr(cmds, err)
+					return
+				}
+
+				cn, err := shard.Client.getConn(ctx)
+				if err != nil {
+					setCmdsErr(cmds, err)
+					return
+				}
+
+				var canRetry bool
+				if tx {
+					canRetry, err = shard.Client.txPipelineProcessCmds(ctx, cn, cmds)
+				} else {
+					canRetry, err = shard.Client.pipelineProcessCmds(ctx, cn, cmds)
+				}
+				shard.Client.releaseConnStrict(cn, err)
+
+				if canRetry && internal.IsRetryableError(err, true) {
+					mu.Lock()
+					if failedCmdsMap == nil {
+						failedCmdsMap = make(map[string][]Cmder)
+					}
+					failedCmdsMap[hash] = cmds
+					mu.Unlock()
+				}
+			}(hash, cmds)
+		}
+
+		wg.Wait()
+		if len(failedCmdsMap) == 0 {
+			break
+		}
+		cmdsMap = failedCmdsMap
+	}
+
+	return cmdsFirstErr(cmds)
+}
+
+// Close closes the ring client, releasing any open resources.
+//
+// It is rare to Close a Ring, as the Ring is meant to be long-lived
+// and shared between many goroutines.
+func (c *Ring) Close() error {
+	return c.shards.Close()
+}
+
+func (c *Ring) Watch(fn func(*Tx) error, keys ...string) error {
+	if len(keys) == 0 {
+		return fmt.Errorf("redis: Watch requires at least one key")
+	}
+
+	var shards []*ringShard
+	for _, key := range keys {
+		if key != "" {
+			shard, err := c.shards.GetByKey(hashtag.Key(key))
+			if err != nil {
+				return err
+			}
+
+			shards = append(shards, shard)
+		}
+	}
+
+	if len(shards) == 0 {
+		return fmt.Errorf("redis: Watch requires at least one shard")
+	}
+
+	if len(shards) > 1 {
+		for _, shard := range shards[1:] {
+			if shard.Client != shards[0].Client {
+				err := fmt.Errorf("redis: Watch requires all keys to be in the same shard")
+				return err
+			}
+		}
+	}
+
+	return shards[0].Client.Watch(fn, keys...)
+}
+
+func newConsistentHash(opt *RingOptions) *consistenthash.Map {
+	return consistenthash.New(opt.HashReplicas, consistenthash.Hash(opt.Hash))
+}

+ 485 - 0
go/gopath/src/github.com/go-redis/redis/ring_test.go

@@ -0,0 +1,485 @@
+package redis_test
+
+import (
+	"context"
+	"crypto/rand"
+	"fmt"
+	"net"
+	"strconv"
+	"sync"
+	"time"
+
+	"github.com/go-redis/redis"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("Redis Ring", func() {
+	const heartbeat = 100 * time.Millisecond
+
+	var ring *redis.Ring
+
+	setRingKeys := func() {
+		for i := 0; i < 100; i++ {
+			err := ring.Set(fmt.Sprintf("key%d", i), "value", 0).Err()
+			Expect(err).NotTo(HaveOccurred())
+		}
+	}
+
+	BeforeEach(func() {
+		opt := redisRingOptions()
+		opt.HeartbeatFrequency = heartbeat
+		ring = redis.NewRing(opt)
+
+		err := ring.ForEachShard(func(cl *redis.Client) error {
+			return cl.FlushDB().Err()
+		})
+		Expect(err).NotTo(HaveOccurred())
+	})
+
+	AfterEach(func() {
+		Expect(ring.Close()).NotTo(HaveOccurred())
+	})
+
+	It("supports WithContext", func() {
+		c, cancel := context.WithCancel(context.Background())
+		cancel()
+
+		err := ring.WithContext(c).Ping().Err()
+		Expect(err).To(MatchError("context canceled"))
+	})
+
+	It("distributes keys", func() {
+		setRingKeys()
+
+		// Both shards should have some keys now.
+		Expect(ringShard1.Info("keyspace").Val()).To(ContainSubstring("keys=57"))
+		Expect(ringShard2.Info("keyspace").Val()).To(ContainSubstring("keys=43"))
+	})
+
+	It("distributes keys when using EVAL", func() {
+		script := redis.NewScript(`
+			local r = redis.call('SET', KEYS[1], ARGV[1])
+			return r
+		`)
+
+		var key string
+		for i := 0; i < 100; i++ {
+			key = fmt.Sprintf("key%d", i)
+			err := script.Run(ring, []string{key}, "value").Err()
+			Expect(err).NotTo(HaveOccurred())
+		}
+
+		Expect(ringShard1.Info("keyspace").Val()).To(ContainSubstring("keys=57"))
+		Expect(ringShard2.Info("keyspace").Val()).To(ContainSubstring("keys=43"))
+	})
+
+	It("uses single shard when one of the shards is down", func() {
+		// Stop ringShard2.
+		Expect(ringShard2.Close()).NotTo(HaveOccurred())
+
+		Eventually(func() int {
+			return ring.Len()
+		}, "30s").Should(Equal(1))
+
+		setRingKeys()
+
+		// RingShard1 should have all keys.
+		Expect(ringShard1.Info("keyspace").Val()).To(ContainSubstring("keys=100"))
+
+		// Start ringShard2.
+		var err error
+		ringShard2, err = startRedis(ringShard2Port)
+		Expect(err).NotTo(HaveOccurred())
+
+		Eventually(func() int {
+			return ring.Len()
+		}, "30s").Should(Equal(2))
+
+		setRingKeys()
+
+		// RingShard2 should have its keys.
+		Expect(ringShard2.Info("keyspace").Val()).To(ContainSubstring("keys=43"))
+	})
+
+	It("supports hash tags", func() {
+		for i := 0; i < 100; i++ {
+			err := ring.Set(fmt.Sprintf("key%d{tag}", i), "value", 0).Err()
+			Expect(err).NotTo(HaveOccurred())
+		}
+
+		Expect(ringShard1.Info("keyspace").Val()).ToNot(ContainSubstring("keys="))
+		Expect(ringShard2.Info("keyspace").Val()).To(ContainSubstring("keys=100"))
+	})
+
+	Describe("pipeline", func() {
+		It("distributes keys", func() {
+			pipe := ring.Pipeline()
+			for i := 0; i < 100; i++ {
+				err := pipe.Set(fmt.Sprintf("key%d", i), "value", 0).Err()
+				Expect(err).NotTo(HaveOccurred())
+			}
+			cmds, err := pipe.Exec()
+			Expect(err).NotTo(HaveOccurred())
+			Expect(cmds).To(HaveLen(100))
+			Expect(pipe.Close()).NotTo(HaveOccurred())
+
+			for _, cmd := range cmds {
+				Expect(cmd.Err()).NotTo(HaveOccurred())
+				Expect(cmd.(*redis.StatusCmd).Val()).To(Equal("OK"))
+			}
+
+			// Both shards should have some keys now.
+			Expect(ringShard1.Info().Val()).To(ContainSubstring("keys=57"))
+			Expect(ringShard2.Info().Val()).To(ContainSubstring("keys=43"))
+		})
+
+		It("is consistent with ring", func() {
+			var keys []string
+			for i := 0; i < 100; i++ {
+				key := make([]byte, 64)
+				_, err := rand.Read(key)
+				Expect(err).NotTo(HaveOccurred())
+				keys = append(keys, string(key))
+			}
+
+			_, err := ring.Pipelined(func(pipe redis.Pipeliner) error {
+				for _, key := range keys {
+					pipe.Set(key, "value", 0).Err()
+				}
+				return nil
+			})
+			Expect(err).NotTo(HaveOccurred())
+
+			for _, key := range keys {
+				val, err := ring.Get(key).Result()
+				Expect(err).NotTo(HaveOccurred())
+				Expect(val).To(Equal("value"))
+			}
+		})
+
+		It("supports hash tags", func() {
+			_, err := ring.Pipelined(func(pipe redis.Pipeliner) error {
+				for i := 0; i < 100; i++ {
+					pipe.Set(fmt.Sprintf("key%d{tag}", i), "value", 0).Err()
+				}
+				return nil
+			})
+			Expect(err).NotTo(HaveOccurred())
+
+			Expect(ringShard1.Info().Val()).ToNot(ContainSubstring("keys="))
+			Expect(ringShard2.Info().Val()).To(ContainSubstring("keys=100"))
+		})
+	})
+
+	Describe("shard passwords", func() {
+		It("can be initialized with a single password, used for all shards", func() {
+			opts := redisRingOptions()
+			opts.Password = "password"
+			ring = redis.NewRing(opts)
+
+			err := ring.Ping().Err()
+			Expect(err).To(MatchError("ERR Client sent AUTH, but no password is set"))
+		})
+
+		It("can be initialized with a passwords map, one for each shard", func() {
+			opts := redisRingOptions()
+			opts.Passwords = map[string]string{
+				"ringShardOne": "password1",
+				"ringShardTwo": "password2",
+			}
+			ring = redis.NewRing(opts)
+
+			err := ring.Ping().Err()
+			Expect(err).To(MatchError("ERR Client sent AUTH, but no password is set"))
+		})
+	})
+})
+
+var _ = Describe("empty Redis Ring", func() {
+	var ring *redis.Ring
+
+	BeforeEach(func() {
+		ring = redis.NewRing(&redis.RingOptions{})
+	})
+
+	AfterEach(func() {
+		Expect(ring.Close()).NotTo(HaveOccurred())
+	})
+
+	It("returns an error", func() {
+		err := ring.Ping().Err()
+		Expect(err).To(MatchError("redis: all ring shards are down"))
+	})
+
+	It("pipeline returns an error", func() {
+		_, err := ring.Pipelined(func(pipe redis.Pipeliner) error {
+			pipe.Ping()
+			return nil
+		})
+		Expect(err).To(MatchError("redis: all ring shards are down"))
+	})
+})
+
+var _ = Describe("Ring watch", func() {
+	const heartbeat = 100 * time.Millisecond
+
+	var ring *redis.Ring
+
+	BeforeEach(func() {
+		opt := redisRingOptions()
+		opt.HeartbeatFrequency = heartbeat
+		ring = redis.NewRing(opt)
+
+		err := ring.ForEachShard(func(cl *redis.Client) error {
+			return cl.FlushDB().Err()
+		})
+		Expect(err).NotTo(HaveOccurred())
+	})
+
+	AfterEach(func() {
+		Expect(ring.Close()).NotTo(HaveOccurred())
+	})
+
+	It("should Watch", func() {
+		var incr func(string) error
+
+		// Transactionally increments key using GET and SET commands.
+		incr = func(key string) error {
+			err := ring.Watch(func(tx *redis.Tx) error {
+				n, err := tx.Get(key).Int64()
+				if err != nil && err != redis.Nil {
+					return err
+				}
+
+				_, err = tx.Pipelined(func(pipe redis.Pipeliner) error {
+					pipe.Set(key, strconv.FormatInt(n+1, 10), 0)
+					return nil
+				})
+				return err
+			}, key)
+			if err == redis.TxFailedErr {
+				return incr(key)
+			}
+			return err
+		}
+
+		var wg sync.WaitGroup
+		for i := 0; i < 100; i++ {
+			wg.Add(1)
+			go func() {
+				defer GinkgoRecover()
+				defer wg.Done()
+
+				err := incr("key")
+				Expect(err).NotTo(HaveOccurred())
+			}()
+		}
+		wg.Wait()
+
+		n, err := ring.Get("key").Int64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(n).To(Equal(int64(100)))
+	})
+
+	It("should discard", func() {
+		err := ring.Watch(func(tx *redis.Tx) error {
+			cmds, err := tx.Pipelined(func(pipe redis.Pipeliner) error {
+				pipe.Set("key1", "hello1", 0)
+				pipe.Discard()
+				pipe.Set("key2", "hello2", 0)
+				return nil
+			})
+			Expect(err).NotTo(HaveOccurred())
+			Expect(cmds).To(HaveLen(1))
+			return err
+		}, "key1", "key2")
+		Expect(err).NotTo(HaveOccurred())
+
+		get := ring.Get("key1")
+		Expect(get.Err()).To(Equal(redis.Nil))
+		Expect(get.Val()).To(Equal(""))
+
+		get = ring.Get("key2")
+		Expect(get.Err()).NotTo(HaveOccurred())
+		Expect(get.Val()).To(Equal("hello2"))
+	})
+
+	It("returns no error when there are no commands", func() {
+		err := ring.Watch(func(tx *redis.Tx) error {
+			_, err := tx.Pipelined(func(redis.Pipeliner) error { return nil })
+			return err
+		}, "key")
+		Expect(err).NotTo(HaveOccurred())
+
+		v, err := ring.Ping().Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(v).To(Equal("PONG"))
+	})
+
+	It("should exec bulks", func() {
+		const N = 20000
+
+		err := ring.Watch(func(tx *redis.Tx) error {
+			cmds, err := tx.Pipelined(func(pipe redis.Pipeliner) error {
+				for i := 0; i < N; i++ {
+					pipe.Incr("key")
+				}
+				return nil
+			})
+			Expect(err).NotTo(HaveOccurred())
+			Expect(len(cmds)).To(Equal(N))
+			for _, cmd := range cmds {
+				Expect(cmd.Err()).NotTo(HaveOccurred())
+			}
+			return err
+		}, "key")
+		Expect(err).NotTo(HaveOccurred())
+
+		num, err := ring.Get("key").Int64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(num).To(Equal(int64(N)))
+	})
+
+	It("should Watch/Unwatch", func() {
+		var C, N int
+
+		err := ring.Set("key", "0", 0).Err()
+		Expect(err).NotTo(HaveOccurred())
+
+		perform(C, func(id int) {
+			for i := 0; i < N; i++ {
+				err := ring.Watch(func(tx *redis.Tx) error {
+					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.Pipelined(func(pipe redis.Pipeliner) error {
+						pipe.Set("key", strconv.FormatInt(num+1, 10), 0)
+						return nil
+					})
+					Expect(cmds).To(HaveLen(1))
+					return err
+				}, "key")
+				if err == redis.TxFailedErr {
+					i--
+					continue
+				}
+				Expect(err).NotTo(HaveOccurred())
+			}
+		})
+
+		val, err := ring.Get("key").Int64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(val).To(Equal(int64(C * N)))
+	})
+
+	It("should close Tx without closing the client", func() {
+		err := ring.Watch(func(tx *redis.Tx) error {
+			_, err := tx.Pipelined(func(pipe redis.Pipeliner) error {
+				pipe.Ping()
+				return nil
+			})
+			return err
+		}, "key")
+		Expect(err).NotTo(HaveOccurred())
+
+		Expect(ring.Ping().Err()).NotTo(HaveOccurred())
+	})
+
+	It("respects max size on multi", func() {
+		perform(1000, func(id int) {
+			var ping *redis.StatusCmd
+
+			err := ring.Watch(func(tx *redis.Tx) error {
+				cmds, err := tx.Pipelined(func(pipe redis.Pipeliner) error {
+					ping = pipe.Ping()
+					return nil
+				})
+				Expect(err).NotTo(HaveOccurred())
+				Expect(cmds).To(HaveLen(1))
+				return err
+			}, "key")
+			Expect(err).NotTo(HaveOccurred())
+
+			Expect(ping.Err()).NotTo(HaveOccurred())
+			Expect(ping.Val()).To(Equal("PONG"))
+		})
+
+		ring.ForEachShard(func(cl *redis.Client) error {
+			defer GinkgoRecover()
+
+			pool := cl.Pool()
+			Expect(pool.Len()).To(BeNumerically("<=", 10))
+			Expect(pool.IdleLen()).To(BeNumerically("<=", 10))
+			Expect(pool.Len()).To(Equal(pool.IdleLen()))
+
+			return nil
+		})
+	})
+})
+
+var _ = Describe("Ring Tx timeout", func() {
+	const heartbeat = 100 * time.Millisecond
+
+	var ring *redis.Ring
+
+	AfterEach(func() {
+		_ = ring.Close()
+	})
+
+	testTimeout := func() {
+		It("Tx timeouts", func() {
+			err := ring.Watch(func(tx *redis.Tx) error {
+				return tx.Ping().Err()
+			}, "foo")
+			Expect(err).To(HaveOccurred())
+			Expect(err.(net.Error).Timeout()).To(BeTrue())
+		})
+
+		It("Tx Pipeline timeouts", func() {
+			err := ring.Watch(func(tx *redis.Tx) error {
+				_, err := tx.Pipelined(func(pipe redis.Pipeliner) error {
+					pipe.Ping()
+					return nil
+				})
+				return err
+			}, "foo")
+			Expect(err).To(HaveOccurred())
+			Expect(err.(net.Error).Timeout()).To(BeTrue())
+		})
+	}
+
+	const pause = 5 * time.Second
+
+	Context("read/write timeout", func() {
+		BeforeEach(func() {
+			opt := redisRingOptions()
+			opt.ReadTimeout = 250 * time.Millisecond
+			opt.WriteTimeout = 250 * time.Millisecond
+			opt.HeartbeatFrequency = heartbeat
+			ring = redis.NewRing(opt)
+
+			err := ring.ForEachShard(func(client *redis.Client) error {
+				return client.ClientPause(pause).Err()
+			})
+			Expect(err).NotTo(HaveOccurred())
+		})
+
+		AfterEach(func() {
+			_ = ring.ForEachShard(func(client *redis.Client) error {
+				defer GinkgoRecover()
+				Eventually(func() error {
+					return client.Ping().Err()
+				}, 2*pause).ShouldNot(HaveOccurred())
+				return nil
+			})
+		})
+
+		testTimeout()
+	})
+})

+ 62 - 0
go/gopath/src/github.com/go-redis/redis/script.go

@@ -0,0 +1,62 @@
+package redis
+
+import (
+	"crypto/sha1"
+	"encoding/hex"
+	"io"
+	"strings"
+)
+
+type scripter interface {
+	Eval(script string, keys []string, args ...interface{}) *Cmd
+	EvalSha(sha1 string, keys []string, args ...interface{}) *Cmd
+	ScriptExists(hashes ...string) *BoolSliceCmd
+	ScriptLoad(script string) *StringCmd
+}
+
+var _ scripter = (*Client)(nil)
+var _ scripter = (*Ring)(nil)
+var _ scripter = (*ClusterClient)(nil)
+
+type Script struct {
+	src, hash string
+}
+
+func NewScript(src string) *Script {
+	h := sha1.New()
+	_, _ = io.WriteString(h, src)
+	return &Script{
+		src:  src,
+		hash: hex.EncodeToString(h.Sum(nil)),
+	}
+}
+
+func (s *Script) Hash() string {
+	return s.hash
+}
+
+func (s *Script) Load(c scripter) *StringCmd {
+	return c.ScriptLoad(s.src)
+}
+
+func (s *Script) Exists(c scripter) *BoolSliceCmd {
+	return c.ScriptExists(s.hash)
+}
+
+func (s *Script) Eval(c scripter, keys []string, args ...interface{}) *Cmd {
+	return c.Eval(s.src, keys, args...)
+}
+
+func (s *Script) EvalSha(c scripter, keys []string, args ...interface{}) *Cmd {
+	return c.EvalSha(s.hash, keys, args...)
+}
+
+// Run optimistically uses EVALSHA to run the script. If script does not exist
+// it is retried using EVAL.
+func (s *Script) Run(c scripter, keys []string, args ...interface{}) *Cmd {
+	r := s.EvalSha(c, keys, args...)
+	if err := r.Err(); err != nil && strings.HasPrefix(err.Error(), "NOSCRIPT ") {
+		return s.Eval(c, keys, args...)
+	}
+	return r
+}

+ 496 - 0
go/gopath/src/github.com/go-redis/redis/sentinel.go

@@ -0,0 +1,496 @@
+package redis
+
+import (
+	"context"
+	"crypto/tls"
+	"errors"
+	"net"
+	"strings"
+	"sync"
+	"time"
+
+	"github.com/go-redis/redis/internal"
+	"github.com/go-redis/redis/internal/pool"
+)
+
+//------------------------------------------------------------------------------
+
+// FailoverOptions are used to configure a failover client and should
+// be passed to NewFailoverClient.
+type FailoverOptions struct {
+	// The master name.
+	MasterName string
+	// A seed list of host:port addresses of sentinel nodes.
+	SentinelAddrs    []string
+	SentinelPassword string
+
+	// Following options are copied from Options struct.
+
+	Dialer    func(ctx context.Context, network, addr string) (net.Conn, error)
+	OnConnect func(*Conn) error
+
+	Password string
+	DB       int
+
+	MaxRetries      int
+	MinRetryBackoff time.Duration
+	MaxRetryBackoff time.Duration
+
+	DialTimeout  time.Duration
+	ReadTimeout  time.Duration
+	WriteTimeout time.Duration
+
+	PoolSize           int
+	MinIdleConns       int
+	MaxConnAge         time.Duration
+	PoolTimeout        time.Duration
+	IdleTimeout        time.Duration
+	IdleCheckFrequency time.Duration
+
+	TLSConfig *tls.Config
+}
+
+func (opt *FailoverOptions) options() *Options {
+	return &Options{
+		Addr:      "FailoverClient",
+		Dialer:    opt.Dialer,
+		OnConnect: opt.OnConnect,
+
+		DB:       opt.DB,
+		Password: opt.Password,
+
+		MaxRetries: opt.MaxRetries,
+
+		DialTimeout:  opt.DialTimeout,
+		ReadTimeout:  opt.ReadTimeout,
+		WriteTimeout: opt.WriteTimeout,
+
+		PoolSize:           opt.PoolSize,
+		PoolTimeout:        opt.PoolTimeout,
+		IdleTimeout:        opt.IdleTimeout,
+		IdleCheckFrequency: opt.IdleCheckFrequency,
+
+		TLSConfig: opt.TLSConfig,
+	}
+}
+
+// NewFailoverClient returns a Redis client that uses Redis Sentinel
+// for automatic failover. It's safe for concurrent use by multiple
+// goroutines.
+func NewFailoverClient(failoverOpt *FailoverOptions) *Client {
+	opt := failoverOpt.options()
+	opt.init()
+
+	failover := &sentinelFailover{
+		masterName:    failoverOpt.MasterName,
+		sentinelAddrs: failoverOpt.SentinelAddrs,
+		password:      failoverOpt.SentinelPassword,
+
+		opt: opt,
+	}
+
+	c := Client{
+		client: &client{
+			baseClient: baseClient{
+				opt:      opt,
+				connPool: failover.Pool(),
+				onClose:  failover.Close,
+			},
+		},
+		ctx: context.Background(),
+	}
+	c.init()
+
+	return &c
+}
+
+//------------------------------------------------------------------------------
+
+type SentinelClient struct {
+	*baseClient
+	ctx context.Context
+}
+
+func NewSentinelClient(opt *Options) *SentinelClient {
+	opt.init()
+	c := &SentinelClient{
+		baseClient: &baseClient{
+			opt:      opt,
+			connPool: newConnPool(opt),
+		},
+		ctx: context.Background(),
+	}
+	return c
+}
+
+func (c *SentinelClient) Context() context.Context {
+	return c.ctx
+}
+
+func (c *SentinelClient) WithContext(ctx context.Context) *SentinelClient {
+	if ctx == nil {
+		panic("nil context")
+	}
+	clone := *c
+	clone.ctx = ctx
+	return &clone
+}
+
+func (c *SentinelClient) Process(cmd Cmder) error {
+	return c.ProcessContext(c.ctx, cmd)
+}
+
+func (c *SentinelClient) ProcessContext(ctx context.Context, cmd Cmder) error {
+	return c.baseClient.process(ctx, cmd)
+}
+
+func (c *SentinelClient) pubSub() *PubSub {
+	pubsub := &PubSub{
+		opt: c.opt,
+
+		newConn: func(channels []string) (*pool.Conn, error) {
+			return c.newConn(context.TODO())
+		},
+		closeConn: c.connPool.CloseConn,
+	}
+	pubsub.init()
+	return pubsub
+}
+
+// Ping is used to test if a connection is still alive, or to
+// measure latency.
+func (c *SentinelClient) Ping() *StringCmd {
+	cmd := NewStringCmd("ping")
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// Subscribe subscribes the client to the specified channels.
+// Channels can be omitted to create empty subscription.
+func (c *SentinelClient) Subscribe(channels ...string) *PubSub {
+	pubsub := c.pubSub()
+	if len(channels) > 0 {
+		_ = pubsub.Subscribe(channels...)
+	}
+	return pubsub
+}
+
+// PSubscribe subscribes the client to the given patterns.
+// Patterns can be omitted to create empty subscription.
+func (c *SentinelClient) PSubscribe(channels ...string) *PubSub {
+	pubsub := c.pubSub()
+	if len(channels) > 0 {
+		_ = pubsub.PSubscribe(channels...)
+	}
+	return pubsub
+}
+
+func (c *SentinelClient) GetMasterAddrByName(name string) *StringSliceCmd {
+	cmd := NewStringSliceCmd("sentinel", "get-master-addr-by-name", name)
+	_ = c.Process(cmd)
+	return cmd
+}
+
+func (c *SentinelClient) Sentinels(name string) *SliceCmd {
+	cmd := NewSliceCmd("sentinel", "sentinels", name)
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// Failover forces a failover as if the master was not reachable, and without
+// asking for agreement to other Sentinels.
+func (c *SentinelClient) Failover(name string) *StatusCmd {
+	cmd := NewStatusCmd("sentinel", "failover", name)
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// Reset resets all the masters with matching name. The pattern argument is a
+// glob-style pattern. The reset process clears any previous state in a master
+// (including a failover in progress), and removes every slave and sentinel
+// already discovered and associated with the master.
+func (c *SentinelClient) Reset(pattern string) *IntCmd {
+	cmd := NewIntCmd("sentinel", "reset", pattern)
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// FlushConfig forces Sentinel to rewrite its configuration on disk, including
+// the current Sentinel state.
+func (c *SentinelClient) FlushConfig() *StatusCmd {
+	cmd := NewStatusCmd("sentinel", "flushconfig")
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// Master shows the state and info of the specified master.
+func (c *SentinelClient) Master(name string) *StringStringMapCmd {
+	cmd := NewStringStringMapCmd("sentinel", "master", name)
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// Masters shows a list of monitored masters and their state.
+func (c *SentinelClient) Masters() *SliceCmd {
+	cmd := NewSliceCmd("sentinel", "masters")
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// Slaves shows a list of slaves for the specified master and their state.
+func (c *SentinelClient) Slaves(name string) *SliceCmd {
+	cmd := NewSliceCmd("sentinel", "slaves", name)
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// CkQuorum checks if the current Sentinel configuration is able to reach the
+// quorum needed to failover a master, and the majority needed to authorize the
+// failover. This command should be used in monitoring systems to check if a
+// Sentinel deployment is ok.
+func (c *SentinelClient) CkQuorum(name string) *StringCmd {
+	cmd := NewStringCmd("sentinel", "ckquorum", name)
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// Monitor tells the Sentinel to start monitoring a new master with the specified
+// name, ip, port, and quorum.
+func (c *SentinelClient) Monitor(name, ip, port, quorum string) *StringCmd {
+	cmd := NewStringCmd("sentinel", "monitor", name, ip, port, quorum)
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// Set is used in order to change configuration parameters of a specific master.
+func (c *SentinelClient) Set(name, option, value string) *StringCmd {
+	cmd := NewStringCmd("sentinel", "set", name, option, value)
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// Remove is used in order to remove the specified master: the master will no
+// longer be monitored, and will totally be removed from the internal state of
+// the Sentinel.
+func (c *SentinelClient) Remove(name string) *StringCmd {
+	cmd := NewStringCmd("sentinel", "remove", name)
+	_ = c.Process(cmd)
+	return cmd
+}
+
+type sentinelFailover struct {
+	sentinelAddrs []string
+
+	opt      *Options
+	password string
+
+	pool     *pool.ConnPool
+	poolOnce sync.Once
+
+	mu          sync.RWMutex
+	masterName  string
+	_masterAddr string
+	sentinel    *SentinelClient
+	pubsub      *PubSub
+}
+
+func (c *sentinelFailover) Close() error {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	if c.sentinel != nil {
+		return c.closeSentinel()
+	}
+	return nil
+}
+
+func (c *sentinelFailover) Pool() *pool.ConnPool {
+	c.poolOnce.Do(func() {
+		opt := *c.opt
+		opt.Dialer = c.dial
+		c.pool = newConnPool(&opt)
+	})
+	return c.pool
+}
+
+func (c *sentinelFailover) dial(ctx context.Context, network, _ string) (net.Conn, error) {
+	addr, err := c.MasterAddr()
+	if err != nil {
+		return nil, err
+	}
+	if c.opt.Dialer != nil {
+		return c.opt.Dialer(ctx, network, addr)
+	}
+	return net.DialTimeout("tcp", addr, c.opt.DialTimeout)
+}
+
+func (c *sentinelFailover) MasterAddr() (string, error) {
+	addr, err := c.masterAddr()
+	if err != nil {
+		return "", err
+	}
+	c.switchMaster(addr)
+	return addr, nil
+}
+
+func (c *sentinelFailover) masterAddr() (string, error) {
+	addr := c.getMasterAddr()
+	if addr != "" {
+		return addr, nil
+	}
+
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	for i, sentinelAddr := range c.sentinelAddrs {
+		sentinel := NewSentinelClient(&Options{
+			Addr: sentinelAddr,
+
+			Password: c.password,
+
+			MaxRetries: c.opt.MaxRetries,
+
+			DialTimeout:  c.opt.DialTimeout,
+			ReadTimeout:  c.opt.ReadTimeout,
+			WriteTimeout: c.opt.WriteTimeout,
+
+			PoolSize:           c.opt.PoolSize,
+			PoolTimeout:        c.opt.PoolTimeout,
+			IdleTimeout:        c.opt.IdleTimeout,
+			IdleCheckFrequency: c.opt.IdleCheckFrequency,
+
+			TLSConfig: c.opt.TLSConfig,
+		})
+
+		masterAddr, err := sentinel.GetMasterAddrByName(c.masterName).Result()
+		if err != nil {
+			internal.Logger.Printf("sentinel: GetMasterAddrByName master=%q failed: %s",
+				c.masterName, err)
+			_ = sentinel.Close()
+			continue
+		}
+
+		// Push working sentinel to the top.
+		c.sentinelAddrs[0], c.sentinelAddrs[i] = c.sentinelAddrs[i], c.sentinelAddrs[0]
+		c.setSentinel(sentinel)
+
+		addr := net.JoinHostPort(masterAddr[0], masterAddr[1])
+		return addr, nil
+	}
+
+	return "", errors.New("redis: all sentinels are unreachable")
+}
+
+func (c *sentinelFailover) getMasterAddr() string {
+	c.mu.RLock()
+	sentinel := c.sentinel
+	c.mu.RUnlock()
+
+	if sentinel == nil {
+		return ""
+	}
+
+	addr, err := sentinel.GetMasterAddrByName(c.masterName).Result()
+	if err != nil {
+		internal.Logger.Printf("sentinel: GetMasterAddrByName name=%q failed: %s",
+			c.masterName, err)
+		c.mu.Lock()
+		if c.sentinel == sentinel {
+			_ = c.closeSentinel()
+		}
+		c.mu.Unlock()
+		return ""
+	}
+
+	return net.JoinHostPort(addr[0], addr[1])
+}
+
+func (c *sentinelFailover) switchMaster(addr string) {
+	c.mu.RLock()
+	masterAddr := c._masterAddr
+	c.mu.RUnlock()
+	if masterAddr == addr {
+		return
+	}
+
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	internal.Logger.Printf("sentinel: new master=%q addr=%q",
+		c.masterName, addr)
+	_ = c.Pool().Filter(func(cn *pool.Conn) bool {
+		return cn.RemoteAddr().String() != addr
+	})
+	c._masterAddr = addr
+}
+
+func (c *sentinelFailover) setSentinel(sentinel *SentinelClient) {
+	c.discoverSentinels(sentinel)
+	c.sentinel = sentinel
+
+	c.pubsub = sentinel.Subscribe("+switch-master")
+	go c.listen(c.pubsub)
+}
+
+func (c *sentinelFailover) closeSentinel() error {
+	firstErr := c.pubsub.Close()
+	c.pubsub = nil
+
+	err := c.sentinel.Close()
+	if err != nil && firstErr == nil {
+		firstErr = err
+	}
+	c.sentinel = nil
+
+	return firstErr
+}
+
+func (c *sentinelFailover) discoverSentinels(sentinel *SentinelClient) {
+	sentinels, err := sentinel.Sentinels(c.masterName).Result()
+	if err != nil {
+		internal.Logger.Printf("sentinel: Sentinels master=%q failed: %s", c.masterName, err)
+		return
+	}
+	for _, sentinel := range sentinels {
+		vals := sentinel.([]interface{})
+		for i := 0; i < len(vals); i += 2 {
+			key := vals[i].(string)
+			if key == "name" {
+				sentinelAddr := vals[i+1].(string)
+				if !contains(c.sentinelAddrs, sentinelAddr) {
+					internal.Logger.Printf("sentinel: discovered new sentinel=%q for master=%q",
+						sentinelAddr, c.masterName)
+					c.sentinelAddrs = append(c.sentinelAddrs, sentinelAddr)
+				}
+			}
+		}
+	}
+}
+
+func (c *sentinelFailover) listen(pubsub *PubSub) {
+	ch := pubsub.Channel()
+	for {
+		msg, ok := <-ch
+		if !ok {
+			break
+		}
+
+		if msg.Channel == "+switch-master" {
+			parts := strings.Split(msg.Payload, " ")
+			if parts[0] != c.masterName {
+				internal.Logger.Printf("sentinel: ignore addr for master=%q", parts[0])
+				continue
+			}
+			addr := net.JoinHostPort(parts[3], parts[4])
+			c.switchMaster(addr)
+		}
+	}
+}
+
+func contains(slice []string, str string) bool {
+	for _, s := range slice {
+		if s == str {
+			return true
+		}
+	}
+	return false
+}

+ 88 - 0
go/gopath/src/github.com/go-redis/redis/sentinel_test.go

@@ -0,0 +1,88 @@
+package redis_test
+
+import (
+	"github.com/go-redis/redis"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("Sentinel", func() {
+	var client *redis.Client
+
+	BeforeEach(func() {
+		client = redis.NewFailoverClient(&redis.FailoverOptions{
+			MasterName:    sentinelName,
+			SentinelAddrs: []string{":" + sentinelPort},
+		})
+		Expect(client.FlushDB().Err()).NotTo(HaveOccurred())
+	})
+
+	AfterEach(func() {
+		Expect(client.Close()).NotTo(HaveOccurred())
+	})
+
+	It("should facilitate failover", func() {
+		// Set value on master.
+		err := client.Set("foo", "master", 0).Err()
+		Expect(err).NotTo(HaveOccurred())
+
+		// Verify.
+		val, err := sentinelMaster.Get("foo").Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(val).To(Equal("master"))
+
+		// Create subscription.
+		ch := client.Subscribe("foo").Channel()
+
+		// Wait until replicated.
+		Eventually(func() string {
+			return sentinelSlave1.Get("foo").Val()
+		}, "1s", "100ms").Should(Equal("master"))
+		Eventually(func() string {
+			return sentinelSlave2.Get("foo").Val()
+		}, "1s", "100ms").Should(Equal("master"))
+
+		// Wait until slaves are picked up by sentinel.
+		Eventually(func() string {
+			return sentinel.Info().Val()
+		}, "10s", "100ms").Should(ContainSubstring("slaves=2"))
+
+		// Kill master.
+		sentinelMaster.Shutdown()
+		Eventually(func() error {
+			return sentinelMaster.Ping().Err()
+		}, "5s", "100ms").Should(HaveOccurred())
+
+		// Wait for Redis sentinel to elect new master.
+		Eventually(func() string {
+			return sentinelSlave1.Info().Val() + sentinelSlave2.Info().Val()
+		}, "30s", "1s").Should(ContainSubstring("role:master"))
+
+		// Check that client picked up new master.
+		Eventually(func() error {
+			return client.Get("foo").Err()
+		}, "5s", "100ms").ShouldNot(HaveOccurred())
+
+		// Publish message to check if subscription is renewed.
+		err = client.Publish("foo", "hello").Err()
+		Expect(err).NotTo(HaveOccurred())
+
+		var msg *redis.Message
+		Eventually(ch, "5s").Should(Receive(&msg))
+		Expect(msg.Channel).To(Equal("foo"))
+		Expect(msg.Payload).To(Equal("hello"))
+	})
+
+	It("supports DB selection", func() {
+		Expect(client.Close()).NotTo(HaveOccurred())
+
+		client = redis.NewFailoverClient(&redis.FailoverOptions{
+			MasterName:    sentinelName,
+			SentinelAddrs: []string{":" + sentinelPort},
+			DB:            1,
+		})
+		err := client.Ping().Err()
+		Expect(err).NotTo(HaveOccurred())
+	})
+})

+ 10 - 0
go/gopath/src/github.com/go-redis/redis/testdata/redis.conf

@@ -0,0 +1,10 @@
+# Minimal redis.conf
+
+port 6379
+daemonize no
+dir .
+save ""
+appendonly yes
+cluster-config-file nodes.conf
+cluster-node-timeout 30000
+maxclients 1001

+ 142 - 0
go/gopath/src/github.com/go-redis/redis/tx.go

@@ -0,0 +1,142 @@
+package redis
+
+import (
+	"context"
+
+	"github.com/go-redis/redis/internal/pool"
+	"github.com/go-redis/redis/internal/proto"
+)
+
+// TxFailedErr transaction redis failed.
+const TxFailedErr = proto.RedisError("redis: transaction failed")
+
+// Tx implements Redis transactions as described in
+// http://redis.io/topics/transactions. It's NOT safe for concurrent use
+// by multiple goroutines, because Exec resets list of watched keys.
+// If you don't need WATCH it is better to use Pipeline.
+type Tx struct {
+	cmdable
+	statefulCmdable
+	baseClient
+
+	ctx context.Context
+}
+
+func (c *Client) newTx() *Tx {
+	tx := Tx{
+		baseClient: baseClient{
+			opt:      c.opt,
+			connPool: pool.NewStickyConnPool(c.connPool.(*pool.ConnPool), true),
+		},
+		ctx: c.ctx,
+	}
+	tx.init()
+	return &tx
+}
+
+func (c *Tx) init() {
+	c.cmdable = c.Process
+	c.statefulCmdable = c.Process
+}
+
+func (c *Tx) Context() context.Context {
+	return c.ctx
+}
+
+func (c *Tx) WithContext(ctx context.Context) *Tx {
+	if ctx == nil {
+		panic("nil context")
+	}
+	clone := *c
+	clone.ctx = ctx
+	return &clone
+}
+
+func (c *Tx) Process(cmd Cmder) error {
+	return c.ProcessContext(c.ctx, cmd)
+}
+
+func (c *Tx) ProcessContext(ctx context.Context, cmd Cmder) error {
+	return c.baseClient.process(ctx, cmd)
+}
+
+// Watch prepares a transaction and marks the keys to be watched
+// for conditional execution if there are any keys.
+//
+// The transaction is automatically closed when fn exits.
+func (c *Client) Watch(fn func(*Tx) error, keys ...string) error {
+	tx := c.newTx()
+	if len(keys) > 0 {
+		if err := tx.Watch(keys...).Err(); err != nil {
+			_ = tx.Close()
+			return err
+		}
+	}
+
+	err := fn(tx)
+	_ = tx.Close()
+	return err
+}
+
+// Close closes the transaction, releasing any open resources.
+func (c *Tx) Close() error {
+	_ = c.Unwatch().Err()
+	return c.baseClient.Close()
+}
+
+// Watch marks the keys to be watched for conditional execution
+// of a transaction.
+func (c *Tx) Watch(keys ...string) *StatusCmd {
+	args := make([]interface{}, 1+len(keys))
+	args[0] = "watch"
+	for i, key := range keys {
+		args[1+i] = key
+	}
+	cmd := NewStatusCmd(args...)
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// Unwatch flushes all the previously watched keys for a transaction.
+func (c *Tx) Unwatch(keys ...string) *StatusCmd {
+	args := make([]interface{}, 1+len(keys))
+	args[0] = "unwatch"
+	for i, key := range keys {
+		args[1+i] = key
+	}
+	cmd := NewStatusCmd(args...)
+	_ = c.Process(cmd)
+	return cmd
+}
+
+// Pipeline creates a new pipeline. It is more convenient to use Pipelined.
+func (c *Tx) Pipeline() Pipeliner {
+	pipe := Pipeline{
+		ctx:  c.ctx,
+		exec: c.processTxPipeline,
+	}
+	pipe.init()
+	return &pipe
+}
+
+// Pipelined executes commands queued in the fn in a transaction.
+//
+// When using WATCH, EXEC will execute commands only if the watched keys
+// were not modified, allowing for a check-and-set mechanism.
+//
+// Exec always returns list of commands. If transaction fails
+// TxFailedErr is returned. Otherwise Exec returns an error of the first
+// failed command or nil.
+func (c *Tx) Pipelined(fn func(Pipeliner) error) ([]Cmder, error) {
+	return c.Pipeline().Pipelined(fn)
+}
+
+// TxPipelined is an alias for Pipelined.
+func (c *Tx) TxPipelined(fn func(Pipeliner) error) ([]Cmder, error) {
+	return c.Pipelined(fn)
+}
+
+// TxPipeline is an alias for Pipeline.
+func (c *Tx) TxPipeline() Pipeliner {
+	return c.Pipeline()
+}

+ 151 - 0
go/gopath/src/github.com/go-redis/redis/tx_test.go

@@ -0,0 +1,151 @@
+package redis_test
+
+import (
+	"context"
+	"strconv"
+	"sync"
+
+	"github.com/go-redis/redis"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("Tx", func() {
+	var client *redis.Client
+
+	BeforeEach(func() {
+		client = redis.NewClient(redisOptions())
+		Expect(client.FlushDB().Err()).NotTo(HaveOccurred())
+	})
+
+	AfterEach(func() {
+		Expect(client.Close()).NotTo(HaveOccurred())
+	})
+
+	It("should Watch", func() {
+		var incr func(string) error
+
+		// Transactionally increments key using GET and SET commands.
+		incr = func(key string) error {
+			err := client.Watch(func(tx *redis.Tx) error {
+				n, err := tx.Get(key).Int64()
+				if err != nil && err != redis.Nil {
+					return err
+				}
+
+				_, err = tx.Pipelined(func(pipe redis.Pipeliner) error {
+					pipe.Set(key, strconv.FormatInt(n+1, 10), 0)
+					return nil
+				})
+				return err
+			}, key)
+			if err == redis.TxFailedErr {
+				return incr(key)
+			}
+			return err
+		}
+
+		var wg sync.WaitGroup
+		for i := 0; i < 100; i++ {
+			wg.Add(1)
+			go func() {
+				defer GinkgoRecover()
+				defer wg.Done()
+
+				err := incr("key")
+				Expect(err).NotTo(HaveOccurred())
+			}()
+		}
+		wg.Wait()
+
+		n, err := client.Get("key").Int64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(n).To(Equal(int64(100)))
+	})
+
+	It("should discard", func() {
+		err := client.Watch(func(tx *redis.Tx) error {
+			cmds, err := tx.Pipelined(func(pipe redis.Pipeliner) error {
+				pipe.Set("key1", "hello1", 0)
+				pipe.Discard()
+				pipe.Set("key2", "hello2", 0)
+				return nil
+			})
+			Expect(err).NotTo(HaveOccurred())
+			Expect(cmds).To(HaveLen(1))
+			return err
+		}, "key1", "key2")
+		Expect(err).NotTo(HaveOccurred())
+
+		get := client.Get("key1")
+		Expect(get.Err()).To(Equal(redis.Nil))
+		Expect(get.Val()).To(Equal(""))
+
+		get = client.Get("key2")
+		Expect(get.Err()).NotTo(HaveOccurred())
+		Expect(get.Val()).To(Equal("hello2"))
+	})
+
+	It("returns no error when there are no commands", func() {
+		err := client.Watch(func(tx *redis.Tx) error {
+			_, err := tx.Pipelined(func(redis.Pipeliner) error { return nil })
+			return err
+		})
+		Expect(err).NotTo(HaveOccurred())
+
+		v, err := client.Ping().Result()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(v).To(Equal("PONG"))
+	})
+
+	It("should exec bulks", func() {
+		const N = 20000
+
+		err := client.Watch(func(tx *redis.Tx) error {
+			cmds, err := tx.Pipelined(func(pipe redis.Pipeliner) error {
+				for i := 0; i < N; i++ {
+					pipe.Incr("key")
+				}
+				return nil
+			})
+			Expect(err).NotTo(HaveOccurred())
+			Expect(len(cmds)).To(Equal(N))
+			for _, cmd := range cmds {
+				Expect(cmd.Err()).NotTo(HaveOccurred())
+			}
+			return err
+		})
+		Expect(err).NotTo(HaveOccurred())
+
+		num, err := client.Get("key").Int64()
+		Expect(err).NotTo(HaveOccurred())
+		Expect(num).To(Equal(int64(N)))
+	})
+
+	It("should recover from bad connection", func() {
+		// Put bad connection in the pool.
+		cn, err := client.Pool().Get(context.Background())
+		Expect(err).NotTo(HaveOccurred())
+
+		cn.SetNetConn(&badConn{})
+		client.Pool().Put(cn)
+
+		do := func() error {
+			err := client.Watch(func(tx *redis.Tx) error {
+				_, err := tx.Pipelined(func(pipe redis.Pipeliner) error {
+					pipe.Ping()
+					return nil
+				})
+				return err
+			})
+			return err
+		}
+
+		err = do()
+		Expect(err).To(MatchError("bad connection"))
+
+		err = do()
+		Expect(err).NotTo(HaveOccurred())
+	})
+})

+ 191 - 0
go/gopath/src/github.com/go-redis/redis/universal.go

@@ -0,0 +1,191 @@
+package redis
+
+import (
+	"context"
+	"crypto/tls"
+	"net"
+	"time"
+)
+
+// UniversalOptions information is required by UniversalClient to establish
+// connections.
+type UniversalOptions struct {
+	// Either a single address or a seed list of host:port addresses
+	// of cluster/sentinel nodes.
+	Addrs []string
+
+	// Database to be selected after connecting to the server.
+	// Only single-node and failover clients.
+	DB int
+
+	// Common options.
+
+	Dialer             func(ctx context.Context, network, addr string) (net.Conn, error)
+	OnConnect          func(*Conn) error
+	Password           string
+	MaxRetries         int
+	MinRetryBackoff    time.Duration
+	MaxRetryBackoff    time.Duration
+	DialTimeout        time.Duration
+	ReadTimeout        time.Duration
+	WriteTimeout       time.Duration
+	PoolSize           int
+	MinIdleConns       int
+	MaxConnAge         time.Duration
+	PoolTimeout        time.Duration
+	IdleTimeout        time.Duration
+	IdleCheckFrequency time.Duration
+	TLSConfig          *tls.Config
+
+	// Only cluster clients.
+
+	MaxRedirects   int
+	ReadOnly       bool
+	RouteByLatency bool
+	RouteRandomly  bool
+
+	// The sentinel master name.
+	// Only failover clients.
+	MasterName string
+}
+
+func (o *UniversalOptions) cluster() *ClusterOptions {
+	if len(o.Addrs) == 0 {
+		o.Addrs = []string{"127.0.0.1:6379"}
+	}
+
+	return &ClusterOptions{
+		Addrs:     o.Addrs,
+		Dialer:    o.Dialer,
+		OnConnect: o.OnConnect,
+
+		Password: o.Password,
+
+		MaxRedirects:   o.MaxRedirects,
+		ReadOnly:       o.ReadOnly,
+		RouteByLatency: o.RouteByLatency,
+		RouteRandomly:  o.RouteRandomly,
+
+		MaxRetries:      o.MaxRetries,
+		MinRetryBackoff: o.MinRetryBackoff,
+		MaxRetryBackoff: o.MaxRetryBackoff,
+
+		DialTimeout:        o.DialTimeout,
+		ReadTimeout:        o.ReadTimeout,
+		WriteTimeout:       o.WriteTimeout,
+		PoolSize:           o.PoolSize,
+		MinIdleConns:       o.MinIdleConns,
+		MaxConnAge:         o.MaxConnAge,
+		PoolTimeout:        o.PoolTimeout,
+		IdleTimeout:        o.IdleTimeout,
+		IdleCheckFrequency: o.IdleCheckFrequency,
+
+		TLSConfig: o.TLSConfig,
+	}
+}
+
+func (o *UniversalOptions) failover() *FailoverOptions {
+	if len(o.Addrs) == 0 {
+		o.Addrs = []string{"127.0.0.1:26379"}
+	}
+
+	return &FailoverOptions{
+		SentinelAddrs: o.Addrs,
+		MasterName:    o.MasterName,
+
+		Dialer:    o.Dialer,
+		OnConnect: o.OnConnect,
+
+		DB:       o.DB,
+		Password: o.Password,
+
+		MaxRetries:      o.MaxRetries,
+		MinRetryBackoff: o.MinRetryBackoff,
+		MaxRetryBackoff: o.MaxRetryBackoff,
+
+		DialTimeout:  o.DialTimeout,
+		ReadTimeout:  o.ReadTimeout,
+		WriteTimeout: o.WriteTimeout,
+
+		PoolSize:           o.PoolSize,
+		MinIdleConns:       o.MinIdleConns,
+		MaxConnAge:         o.MaxConnAge,
+		PoolTimeout:        o.PoolTimeout,
+		IdleTimeout:        o.IdleTimeout,
+		IdleCheckFrequency: o.IdleCheckFrequency,
+
+		TLSConfig: o.TLSConfig,
+	}
+}
+
+func (o *UniversalOptions) simple() *Options {
+	addr := "127.0.0.1:6379"
+	if len(o.Addrs) > 0 {
+		addr = o.Addrs[0]
+	}
+
+	return &Options{
+		Addr:      addr,
+		Dialer:    o.Dialer,
+		OnConnect: o.OnConnect,
+
+		DB:       o.DB,
+		Password: o.Password,
+
+		MaxRetries:      o.MaxRetries,
+		MinRetryBackoff: o.MinRetryBackoff,
+		MaxRetryBackoff: o.MaxRetryBackoff,
+
+		DialTimeout:  o.DialTimeout,
+		ReadTimeout:  o.ReadTimeout,
+		WriteTimeout: o.WriteTimeout,
+
+		PoolSize:           o.PoolSize,
+		MinIdleConns:       o.MinIdleConns,
+		MaxConnAge:         o.MaxConnAge,
+		PoolTimeout:        o.PoolTimeout,
+		IdleTimeout:        o.IdleTimeout,
+		IdleCheckFrequency: o.IdleCheckFrequency,
+
+		TLSConfig: o.TLSConfig,
+	}
+}
+
+// --------------------------------------------------------------------
+
+// UniversalClient is an abstract client which - based on the provided options -
+// can connect to either clusters, or sentinel-backed failover instances
+// or simple single-instance servers. This can be useful for testing
+// cluster-specific applications locally.
+type UniversalClient interface {
+	Cmdable
+	Context() context.Context
+	AddHook(Hook)
+	Watch(fn func(*Tx) error, keys ...string) error
+	Do(args ...interface{}) *Cmd
+	DoContext(ctx context.Context, args ...interface{}) *Cmd
+	Process(cmd Cmder) error
+	ProcessContext(ctx context.Context, cmd Cmder) error
+	Subscribe(channels ...string) *PubSub
+	PSubscribe(channels ...string) *PubSub
+	Close() error
+}
+
+var _ UniversalClient = (*Client)(nil)
+var _ UniversalClient = (*ClusterClient)(nil)
+var _ UniversalClient = (*Ring)(nil)
+
+// NewUniversalClient returns a new multi client. The type of client returned depends
+// on the following three conditions:
+//
+// 1. if a MasterName is passed a sentinel-backed FailoverClient will be returned
+// 2. if the number of Addrs is two or more, a ClusterClient will be returned
+// 3. otherwise, a single-node redis Client will be returned.
+func NewUniversalClient(opts *UniversalOptions) UniversalClient {
+	if opts.MasterName != "" {
+		return NewFailoverClient(opts.failover())
+	} else if len(opts.Addrs) > 1 {
+		return NewClusterClient(opts.cluster())
+	}
+	return NewClient(opts.simple())
+}

+ 41 - 0
go/gopath/src/github.com/go-redis/redis/universal_test.go

@@ -0,0 +1,41 @@
+package redis_test
+
+import (
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+
+	"github.com/go-redis/redis"
+)
+
+var _ = Describe("UniversalClient", func() {
+	var client redis.UniversalClient
+
+	AfterEach(func() {
+		if client != nil {
+			Expect(client.Close()).To(Succeed())
+		}
+	})
+
+	It("should connect to failover servers", func() {
+		client = redis.NewUniversalClient(&redis.UniversalOptions{
+			MasterName: sentinelName,
+			Addrs:      []string{":" + sentinelPort},
+		})
+		Expect(client.Ping().Err()).NotTo(HaveOccurred())
+	})
+
+	It("should connect to simple servers", func() {
+		client = redis.NewUniversalClient(&redis.UniversalOptions{
+			Addrs: []string{redisAddr},
+		})
+		Expect(client.Ping().Err()).NotTo(HaveOccurred())
+	})
+
+	It("should connect to clusters", func() {
+		client = redis.NewUniversalClient(&redis.UniversalOptions{
+			Addrs: cluster.addrs(),
+		})
+		Expect(client.Ping().Err()).NotTo(HaveOccurred())
+	})
+
+})