Skip to content

Instantly share code, notes, and snippets.

@vmihailenco
Created June 28, 2014 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vmihailenco/501f7b12e10980fd1e5d to your computer and use it in GitHub Desktop.
Save vmihailenco/501f7b12e10980fd1e5d to your computer and use it in GitHub Desktop.
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