wcache

package module
v0.0.0-...-70c2af6 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2022 License: MIT Imports: 12 Imported by: 0

README

wcache

GitHub Repo stars GitHub GitHub go.mod Go version GitHub CI Status Go Report Card Go.Dev reference codecov

A high performance gin middleware to cache http response. Compared to gin 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.

How To Use

Install

go get -u github.com/wyy-go/wcache

Example

Cache In Local Memory
package main

import (
	"github.com/wyy-go/wcache/persist/memory"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/wyy-go/wcache"
)

func main() {
	app := gin.New()

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

	app.GET("/hello",
		wcache.CacheByRequestURI(
			wcache.WithCacheStore(memoryStore),
			wcache.WithExpire(2*time.Second),
			wcache.WithHandle(func(c *gin.Context) {
				c.String(200, "hello world")
			})),
	)

	if err := app.Run(":8080"); err != nil {
		panic(err)
	}
}
Cache In Redis
package main

import (
	redisStore "github.com/wyy-go/wcache/persist/redis"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"github.com/wyy-go/wcache"
)

func main() {
	app := gin.New()

	store := redisStore.NewRedisStore(redis.NewClient(&redis.Options{
		Network: "tcp",
		Addr:    "127.0.0.1:6379",
		DB:      0,
	}))

	app.GET("/hello",
		wcache.CacheByRequestURI(
			wcache.WithCacheStore(store),
			wcache.WithExpire(2*time.Second),
			wcache.WithHandle(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

View Source
var PageCachePrefix = "wcache.page.cache:"

PageCachePrefix default page cache key prefix

Functions

func Cache

func Cache(opts ...Option) gin.HandlerFunc

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

func CacheByRequestPath

func CacheByRequestPath(opts ...Option) gin.HandlerFunc

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

func CacheByRequestURI

func CacheByRequestURI(opts ...Option) gin.HandlerFunc

CacheByRequestURI a shortcut function for caching response by uri

func CacheKeyWithPrefix

func CacheKeyWithPrefix(prefix, key string) string

func GenerateCacheKeyByPath

func GenerateCacheKeyByPath(c *gin.Context) (string, bool)

GenerateCacheKeyByPath generate key with PageCachePrefix and request Path

func GenerateCacheKeyByURI

func GenerateCacheKeyByURI(c *gin.Context) (string, bool)

GenerateCacheKeyByURI generate key with PageCachePrefix and request uri

Types

type Discard

type Discard struct {
}

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

func NewDiscard

func NewDiscard() Discard

NewDiscard a discard logger on which always succeed without doing anything

func (Discard) DPanicf

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

DPanicf implement Logger interface.

func (Discard) Debugf

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

Debugf implement Logger interface.

func (Discard) Errorf

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

Errorf implement Logger interface.

func (Discard) Fatalf

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

Fatalf implement Logger interface.

func (Discard) Infof

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

Infof implement Logger interface.

func (Discard) Warnf

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

Warnf implement Logger interface.

type Encoding

type Encoding interface {
	Marshal(v interface{}) ([]byte, error)
	Unmarshal(data []byte, v interface{}) error
}

Encoding interface

type GenerateCacheKey

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

type JSONEncoding

type JSONEncoding struct{}

func (JSONEncoding) Marshal

func (JSONEncoding) Marshal(v interface{}) ([]byte, error)

func (JSONEncoding) Unmarshal

func (JSONEncoding) Unmarshal(data []byte, v interface{}) error

type JSONGzipEncoding

type JSONGzipEncoding struct{}

func (JSONGzipEncoding) Marshal

func (JSONGzipEncoding) Marshal(v interface{}) ([]byte, error)

func (JSONGzipEncoding) Unmarshal

func (JSONGzipEncoding) Unmarshal(data []byte, v interface{}) error

type Logger

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

Logger define the logger interface

type OnHitCacheCallback

type OnHitCacheCallback func(c *gin.Context)

OnHitCacheCallback define the callback when use cache

type OnShareSingleFlightCallback

type OnShareSingleFlightCallback func(c *gin.Context)

OnShareSingleFlightCallback define the callback when share the singleflight result

type Option

type Option func(c *Options)

Option represents the optional function.

func WithCacheStore

func WithCacheStore(store persist.CacheStore) Option

func WithEncoding

func WithEncoding(encode Encoding) Option

func WithExpire

func WithExpire(expire time.Duration) Option

func WithGenerateCacheKey

func WithGenerateCacheKey(f GenerateCacheKey) Option

func WithHandle

func WithHandle(handle gin.HandlerFunc) Option

func WithLogger

func WithLogger(l Logger) Option

WithLogger set the custom logger

func WithOnHitCache

func WithOnHitCache(cb OnHitCacheCallback) Option

WithOnHitCache will be called when cache hit.

func WithOnShareSingleFlight

func WithOnShareSingleFlight(cb OnShareSingleFlightCallback) Option

WithOnShareSingleFlight will be called when share the singleflight result

func WithPool

func WithPool(pool Pool) Option

func WithRand

func WithRand(rand Rand) Option

func WithSingleFlightForgetTimeout

func WithSingleFlightForgetTimeout(forgetTimeout time.Duration) Option

WithSingleFlightForgetTimeout to reduce the impact of long tail requests. when request in the singleflight, after the forget timeout, singleflight.Forget will be called

func WithSingleflight

func WithSingleflight(group *singleflight.Group) Option

type Options

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

Options contains all options

type Pool

type Pool interface {
	Get() *ResponseCache
	Put(*ResponseCache)
}

func NewPool

func NewPool() Pool

NewPool new pool for responseCache

type Rand

type Rand func() time.Duration

type ResponseCache

type ResponseCache struct {
	Status int
	Header http.Header
	Data   []byte
	// contains filtered or unexported fields
}

func (*ResponseCache) MarshalBinary

func (c *ResponseCache) MarshalBinary() ([]byte, error)

func (*ResponseCache) UnmarshalBinary

func (c *ResponseCache) UnmarshalBinary(data []byte) error

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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