gin/hertz redis cache

gin-cache/[hertz-cache](hertz-contrib/cache (github.com))

package main

import (
	"context"
	"log"
	"net/http"
	"time"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/go-redis/redis/v8"
	"github.com/hertz-contrib/cache"
	"github.com/hertz-contrib/cache/persist"
)

var (
	redisStore *persist.RedisStore
)

// 注册中间件
func useRedisMw() app.HandlerFunc {
	return cache.NewCacheByRequestPath(redisStore, 2*time.Minute)
}

func main() {
	h := server.New()

	redisStore = persist.NewRedisStore(redis.NewClient(&redis.Options{
		Network: "tcp",
		Addr:    "localhost:6379",
	}))

	h.GET("/hello", useRedisMw(), func(ctx context.Context, c *app.RequestContext) {
		log.Println("request hello")
		c.String(http.StatusOK, "hello world")
	})
	h.GET("/clean", func(ctx context.Context, c *app.RequestContext) {
		// 删除缓存
        err := redisStore.Delete(ctx, "/hello")
		if err != nil {
			c.String(http.StatusInternalServerError, "clean failed")
			return
		}
		c.String(http.StatusOK, "clean success")
	})
	h.Spin()
}

posted @ 2023-02-17 10:43  七つ一旋桜  阅读(115)  评论(0)    收藏  举报