cache

package module
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2023 License: MIT Imports: 10 Imported by: 37

README

gin-cache

Release doc goreportcard for gin-cache codecov

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.
  • Cache http response in local memory or Redis.
  • Offer a way to custom the cache strategy by per request.
  • Use singleflight to avoid cache breakdown problem.
  • Only Cache 2xx HTTP Response.

How To Use

Install

go get -u 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()

	memoryStore := persist.NewMemoryStore(1 * time.Minute)

	app.GET("/hello",
		cache.CacheByRequestURI(memoryStore, 2*time.Second),
		func(c *gin.Context) {
			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.CacheByRequestURI(redisStore, 2*time.Second),
		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

MemoryStore

MemoryStore QPS

RedisStore

RedisStore QPS

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cache

func Cache(
	defaultCacheStore persist.CacheStore,
	defaultExpire time.Duration,
	opts ...Option,
) gin.HandlerFunc

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

func CacheByRequestPath added in v1.0.0

func CacheByRequestPath(defaultCacheStore persist.CacheStore, defaultExpire time.Duration, opts ...Option) gin.HandlerFunc

CacheByRequestPath a shortcut function for caching response by url path, means will discard the query params

func CacheByRequestURI added in v1.0.0

func CacheByRequestURI(defaultCacheStore persist.CacheStore, defaultExpire time.Duration, opts ...Option) gin.HandlerFunc

CacheByRequestURI a shortcut function for caching response by uri

func CorsHeaders added in v1.9.0

func CorsHeaders() []string

Types

type BeforeReplyWithCacheCallback added in v1.5.0

type BeforeReplyWithCacheCallback func(c *gin.Context, cache *ResponseCache)

type Config added in v1.0.0

type Config struct {
	// contains filtered or unexported fields
}

Config contains all options

type Discard added in v1.0.0

type Discard struct {
}

Discard the default logger that will discard all logs of gin-cache

func (Discard) Errorf added in v1.0.0

func (l Discard) Errorf(string, ...interface{})

Errorf will output the log at error level

type GetCacheStrategyByRequest added in v1.0.0

type GetCacheStrategyByRequest func(c *gin.Context) (bool, Strategy)

GetCacheStrategyByRequest User can this function to design custom cache strategy by request. The first return value bool means whether this request should be cached. The second return value Strategy determine the special strategy by this request.

type Logger

type Logger interface {
	Errorf(string, ...interface{})
}

Logger define the logger interface

type OnHitCacheCallback added in v1.1.0

type OnHitCacheCallback func(c *gin.Context)

OnHitCacheCallback define the callback when use cache

type OnMissCacheCallback added in v1.8.0

type OnMissCacheCallback func(c *gin.Context)

OnMissCacheCallback define the callback when use cache

type OnShareSingleFlightCallback added in v1.3.0

type OnShareSingleFlightCallback func(c *gin.Context)

OnShareSingleFlightCallback define the callback when share the singleflight result

type Option added in v1.0.0

type Option func(c *Config)

Option represents the optional function.

func IgnoreQueryOrder added in v1.6.0

func IgnoreQueryOrder() Option

IgnoreQueryOrder will ignore the queries order in url when generate cache key . This option only takes effect in CacheByRequestURI function

func WithBeforeReplyWithCache added in v1.5.0

func WithBeforeReplyWithCache(cb BeforeReplyWithCacheCallback) Option

WithBeforeReplyWithCache will be called before replying with cache.

func WithCacheStrategyByRequest added in v1.0.0

func WithCacheStrategyByRequest(getGetCacheStrategyByRequest GetCacheStrategyByRequest) Option

WithCacheStrategyByRequest set up the custom strategy by per request

func WithDiscardHeaders added in v1.9.0

func WithDiscardHeaders(headers []string) Option

func WithLogger added in v1.0.0

func WithLogger(l Logger) Option

WithLogger set the custom logger

func WithOnHitCache added in v1.1.0

func WithOnHitCache(cb OnHitCacheCallback) Option

WithOnHitCache will be called when cache hit.

func WithOnMissCache added in v1.8.0

func WithOnMissCache(cb OnMissCacheCallback) Option

WithOnMissCache will be called when cache miss.

func WithOnShareSingleFlight added in v1.3.0

func WithOnShareSingleFlight(cb OnShareSingleFlightCallback) Option

WithOnShareSingleFlight will be called when share the singleflight result

func WithPrefixKey added in v1.7.0

func WithPrefixKey(prefix string) Option

WithPrefixKey will prefix the key

func WithSingleFlightForgetTimeout added in v1.2.0

func WithSingleFlightForgetTimeout(forgetTimeout time.Duration) Option

WithSingleFlightForgetTimeout to reduce the impact of long tail requests. singleflight.Forget will be called after the timeout has reached for each backend request when timeout is greater than zero.

func WithoutHeader added in v1.8.0

func WithoutHeader() Option

type ResponseCache added in v1.5.0

type ResponseCache struct {
	Status int
	Header http.Header
	Data   []byte
}

ResponseCache record the http response cache

type Strategy added in v1.0.0

type Strategy struct {
	CacheKey string

	// CacheStore if nil, use default cache store instead
	CacheStore persist.CacheStore

	// CacheDuration
	CacheDuration time.Duration
}

Strategy the cache strategy

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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