Created
June 28, 2014 11:32
-
-
Save vmihailenco/501f7b12e10980fd1e5d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sharding | |
import ( | |
"sync" | |
"github.com/golang/groupcache/consistenthash" | |
"gopkg.in/redis.v1" | |
) | |
const replicas = 100 | |
var noop = redis.NewTCPClient(&redis.Options{ | |
Addr: "noop", | |
}) | |
type RedisShard struct { | |
cons *consistenthash.Map | |
mtx sync.Mutex | |
servers map[string]*redis.Options | |
shards map[string]*redis.Client | |
} | |
func NewRedisShard() *RedisShard { | |
return &RedisShard{ | |
cons: consistenthash.New(replicas, nil), | |
servers: make(map[string]*redis.Options), | |
shards: make(map[string]*redis.Client), | |
} | |
} | |
func (s *RedisShard) Add(server string, opt *redis.Options) { | |
s.mtx.Lock() | |
s.cons.Add(server) | |
s.servers[server] = opt | |
s.mtx.Unlock() | |
} | |
func (s *RedisShard) getShard(server string) *redis.Client { | |
cl, ok := s.shards[server] | |
if !ok { | |
cl = redis.NewTCPClient(s.servers[server]) | |
s.shards[server] = cl | |
} | |
return cl | |
} | |
func (s *RedisShard) Get(key string) *redis.Client { | |
s.mtx.Lock() | |
server := s.cons.Get(key) | |
if server == "" { | |
return noop | |
} | |
shard := s.getShard(server) | |
s.mtx.Unlock() | |
return shard | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment