{cluster,ring}: add support for context to ClusterClient and Ring

This commit is contained in:
Gabriel Aszalos 2018-03-07 14:39:56 +01:00
parent b533525eff
commit 731dd72b84
No known key found for this signature in database
GPG Key ID: A62C719E49E3B839
2 changed files with 39 additions and 0 deletions

View File

@ -1,6 +1,7 @@
package redis package redis
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"math" "math"
@ -557,6 +558,8 @@ func (c *clusterStateHolder) Get() (*clusterState, error) {
type ClusterClient struct { type ClusterClient struct {
cmdable cmdable
ctx context.Context
opt *ClusterOptions opt *ClusterOptions
nodes *clusterNodes nodes *clusterNodes
state *clusterStateHolder state *clusterStateHolder
@ -593,6 +596,22 @@ func NewClusterClient(opt *ClusterOptions) *ClusterClient {
return c return c
} }
func (c *ClusterClient) Context() context.Context {
if c.ctx != nil {
return c.ctx
}
return context.Background()
}
func (c *ClusterClient) WithContext(ctx context.Context) *ClusterClient {
if ctx == nil {
panic("nil context")
}
c2 := c.copy()
c2.ctx = ctx
return c2
}
func (c *ClusterClient) copy() *ClusterClient { func (c *ClusterClient) copy() *ClusterClient {
cp := *c cp := *c
return &cp return &cp

20
ring.go
View File

@ -1,6 +1,7 @@
package redis package redis
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"math/rand" "math/rand"
@ -289,6 +290,9 @@ func (c *ringShards) Close() error {
// Otherwise you should use Redis Cluster. // Otherwise you should use Redis Cluster.
type Ring struct { type Ring struct {
cmdable cmdable
ctx context.Context
opt *RingOptions opt *RingOptions
shards *ringShards shards *ringShards
cmdsInfoCache *cmdsInfoCache cmdsInfoCache *cmdsInfoCache
@ -318,6 +322,22 @@ func NewRing(opt *RingOptions) *Ring {
return ring return ring
} }
func (c *Ring) Context() context.Context {
if c.ctx != nil {
return c.ctx
}
return context.Background()
}
func (c *Ring) WithContext(ctx context.Context) *Ring {
if ctx == nil {
panic("nil context")
}
c2 := c.copy()
c2.ctx = ctx
return c2
}
func (c *Ring) copy() *Ring { func (c *Ring) copy() *Ring {
cp := *c cp := *c
return &cp return &cp