httpcache

package module
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: May 16, 2022 License: Apache-2.0 Imports: 10 Imported by: 0

README

Krakend HTTP Cache

A cached http client for the KrakenD framework tested on krakend-ce 1.4.1

Using it

This package exposes two simple factories capable to create a instances of the proxy.HTTPClientFactory and the proxy.BackendFactory interfaces, respectively, embedding an in-memory-cached http client using the package github.com/gregjones/httpcache. The client will cache the responses honoring the defined Cache HTTP header.

import 	(
	"context"
	"net/http"
	"github.com/luraproject/lura/config"
	"github.com/luraproject/lura/proxy"
	"github.com/devopsfaith/krakend-httpcache"
)

requestExecutorFactory := func(cfg *config.Backend) proxy.HTTPRequestExecutor {
	clientFactory := httpcache.NewHTTPClient(cfg)
	return func(ctx context.Context, req *http.Request) (*http.Response, error) {
		return clientFactory(ctx).Do(req.WithContext(ctx))
	}
}

You can create your own proxy.HTTPRequestExecutor and inject it into your BackendFactory

Lean changes

Modified added support to redis & redis-cluster as cache backends.

Backend extra configuration block example with default values:

"backend": [
{
    "extra_config": {
        "github.com/devopsfaith/krakend-httpcache": {
            "type": "redis",
            "redis": {
                "mode": "redis",
                "address": "localhost:6379",
                "dialTimeout": "100ms",
                "readTimeout": "100ms",
                "writeTimeout": "200ms",
                "maxRetries": 0,
                "idleTimeout": "5m",
                "idleCheckFrequency": "1m",
                "poolSize": 10,
                "poolTimeout": "10ms",
                "ttl": "1h",
            }
        },
    }
}

Config options:

  • type (optional, if missing memory will be used for an inmemory cache): memory | redis

redis block is required if type is set to redis:

  • mode (required): redis or rediscluster
  • address (required): Address to the redis node or one of the redis nodes when using a cluster. Format: ip:port
  • ttl: TTL to be used on all redis keys being set. Redis will expire the keys after this time. This value is independent from the Cache-Control header that the library will use to decide if the cached value is still valid or not.

Check the description of the following options in the go-redis package documentation: https://github.com/go-redis/redis

  • dialTimeout:
  • readTimeout:
  • writeTimeout:
  • maxRetries:
  • idleTimeout:
  • idleCheckFrequency:
  • poolSize:
  • poolTimeout:

How to build into krakend

We need to recompile kraken-cd in order to interpret new redis config schema

Edit krakend-ce go.mod file and in the requires section add

require (
    github.com/leandroreox/krakend-rediscache v1.0
)

And at the end of the go.mod file add a replace sentence

replace github.com/devopsfaith/krakend-httpcache v1.4.0 => github.com/leandroreox/krakend-rediscache v1.0

re-build krakend-ce, and run it !

Documentation

Overview

Package httpcache introduces an in-memory-cached http client into the KrakenD stack

Index

Constants

View Source
const (
	Namespace = "github.com/devopsfaith/krakend-httpcache"

	BackendMemory = "memory"
	BackendRedis  = "redis"

	RedisModeRedis                 = "redis"
	RedisModeCluster               = "rediscluster"
	RedisDefaultDialTimeout        = 100 * time.Millisecond
	RedisDefaultReadTimeout        = 100 * time.Millisecond
	RedisDefaultWriteTimeout       = 200 * time.Millisecond
	RedisDefaultMaxRetries         = 0
	RedisDefaultIdleTimeout        = 5 * time.Minute
	RedisDefaultIdleCheckFrequency = 1 * time.Minute
	RedisDefaultPoolSize           = 10
	RedisDefaultPoolTimeout        = 10 * time.Millisecond
	RedisDefaultTtl                = 1 * time.Hour
)

Variables

View Source
var ErrInvalidValue = func(field string) error {
	return errors.New(fmt.Sprintf("Invalid value for krakend-httpcache config field [%s]", field))
}
View Source
var ErrMappingConfig = errors.New("could not map krakend-httpcache config")
View Source
var ErrMissingRequired = func(field string) error {
	return errors.New(fmt.Sprintf("Missing required krakend-httpcache config field [%s]", field))
}
View Source
var WarnNoConfig = errors.New("no config found for krakend-httpcache")

Functions

func BackendFactory

func BackendFactory(cfg *config.Backend) proxy.BackendFactory

BackendFactory returns a proxy.BackendFactory that creates backend proxies using an in-memory-cached http client

func ConfigGetter

func ConfigGetter(cfg *config.Backend) (interface{}, error)

func NewHTTPClient

func NewHTTPClient(cfg *config.Backend) client.HTTPClientFactory

NewHTTPClient creates a HTTPClientFactory using an in-memory-cached http client

func NewRedisCacheTransport

func NewRedisCacheTransport(c Cache) *httpcache.Transport

Types

type Cache

type Cache interface {
	httpcache.Cache
}

type Client

type Client interface {
	redis.Cmdable
}

func NewRedis

func NewRedis(cfg RedisConfig) Client

func NewRedisCluster

func NewRedisCluster(cfg RedisConfig) Client

type Config

type Config struct {
	Type        string
	RedisConfig RedisConfig
}

type RedisCache

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

func NewRedisCache

func NewRedisCache(client Client, ttl time.Duration) *RedisCache

func (*RedisCache) Delete

func (c *RedisCache) Delete(key string)

func (*RedisCache) Get

func (c *RedisCache) Get(key string) (responseBytes []byte, ok bool)

func (*RedisCache) Set

func (c *RedisCache) Set(key string, responseBytes []byte)

type RedisConfig

type RedisConfig struct {
	Mode               string
	Address            string
	DialTimeout        time.Duration
	ReadTimeout        time.Duration
	WriteTimeout       time.Duration
	MaxRetries         int
	IdleTimeout        time.Duration
	IdleCheckFrequency time.Duration
	PoolSize           int
	PoolTimeout        time.Duration
	Ttl                time.Duration
}

Jump to

Keyboard shortcuts

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