gin-cache
English |
A high performance gin middleware to cache http response. Compared to gin-contrib/cache. It has a huge performance improvement.
Feature
- Has a huge performance improvement compared to gin-contrib/cache.
- Support cache response in local memory and redis.
- Offer a way to custom the cache key of request.
- Use sync.Pool to cache high frequency objects.
- Use singleflight to avoid hotspot invalid.
How To Use
Install
go get github.com/chenyahui/gin-cache
Example
Cache In Local Memory
package main
import (
"time"
"github.com/chenyahui/gin-cache"
"github.com/chenyahui/gin-cache/persist"
"github.com/gin-gonic/gin"
)
func main() {
app := gin.New()
app.GET("/hello",
cache.CacheByPath(cache.Options{
CacheDuration: 5 * time.Second,
CacheStore: persist.NewMemoryStore(1 * time.Minute),
DisableSingleFlight: true,
}),
func(c *gin.Context) {
time.Sleep(200 * time.Millisecond)
c.String(200, "hello world")
},
)
if err := app.Run(":8080"); err != nil {
panic(err)
}
}
Cache In Redis
package main
import (
"time"
"github.com/chenyahui/gin-cache"
"github.com/chenyahui/gin-cache/persist"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v8"
)
func main() {
app := gin.New()
redisStore := persist.NewRedisStore(redis.NewClient(&redis.Options{
Network: "tcp",
Addr: "127.0.0.1:6379",
}))
app.GET("/hello",
cache.CacheByPath(cache.Options{
CacheDuration: 5 * time.Second,
CacheStore: redisStore,
}),
func(c *gin.Context) {
c.String(200, "hello world")
},
)
if err := app.Run(":8080"); err != nil {
panic(err)
}
}
Benchmark
wrk -c 500 -d 1m -t 5 http://127.0.0.1:8080/hello