cache

package module
v0.0.0-...-3301c0c Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2023 License: MIT Imports: 17 Imported by: 0

README

echo-http-cache

This is a high performance Golang HTTP middleware for server-side application layer caching, ideal for REST APIs, using Echo framework. It is simple, superfast, thread safe and gives the possibility to choose the adapter (memory, Redis).

Getting Started

Installation (Go Modules)

go get github.com/coinpaprika/echo-http-cache

Usage

Full example is available at example can be run by:

go run ./example/main.go

Example of use with the memory adapter:

package main

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

	cache "github.com/coinpaprika/echo-http-cache"
	"github.com/coinpaprika/echo-http-cache/adapter/memory"
	"github.com/labstack/echo/v4"
)

func main() {
	memoryAdapter, err := memory.NewAdapter(
		// after reaching the capacity, items are not cached 
		// until the next cleaning goroutine makes the space
		// this is a protection against cache pollution attacks
		memory.WithCapacity(10_000),  
	) 
	if err != nil {
		log.Fatal(err)
	}

	cacheClient, err := cache.NewClient(
		cache.ClientWithAdapter(memoryAdapter),
		cache.ClientWithTTL(10*time.Minute),
		cache.ClientWithRefreshKey("opn"),
	)
	if err != nil {
		log.Fatal(err)
	}

	e := echo.New()
	e.Use(cacheClient.Middleware())
	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "OK")
	})
	e.Start(":8080")
}

Example of Client initialization with REDIS adapter:

import (
    "github.com/coinpaprika/echo-http-cache"
    "github.com/coinpaprika/echo-http-cache/adapter/redis"
)

...

    ringOpt := &redis.RingOptions{
        Addrs: map[string]string{
            "server": ":6379",
        },
    }
    cacheClient := cache.NewClient(
        cache.ClientWithAdapter(redis.NewAdapter(ringOpt)),
        cache.ClientWithTTL(10 * time.Minute),
        cache.ClientWithRefreshKey("opn"),
    )
...

Example of Client initialization with disk based adapter using diskv:

import (
    "github.com/coinpaprika/echo-http-cache"
    "github.com/coinpaprika/echo-http-cache/adapter/disk"
)

...
    cacheClient := cache.NewClient(
        // leave empty for default directory './cache'. Directory will be created if not exist.
        cache.ClientWithAdapter(disk.NewAdapter(disk.WithDirectory("./tmp/cache"), disk.WithMaxMemorySize(50_000_000))), 
        cache.ClientWithTTL(10 * time.Minute),
        cache.ClientWithRefreshKey("opn"),
    )

Adapters selection guide

Memory
  • local environments
  • high cache hit ratio
  • production single & multi node environments
  • short-lived objects < 3min
  • cheap underlying operations' avg(exec time) < 300ms
  • low number of entries: < 1M & < 1Gb in size
  • memory safe (when used with WithCapacity option)
Disk
  • SSD disks
  • high cache hit ratio
  • production single & multi node environments
  • short-lived to medium-lived objects < 12hr
  • cheap underlying operations' avg(exec time) < 300ms
  • always memory safe, disk space is used extensively
  • some entries are cached in memory for performance - controlled by WithMaxMemorySize() settings, default 100Mb
  • large number of entries > 1M & > 1 Gb in size (up to full size of a disk)
Redis
  • production multi node environments
  • low to high cache hit ratio
  • short-lived to long-lived objects > 10 min
  • expensive underlying operations' avg(exec time) > 300ms, benefit from sharing across multi nodes
  • large number of entries > 1M & >1 Gb in size (up to full size of a disk)

License

echo-http-cache is released under the MIT License.

Forked from:

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func KeyAsString

func KeyAsString(key uint64) string

KeyAsString can be used by adapters to convert the cache key from uint64 to string.

Types

type Adapter

type Adapter interface {
	// Get retrieves the cached response by a given key. It also
	// returns true or false, whether it exists or not.
	Get(key uint64) ([]byte, bool)

	// Set caches a response for a given key until an expiration date.
	Set(key uint64, response []byte, expiration time.Time) error

	// Release frees cache for a given key.
	Release(key uint64) error
}

Adapter interface for HTTP cache middleware client.

type Client

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

Client data structure for HTTP cache middleware.

func NewClient

func NewClient(opts ...ClientOption) (*Client, error)

NewClient initializes the cache HTTP middleware client with the given options.

func (*Client) Middleware

func (client *Client) Middleware() echo.MiddlewareFunc

Middleware is the HTTP cache middleware handler.

type ClientOption

type ClientOption func(c *Client) error

ClientOption is used to set Client settings.

func ClientWithAdapter

func ClientWithAdapter(a Adapter) ClientOption

ClientWithAdapter sets the adapter type for the HTTP cache middleware client.

func ClientWithMethods

func ClientWithMethods(methods []string) ClientOption

ClientWithMethods sets the acceptable HTTP methods to be cached. Optional setting. If not set, default is "GET".

func ClientWithRefreshKey

func ClientWithRefreshKey(refreshKey string) ClientOption

ClientWithRefreshKey sets the parameter key used to free a request cached response. Optional setting.

func ClientWithRestrictedPaths

func ClientWithRestrictedPaths(paths []string) ClientOption

ClientWithRestrictedPaths sets the restricted HTTP paths for caching. Optional setting.

func ClientWithTTL

func ClientWithTTL(ttl time.Duration) ClientOption

ClientWithTTL sets how long each response is going to be cached.

type Response

type Response struct {
	// Value is the cached response value.
	Value []byte

	// Header is the cached response header.
	Header http.Header

	// Expiration is the cached response expiration date.
	Expiration time.Time

	// LastAccess is the last date a cached response was accessed.
	// Used by LRU and MRU algorithms.
	LastAccess time.Time

	// Frequency is the count of times a cached response is accessed.
	// Used for LFU and MFU algorithms.
	Frequency int
}

Response is the cached response data structure.

func BytesToResponse

func BytesToResponse(b []byte) Response

BytesToResponse converts bytes array into Response data structure.

func (Response) Bytes

func (r Response) Bytes() []byte

Bytes converts Response data structure into bytes array.

Directories

Path Synopsis
adapter

Jump to

Keyboard shortcuts

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