cache

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 15, 2021 License: MIT Imports: 7 Imported by: 54

README

gin-cache

A high performance gin middleware to cache http response. Compared to gin-contrib/cache, it has more than 45% performance improvement.

How To Use

Install

go get github.com/chenyahui/gin-cache

Example

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)
	}
}

Feature

  • Has more than 45% performance improvement compared to gin-cache
  • Offer a way to custom the cache key of request
  • Use Sync.Pool to cache high frequency objects
  • Use SingleFlight to avoid Hotspot Invalid

Benchmark

wrk -c 500 -d 1m -t 5 http://127.0.0.1:8080/hello

QPS

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cache

func Cache(keyGenerator KeyGenerator, options Options) gin.HandlerFunc

Cache user must pass getCacheKey to describe the way to generate cache key

func CacheByPath

func CacheByPath(options Options) gin.HandlerFunc

CacheByPath a shortcut function for caching response with url path, discard the query params

func CacheByURI

func CacheByURI(options Options) gin.HandlerFunc

CacheByURI a shortcut function for caching response with uri

Types

type KeyGenerator

type KeyGenerator func(c *gin.Context) (string, bool)

type Logger

type Logger interface {
	Printf(format string, args ...interface{})
}

type Options

type Options struct {
	// CacheStore the cache backend to store response
	CacheStore persist.CacheStore

	// CacheDuration
	CacheDuration time.Duration

	// DisableSingleFlight means whether use singleflight to avoid Hotspot Invalid when cache miss
	DisableSingleFlight bool

	// SingleflightForgetTime this option only be effective when DisableSingleFlight is false
	SingleflightForgetTime time.Duration

	// Logger
	Logger Logger
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL