forked from hyacinthus/restdemo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
70 lines (62 loc) · 1.29 KB
/
cache.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
package main
import (
"net/http"
"time"
"github.com/go-redis/cache"
"github.com/labstack/echo"
"github.com/sirupsen/logrus"
"github.com/vmihailenco/msgpack"
)
// 初始化缓存
func initCache() {
cc = &cache.Codec{
Redis: rdb,
Marshal: func(v interface{}) ([]byte, error) {
return msgpack.Marshal(v)
},
Unmarshal: func(b []byte, v interface{}) error {
return msgpack.Unmarshal(b, v)
},
}
}
// setcc 写缓存
func setcc(key string, object interface{}, exp time.Duration) {
cc.Set(&cache.Item{
Key: key,
Object: object,
Expiration: exp,
})
}
// getcc 读缓存
func getcc(key string, pointer interface{}) error {
return cc.Get(key, pointer)
}
// delcc 清缓存
func delcc(key string) {
cc.Delete(key)
}
// cleancc 批量清除一类缓存
func cleancc(cate string) {
if cate == "" {
logrus.Error("someone try to clean all cache keys")
return
}
i := 0
for _, key := range rdb.Keys(cate + "*").Val() {
delcc(key)
i++
}
logrus.Infof("delete %d %s cache", i, cate)
}
func deleteCache(c echo.Context) error {
cate := c.Param("cate")
switch cate {
case "token":
cleancc("token")
case "all":
cleancc("token")
default:
return newHTTPError(400, "InvalidID", "请在URL中提供合法的缓存类型")
}
return c.NoContent(http.StatusNoContent)
}