sfcache

package module
v0.0.0-...-0b05bc0 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2021 License: MIT Imports: 5 Imported by: 0

README

sfcache

This is a caching and cache-filling library with the ability to set expire times on values.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/silas/sfcache"
)

func main() {
	loader := func(ctx context.Context, key interface{}) (interface{}, time.Time, error) {
		value := fmt.Sprintf("%s-%d", key, time.Now().Unix())
		expireTime := time.Now().Add(3 * time.Second)
		return value, expireTime, nil
	}

	c, err := sfcache.New(100, loader)
	if err != nil {
		panic(err)
	}

	for i := 0; i < 10; i++ {
		v, err := c.Load(context.Background(), "foo")
		if err != nil {
			panic(err)
		}

		fmt.Println(v)

		time.Sleep(time.Second)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned when Loader returns a nil or expired value.
	ErrNotFound = errors.New("cache entry not found")

	// NoExpireTime disables expire time for a given value.
	NoExpireTime time.Time

	// NoValue is a value a Loader can return to cache a nil.
	NoValue noValue = struct{}{}
)

Functions

This section is empty.

Types

type Cache

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

Cache is an LRU cache with cache filling functionality.

func New

func New(size int, load Loader) (*Cache, error)

New creates an LRU cache with the given size and loader.

func (*Cache) Delete

func (c *Cache) Delete(key interface{}) bool

Delete removes the provided key from the cache.

func (*Cache) Get

func (c *Cache) Get(key interface{}) (interface{}, bool)

Get looks up a key's value from the cache.

func (*Cache) Load

func (c *Cache) Load(ctx context.Context, key interface{}) (interface{}, error)

Load looks up a key's value from the cache or populates it from Loader if not found.

func (*Cache) Peek

func (c *Cache) Peek(key interface{}) (interface{}, bool)

Peek returns the key's value (or nil if not found) without updating the "recently used"-ness of the key.

func (*Cache) Set

func (c *Cache) Set(key interface{}, value interface{}, expireTime time.Time) bool

Set sets a value to the cache. Returns false if expired or value is nil.

type Loader

type Loader func(ctx context.Context, key interface{}) (interface{}, time.Time, error)

Loader gets data to populate the cache, returning the value and expire time.

Directories

Path Synopsis
internal
singleflight
Package singleflight provides a duplicate function call suppression mechanism.
Package singleflight provides a duplicate function call suppression mechanism.

Jump to

Keyboard shortcuts

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