Help us shape the future of Go! Take the 2026 Go Developer Survey

cache

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package cache keeps one value read from the database in memory for a short time. Writes in this process invalidate it at once; writes by other processes show up when the time to live has passed.

Reading is lock free: a hit costs two atomic loads. A value loaded while a write invalidated the cache is never kept, because every entry remembers the generation it was loaded in.

Index

Constants

View Source
const DefaultTTL = 30 * time.Second

DefaultTTL is how long a value is reused when nothing else is configured.

Variables

This section is empty.

Functions

This section is empty.

Types

type Value

type Value[T any] struct {
	// contains filtered or unexported fields
}

Value caches the result of a load function. The zero value caches for DefaultTTL; it is safe for concurrent use.

func (*Value[T]) Generation

func (v *Value[T]) Generation() uint64

Generation counts the invalidations (see Invalidate): it changes with every write in this process, and only goes up, so what is made from the value, such as a rendered page, can be kept with the generation it was made at and made again once it moved on. Values loaded again when the time to live has passed do not change it.

func (*Value[T]) Get

func (v *Value[T]) Get(ctx context.Context, load func(context.Context) (T, error)) (T, error)

Get returns the cached value, or loads and keeps a new one. Inside a transaction it always loads and keeps nothing: the transaction must see its own changes, which are not committed and so not in the cache, and others must not see them before the commit.

func (*Value[T]) Invalidate

func (v *Value[T]) Invalidate()

Invalidate drops the cached value; call it after every committed write.

func (*Value[T]) SetClock

func (v *Value[T]) SetClock(now func() time.Time)

SetClock replaces the clock that decides when values expire, so tests can move time forward instead of sleeping. Call it before the value is used.

func (*Value[T]) SetTTL

func (v *Value[T]) SetTTL(ttl time.Duration)

SetTTL changes how long values are kept; zero or less disables caching.

Jump to

Keyboard shortcuts

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