/
memcache.go
71 lines (60 loc) · 1.53 KB
/
memcache.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
61
62
63
64
65
66
67
68
69
70
71
// Package mpcache memcache
// User: 姜伟
// Time: 2020-02-19 06:15:40
package mpcache
import (
"sync"
"time"
"github.com/a07061625/gompf/mpf"
"github.com/a07061625/gompf/mpf/mpconstant/errorcode"
"github.com/a07061625/gompf/mpf/mperr"
"github.com/bradfitz/gomemcache/memcache"
)
type cacheMem struct {
conn *memcache.Client
connTime int64
refreshTime int64
idleTime int64
}
func (c *cacheMem) connect() {
conf := mpf.NewConfig().GetConfig("caches")
servers := conf.GetStringSlice("memcache." + mpf.EnvProjectKey() + ".servers")
c.conn = memcache.New(servers...)
pingErr := c.conn.Ping()
if pingErr != nil {
c.conn = nil
panic(mperr.NewCacheMem(errorcode.CacheMemCacheConnect, "memcache连接失败", pingErr))
}
c.connTime = time.Now().Unix()
c.idleTime = conf.GetInt64("memcache." + mpf.EnvProjectKey() + ".idle")
c.refreshTime = c.connTime + c.idleTime
}
func (c *cacheMem) Reconnect() {
nowTime := time.Now().Unix()
if c.conn == nil {
c.connect()
} else if c.refreshTime < nowTime {
pingErr := c.conn.Ping()
if pingErr != nil {
c.connect()
}
c.refreshTime = nowTime + c.idleTime
}
}
func (c *cacheMem) GetConn() *memcache.Client {
return c.conn
}
var (
onceMem sync.Once
insMem *cacheMem
)
func init() {
insMem = &cacheMem{nil, 0, 0, 0}
}
// NewMem NewMem
func NewMem() *cacheMem {
onceMem.Do(func() {
insMem.connect()
})
return insMem
}