multicacheadapters

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2023 License: Apache-2.0 Imports: 8 Imported by: 0

README

GitHub go.mod Go version go.dev reference Go Report Card GitHub Twitter Follow

Multi Cache Adapter implementation

A CacheAdapter implementation that allows to connect and use multiple adapters at the same time.

Features

  • Allows the creation of fallback cache logics, allowing to reach different cache types if one of them is failing for any reason
  • Allows, optionally, to track partial failures as warnings, so you can log them using your preferred method

Usage

Since MultiCacheAdapter and MultiCacheSessionAdapter implement the respective interfaces (CacheAdapter and CacheSessionAdapter) you have all the methods at your disposal.

Please refer to the following example for the correct usage:

package main

import (
	"log"
	"time"

	"github.com/gomodule/redigo/redis"
	cacheadapters "github.com/tryvium-travels/golang-cache-adapters"
	rediscacheadapters "github.com/tryvium-travels/golang-cache-adapters/redis"
	multicacheadapters "github.com/tryvium-travels/golang-cache-adapters/multicache"
)

func main() {
	// Ideally you would want to use 2 DIFFERENT cache types
	// for the sake of the simplicity, we will just create 2
	// adapters of the same type.

	redisURI1 := "rediss://my-redis-instance-uri1:port"
	redisURI2 := "rediss://my-redis-instance-uri2:port"

	myRedisPool1 := &redis.Pool{
		Dial: func() (redis.Conn, error) {
			// obtain a redis connection, there
			// are plenty of ways to do that.
			return redis.DialURL(redisURI1)
		},
	}

	myRedisPool2 := &redis.Pool{
		Dial: func() (redis.Conn, error) {
			// obtain a redis connection, there
			// are plenty of ways to do that.
			return redis.DialURL(redisURI2)
		},
	}

	exampleTTL := time.Hour

	// first we create the adapters.
	redisAdapter1, err := rediscacheadapters.New(myRedisPool1, exampleTTL)
	if err != nil {
		// remember to check for errors
		log.Fatalf("Redis Adapter 1 initialization error: %s", err)
	}

	redisAdapter2, err := rediscacheadapters.New(myRedisPool1, exampleTTL)
	if err != nil {
		// remember to check for errors
		log.Fatalf("Redis Adapter 2 initialization error: %s", err)
	}

	// then we create a MultiCacheAdapter to use them at the same time.
	adapter, err := multicacheadapters.New(redisAdapter1, redisAdapter2)
	if err != nil {
		// remember to check for errors
		log.Fatalf("Multi Cache Adapter 2 initialization error: %s", err)
	}

	type exampleStruct struct {
		Value string
	}

	exampleKey := "a:redis:key"

	var exampleValue exampleStruct
	err = adapter.Get(exampleKey, &exampleValue)
	if err != nil {
		// remember to check for errors
		log.Fatalf("adapter.Get error: %s", err)
	}

	exampleKey = "another:redis:key"

	// nil TTL represents the default value put in the New function
	err = adapter.Set(exampleKey, exampleValue, nil)
	if err != nil {
		// remember to check for errors
		log.Fatalf("adapter.Get error: %s", err)
	}
}

Documentation

Overview

Package multicacheadapters contains the implementations of CacheAdapter and CacheSessionAdapter with the objective of accessing multiple cache sources with fallback support.

Just use this adapter and when a cache source errors, it will automatically perform the operations on other sources.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidSubAdapters will come out if you try to pass one or more nil
	// sub-adapters when creating a new MultiCacheAdapter or a session.
	ErrInvalidSubAdapters = fmt.Errorf("you must pass at least one valid sub-adapter")
	// ErrMultiCacheWarning will come out paired with other errors in case
	// an non-fatal error occurs during a multicache operation.
	//
	// This includes for example when a GET operation fails on the first
	// adapter but is successful in the second adapter.
	ErrMultiCacheWarning = fmt.Errorf("warning when performing an operation with a multicache adapter")
)

Functions

This section is empty.

Types

type MultiCacheAdapter

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

MultiCacheAdapter is a cache adapter which uses multiple sub-adapters, following a priority given by the index of the adapter in the inner array of adapters.

func New

New creates a new multi cache adapter from an index-based priority array of cache adapters (called sub-adapters) and a flag instructing to show warning (non-fatal) errors.

index-based means that the array at the first position(s) will
have more priority than those at latter positions.

func (*MultiCacheAdapter) Delete

func (mca *MultiCacheAdapter) Delete(key string) error

Delete deletes a key from the cache.

func (*MultiCacheAdapter) DisableWarnings

func (mca *MultiCacheAdapter) DisableWarnings()

DisableWarning disables the return of warning errors.

If the error is a warning, you can continue standard execution as The operations concluded successfully. You can then log the warning using your favourite tool (like sentry).

