Repository navigation
Expand file tree
/
Copy pathcachepool.go
More file actions
80 lines (60 loc) · 1.37 KB
/
Copy pathcachepool.go
File metadata and controls
80 lines (60 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright 2014 Wandoujia Inc. All Rights Reserved.
// Licensed under the MIT (MIT-LICENSE.txt) license.
package cachepool
import (
"sync"
"time"
"github.com/wandoulabs/codis/pkg/proxy/redispool"
"github.com/juju/errors"
)
type LivePool struct {
pool *redispool.ConnectionPool
}
type CachePool struct {
mu sync.RWMutex
pools map[string]*LivePool
}
func NewCachePool() *CachePool {
return &CachePool{
pools: make(map[string]*LivePool),
}
}
func (cp *CachePool) GetConn(key string) (redispool.PoolConnection, error) {
cp.mu.RLock()
pool, ok := cp.pools[key]
if !ok {
cp.mu.RUnlock()
return nil, errors.Errorf("pool %s not exist", key)
}
c, err := pool.pool.Get()
cp.mu.RUnlock()
return c, err
}
func (cp *CachePool) ReleaseConn(pc redispool.PoolConnection) {
pc.Recycle()
}
func (cp *CachePool) AddPool(key string) error {
cp.mu.Lock()
defer cp.mu.Unlock()
pool, ok := cp.pools[key]
if ok {
return nil
}
pool = &LivePool{
pool: redispool.NewConnectionPool("redis conn pool", 20, 120*time.Second),
}
pool.pool.Open(redispool.ConnectionCreator(key))
cp.pools[key] = pool
return nil
}
func (cp *CachePool) RemovePool(key string) error {
cp.mu.Lock()
defer cp.mu.Unlock()
pool, ok := cp.pools[key]
if !ok {
return errors.Errorf("pool %s already exist", key)
}
pool.pool.Close() //todo:async close
delete(cp.pools, key)
return nil
}