redis_clear_cache_handler.go
952 字节
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
package rd
import (
"fmt"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/rest"
"net/http"
"strings"
)
func Routers(rd *redis.Redis, appName string) []rest.Route {
return []rest.Route{
{
Method: http.MethodGet,
Path: "/rd/clean",
Handler: CleanCache(rd, appName),
},
}
}
func CleanCache(rd *redis.Redis, appName string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
success int
)
if strings.TrimSpace(appName) == "" {
return
}
keyPattern := fmt.Sprintf("%s*", appName)
list, err := rd.Keys(keyPattern)
if err != nil {
return
}
for _, key := range list {
if _, err = rd.Del(key); err == nil {
success++
}
}
logx.Infof("清理缓存:%d/%d", success, len(list))
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf("清理缓存:%d/%d", success, len(list))))
return
}
}