redis_clear_cache_handler.go 952 字节
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
	}
}