loader

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2020 License: MIT Imports: 4 Imported by: 1

README

cache-loader

GitHub tag (latest SemVer) go.dev reference Go codecov

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

func InMemoryCache added in v0.1.1

func InMemoryCache() Cache

type LRUCache added in v0.1.1

type LRUCache struct {
	*lru.Cache
}

LRUCache wraps hashicorp's lru cache object, so it's compatible with loader cache

func (*LRUCache) Add added in v0.1.1

func (c *LRUCache) Add(key, value interface{})

Add item to cache

func (*LRUCache) Remove added in v0.1.1

func (c *LRUCache) Remove(key interface{})

Remove item from cache

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