Warning errors, if shown need different handling from traditional
errors. Use the helper IsWarning(error err) to check for warnings.

Example of handling of warnings:

    err := adapter.Get("key", &objRef)
    if (errors.Is(cacheadapter.ErrWarning)) {
	       // log the error, but use objRef safely
    } else if err != nil {
        // log the error and handle a failure
        // you cannot use objRef safely here
    }
    // else use objRef safely without any error

func (*MultiCacheAdapter) EnableWarnings

func (mca *MultiCacheAdapter) EnableWarnings()

EnableWarning enable the return of warning errors.

If the error is a warning, you can continue standard execution as The operations concluded successfully. You can then log the warning using your favourite tool (like sentry).

Warning errors, if shown need different handling from traditional
errors. Use the helper IsWarning(error err) to check for warnings.

Example of handling of warnings:

    err := adapter.Get("key", &objRef)
    if (cacheadapters.IsWarning(err)) {
	       // log the error, but use objRef safely
    } else if err != nil {
        // log the error and handle a failure
        // you cannot use objRef safely here
    }
    // else use objRef safely without any error

func (*MultiCacheAdapter) Get

func (mca *MultiCacheAdapter) Get(key string, objectRef interface{}) error

Get obtains a value from the cache using a key, then tries to unmarshal it into the object reference passed as parameter.

func (*MultiCacheAdapter) OpenSession

func (*MultiCacheAdapter) Set

func (mca *MultiCacheAdapter) Set(key string, object interface{}, TTL *time.Duration) error

Set sets a value represented by the object parameter into the cache, with the specified key.

func (*MultiCacheAdapter) SetTTL

func (mca *MultiCacheAdapter) SetTTL(key string, newTTL time.Duration) error

SetTTL marks the specified key new expiration, deletes it via using cacheadapters.TTLExpired or negative duration.

type MultiCacheSessionAdapter

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

MultiCacheSessionAdapter is a cache adapter which uses multiple sub-adapters, following a priority given by the index of the adapter in the inner array of adapters.

func NewSession

NewSession creates a new multi cache session adapter from an index-based priority array of cache adapters (called sub-adapters) and a flag instructing to show warning (non-fatal) errors.

index-based means that the array at the first position(s) will
have more priority than those at latter positions.

func (*MultiCacheSessionAdapter) Close

func (mcsa *MultiCacheSessionAdapter) Close() error

Close closes the Cache Sessions.

func (*MultiCacheSessionAdapter) Delete

func (mcsa *MultiCacheSessionAdapter) Delete(key string) error

Delete deletes a key from the cache.

func (*MultiCacheSessionAdapter) DisableWarnings

func (mcsa *MultiCacheSessionAdapter) DisableWarnings()

DisableWarning disables the return of warning errors.

If the error is a warning, you can continue standard execution as The operations concluded successfully. You can then log the warning using your favourite tool (like sentry).

Warning errors, if shown need different handling from traditional
errors. Use the helper IsWarning(error err) to check for warnings.

Example of handling of warnings:

    err := adapter.Get("key", &objRef)
    if (errors.Is(cacheadapter.ErrWarning)) {
	       // log the error, but use objRef safely
    } else if err != nil {
        // log the error and handle a failure
        // you cannot use objRef safely here
    }
    // else use objRef safely without any error

func (*MultiCacheSessionAdapter) EnableWarnings

func (mcsa *MultiCacheSessionAdapter) EnableWarnings()

EnableWarning enable the return of warning errors.

If the error is a warning, you can continue standard execution as The operations concluded successfully. You can then log the warning using your favourite tool (like sentry).

Warning errors, if shown need different handling from traditional
errors. Use the helper IsWarning(error err) to check for warnings.

Example of handling of warnings:

    err := adapter.Get("key", &objRef)
    if (cacheadapters.IsWarning(err)) {
	       // log the error, but use objRef safely
    } else if err != nil {
        // log the error and handle a failure
        // you cannot use objRef safely here
    }
    // else use objRef safely without any error

func (*MultiCacheSessionAdapter) Get

func (mcsa *MultiCacheSessionAdapter) Get(key string, objectRef interface{}) error

Get obtains a value from the cache using a key, then tries to unmarshal it into the object reference passed as parameter.

func (*MultiCacheSessionAdapter) Set

func (mcsa *MultiCacheSessionAdapter) Set(key string, object interface{}, TTL *time.Duration) error

Set sets a value represented by the object parameter into the cache, with the specified key.

func (*MultiCacheSessionAdapter) SetTTL

func (mcsa *MultiCacheSessionAdapter) SetTTL(key string, newTTL time.Duration) error

SetTTL marks the specified key new expiration, deletes it via using cacheadapters.TTLExpired or negative duration.

Jump to

Keyboard shortcuts

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