-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRedisProvider.go
More file actions
110 lines (103 loc) · 2.53 KB
/
Copy pathRedisProvider.go
File metadata and controls
110 lines (103 loc) · 2.53 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package go2cache
import (
"github.com/garyburd/redigo/redis"
"sync"
"time"
"log"
)
//基于redis缓存提供者
type RedisProvider struct {
//redisCacheMap lock
mapLock sync.Mutex
//redis cache
redisCacheMap map[string]*RedisCache
// pool
redisClient *redis.Pool
//regions
regions []Region
//redis name space
redisNameSpace string
}
//init redis cahce
func (p *RedisProvider) InitRedisCache(config *Go2CacheRedis) {
p.mapLock.Lock()
defer p.mapLock.Unlock()
p.redisCacheMap = make(map[string]*RedisCache)
p.redisClient = &redis.Pool{
MaxActive: config.MaxActive,
MaxIdle: config.MaxIdle,
IdleTimeout: time.Duration(config.IdleTimeOut) * time.Second,
//test on borrow
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do("PING")
return err
},
Dial: func() (redis.Conn, error) {
c, e := redis.Dial("tcp", config.ConnectInfo)
if e != nil {
log.Printf("connect redis error:%s", e)
//循环尝试链接redis,直到成功
var wait sync.WaitGroup
wait.Add(1)
var count = 0
go func() {
for {
c, e = redis.Dial("tcp", config.ConnectInfo)
if e != nil {
//连接失败
log.Printf("the %d times try connect address:%s but failed :%s ", count, config.ConnectInfo, e)
count++
time.Sleep(3 * time.Second)
} else {
//连接成功
log.Printf("try to connect address:%s successful.... ...", config.ConnectInfo)
wait.Done()
break
}
}
}()
wait.Wait() //等待redis 连接成功之后 在继续逻辑
}
if config.Password != "" {
if _, err := c.Do("AUTH", config.Password); err != nil {
c.Close()
return nil, err
}
}
if _, err := c.Do("SELECT", config.DbIndex); err != nil {
c.Close()
return nil, err
}
return c, nil
}}
}
// build cache
func (p *RedisProvider) BuildCache(region string) (interface{}, error) {
p.mapLock.Lock()
defer p.mapLock.Unlock()
region = p.redisNameSpace + ":" + region
cache := p.redisCacheMap[region]
if cache == nil {
cache = &RedisCache{
redisClient: p.redisClient,
region: region}
p.redisCacheMap[region] = cache
p.regions = append(p.regions, Region{Name: region})
}
return cache, nil
}
// 缓存 等级
func (p *RedisProvider) Level() int {
return LEVEL_2
}
//region name default go2cache_redis
func (p *RedisProvider) Name() string {
return "go2cache_redis_provider"
}
//获取region 列表
func (p *RedisProvider) GetRegions() []Region {
return nil
}