-
Notifications
You must be signed in to change notification settings - Fork 0
/
memcache_pool.go
60 lines (55 loc) · 1.31 KB
/
memcache_pool.go
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
package frame
import (
"github.com/bradfitz/gomemcache/memcache"
"runtime/debug"
"sync"
"time"
)
var mcCacheMap map[string]*memcache.Client
var mcCacheOnce sync.Once
var mcLock sync.Mutex
type memCacheConfig struct {
Servers []string `toml:"servers"`
ConnectTimeout int `toml:"connect_timeout"`
MaxIdleConn int `toml:"maxIdleConn"`
}
func getMc(mcGroup string) *memcache.Client {
if mcCacheMap == nil {
mcCacheOnce.Do(func() {
mcCacheMap = make(map[string]*memcache.Client)
})
}
if cache, ok := mcCacheMap[mcGroup]; ok {
return cache
}
mcLock.Lock()
defer mcLock.Unlock()
mcConfig := &memCacheConfig{}
err := App().Env(mcGroup, mcConfig)
if err != nil {
panic(MemcachedConfigError.Error() + ":" + err.Error())
}
serverList := mcConfig.Servers
mc := memcache.New(serverList...)
if mc == nil {
msg := map[string]interface{}{
"error": "memcached New failed",
"stack": string(debug.Stack()),
}
App().Log.Error(msg, LogMemcachedError)
panic("memcached New failed")
}
mc.Timeout = time.Duration(mcConfig.ConnectTimeout) * time.Second
mc.MaxIdleConns = mcConfig.MaxIdleConn
mcCacheMap[mcGroup] = mc
return mc
}
//关闭连接池中所有闲置连接
func closeMemcachedPool() {
if mcCacheMap == nil {
return
}
for _, v := range mcCacheMap {
v.MaxIdleConns = 0
}
}