作者 yangfu

清理缓存

@@ -55,7 +55,7 @@ func main() { @@ -55,7 +55,7 @@ func main() {
55 55
56 ctx := svc.NewServiceContext(c) 56 ctx := svc.NewServiceContext(c)
57 handler.RegisterHandlers(server, ctx) 57 handler.RegisterHandlers(server, ctx)
58 - 58 + handler.RegisterExternalHandlers(server, ctx)
59 db.Migrate(ctx.DB) 59 db.Migrate(ctx.DB)
60 //启动消费队列 60 //启动消费队列
61 startConsume(ctx) 61 startConsume(ctx)
  1 +package handler
  2 +
  3 +import (
  4 + "github.com/zeromicro/go-zero/rest"
  5 + "gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/api/internal/svc"
  6 + "gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/pkg/openapi/rd"
  7 +)
  8 +
  9 +func RegisterExternalHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
  10 + server.AddRoutes(rd.Routers(serverCtx.Redis, serverCtx.Config.Name))
  11 +}
  1 +package rd
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/zeromicro/go-zero/core/logx"
  6 + "github.com/zeromicro/go-zero/core/stores/redis"
  7 + "github.com/zeromicro/go-zero/rest"
  8 + "net/http"
  9 + "strings"
  10 +)
  11 +
  12 +func Routers(rd *redis.Redis, appName string) []rest.Route {
  13 + return []rest.Route{
  14 + {
  15 + Method: http.MethodGet,
  16 + Path: "/rd/clean",
  17 + Handler: CleanCache(rd, appName),
  18 + },
  19 + }
  20 +}
  21 +
  22 +func CleanCache(rd *redis.Redis, appName string) http.HandlerFunc {
  23 + return func(w http.ResponseWriter, r *http.Request) {
  24 + var (
  25 + success int
  26 + )
  27 + if strings.TrimSpace(appName) == "" {
  28 + return
  29 + }
  30 + keyPattern := fmt.Sprintf("%s*", appName)
  31 + list, err := rd.Keys(keyPattern)
  32 + if err != nil {
  33 + return
  34 + }
  35 + for _, key := range list {
  36 + if _, err = rd.Del(key); err == nil {
  37 + success++
  38 + }
  39 + }
  40 + logx.Infof("清理缓存:%d/%d", success, len(list))
  41 + w.WriteHeader(http.StatusOK)
  42 + w.Write([]byte(fmt.Sprintf("清理缓存:%d/%d", success, len(list))))
  43 + return
  44 + }
  45 +}