loader

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2020 License: MIT Imports: 3 Imported by: 1

README

cache-loader

Golang Cache Loader

Feature

  • Thread safe
  • Fetch once even when concurrent process request same key.
  • stale-while-revalidate when item is expired

Example

func main() {
  itemLoader := loader.NewLRU(fetchItem, 5 * time.Minute, 1000)
  item, err := loader.Get("key")
  // use item
}

func fetchItem(key interface{}) (interface{}, error) {
  res, err := http.Get("https://example.com/item/" + key)
  if err != nil {
    return nil, err
  }
  return processResponse(res)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache interface {
	Add(key, value interface{})
	Get(key interface{}) (value interface{}, ok bool)
	Remove(key interface{})
}

Cache stores the items you can use ARCCache or TwoQueueCache from github.com/hashicorp/golang-lru

type LoadFunc

type LoadFunc func(key interface{}) (interface{}, error)

LoadFunc loads the value based on key

type Loader

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

Loader manage items in cache and fetch them if not exist

func New

func New(fn LoadFunc, ttl time.Duration, cache Cache) *Loader

New creates new Loader

func NewLRU

func NewLRU(fn LoadFunc, ttl time.Duration, size int) *Loader

NewLRU creates Loader with lru based cache

func (*Loader) Get

func (l *Loader) Get(key interface{}) (interface{}, error)

Get the item. If it doesn't exist on cache, Loader will call LoadFunc once even when other go routine access the same key. If the item is expired, it will return old value while loading new one.

Jump to

Keyboard shortcuts

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