cache

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 2 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Examples

Constants

View Source
const NoExpiry time.Duration = -1

NoExpiry, passed as Config.DefaultTTL, means the cache never expires entries: NewOtterCache constructs the underlying Otter cache without any expiry policy at all (Otter's native no-expiration mode), rather than simulating "permanent" with some very long duration.

In this mode, Set's expire parameter has no effect on any key, silently (not an error): Otter's SetExpiresAfter is a no-op whenever the cache itself wasn't configured with an expiry policy, regardless of what's passed for an individual key. Otter's "which keys can have a TTL at all" is an all-or-nothing, cache-wide setting, not a per-key one — so a single cache can't mix "most keys are permanent" with "this one key really does expire". Construct a second OtterCache with a real DefaultTTL if both are needed side by side.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// MaxSize is the maximum number of entries before the W-TinyLFU
	// admission policy starts evicting to make room for new keys — this
	// applies regardless of DefaultTTL; even a NoExpiry cache can still
	// evict entries under capacity pressure, just never due to TTL.
	// Zero-value: 10,000.
	MaxSize int

	// DefaultTTL is the TTL applied the first time a key is created via Set
	// with expire <= 0 (re-Set/Update on an already-existing key never
	// resets it - see the package doc). Zero-value: 1 hour.
	//
	// Set to NoExpiry to disable expiry entirely for this cache instance —
	// entries are then only ever removed by Delete/Clear/capacity eviction,
	// never by TTL, and Set's expire parameter stops having any effect for
	// every key (see NoExpiry's doc comment).
	DefaultTTL time.Duration
}

Config holds NewOtterCache's configuration. Zero-value fields fall back to the package defaults above.

type ICache

type ICache interface {
	// Get retrieves the value for key. Returns the value and true if found, otherwise nil and false.
	Get(key string) (interface{}, bool)
	// Set stores value under key with the given TTL. A non-positive expire means use the default TTL.
	Set(key string, value interface{}, expire time.Duration) error
	// Update replaces the value of an existing key without altering its expiry.
	Update(key string, value interface{}) error
	// Keys returns all keys currently present in the cache.
	Keys() []interface{}
	// Values returns all values currently stored in the cache.
	Values() []interface{}
	// Delete removes the entry identified by key from the cache.
	Delete(key string) error
	// Size returns the number of entries currently held in the cache.
	Size() int
	// Clear removes all entries from the cache.
	Clear() error
}

ICache defines a generic key-value cache interface with optional TTL support. All implementations must be safe for concurrent use.

func NewOtterCache

func NewOtterCache(cfg ...Config) ICache

NewOtterCache creates a new OtterCache instance. cfg is optional: omit it for the package defaults (capacity 10,000, default TTL 1 hour), or pass one Config to customize capacity and/or the default TTL — including Config.DefaultTTL: NoExpiry for a cache that never expires entries.

Example

ExampleNewOtterCache shows how to create an in-process cache and perform a basic Set / Get round trip. A zero (or negative) expire means "use the cache's default TTL" rather than "never expire" — see ExampleOtterCache_Set.

package main

import (
	"fmt"

	"github.com/phcp-tech/common-library-golang/cache"
)

func main() {
	c := cache.NewOtterCache()
	_ = c.Set("EURUSD", 10500, 0)

	val, ok := c.Get("EURUSD")
	fmt.Println(val, ok)
}
Output:
10500 true
Example (Config)

ExampleNewOtterCache_config shows customizing capacity and the default TTL. Config is optional — omit it entirely (as in ExampleNewOtterCache) for capacity 10,000 and a 1-hour default TTL.

package main

import (
	"fmt"
	"time"

	"github.com/phcp-tech/common-library-golang/cache"
)

func main() {
	c := cache.NewOtterCache(cache.Config{
		MaxSize:    500,
		DefaultTTL: 10 * time.Minute,
	})
	_ = c.Set("EURUSD", 10500, 0) // expire<=0 -> uses this cache's 10-minute default

	val, ok := c.Get("EURUSD")
	fmt.Println(val, ok)
}
Output:
10500 true
Example (NoExpiry)

ExampleNewOtterCache_noExpiry shows building a cache that never expires entries. In this mode Set's expire parameter has no effect on any key — see cache.NoExpiry's doc comment for why a single cache can't mix permanent keys with keys that really do expire.

package main

import (
	"fmt"
	"time"

	"github.com/phcp-tech/common-library-golang/cache"
)

func main() {
	c := cache.NewOtterCache(cache.Config{DefaultTTL: cache.NoExpiry})

	_ = c.Set("config:feature-flags", "enabled", 0)     // never expires
	_ = c.Set("also-permanent", "value", 5*time.Minute) // expire is ignored: also never expires

	val, ok := c.Get("config:feature-flags")
	fmt.Println(val, ok)
}
Output:
enabled true

type OtterCache

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

OtterCache is a high-performance in-process cache backed by the Otter library. It implements the ICache interface and supports TTL-based expiry.

func (*OtterCache) Clear

func (c *OtterCache) Clear() error

Clear removes all entries from the cache. It always returns nil.

Example

ExampleOtterCache_Clear shows removing every entry at once.

package main

import (
	"fmt"

	"github.com/phcp-tech/common-library-golang/cache"
)

func main() {
	c := cache.NewOtterCache()
	_ = c.Set("a", 1, 0)
	_ = c.Set("b", 2, 0)
	_ = c.Clear()

	fmt.Println(c.Size())
}
Output:
0

func (*OtterCache) Delete

func (c *OtterCache) Delete(key string) error

Delete removes the entry identified by key from the cache. It always returns nil.

Example

ExampleOtterCache_Delete shows removing an entry; Get on the deleted key afterwards reports a miss.

package main

import (
	"fmt"

	"github.com/phcp-tech/common-library-golang/cache"
)

func main() {
	c := cache.NewOtterCache()
	_ = c.Set("temp", "value", 0)
	_ = c.Delete("temp")

	_, ok := c.Get("temp")
	fmt.Println(ok)
}
Output:
false

func (*OtterCache) Get

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

Get retrieves the value associated with key from the cache. It returns the value and true if the key exists, or nil and false otherwise.

Example

ExampleOtterCache_Get shows Get on a key that was never set: it returns (nil, false) rather than panicking or returning a zero value of some concrete type — the cache stores values as interface{}.

package main

import (
	"fmt"

	"github.com/phcp-tech/common-library-golang/cache"
)

func main() {
	c := cache.NewOtterCache()
	val, ok := c.Get("missing")
	fmt.Println(val, ok)
}
Output:
<nil> false

func (*OtterCache) Keys

func (c *OtterCache) Keys() []interface{}

Keys returns a snapshot of all keys currently present in the cache.

Example

ExampleOtterCache_Keys shows listing every key currently stored. Only one key is inserted here because Keys' traversal order over multiple entries is not guaranteed (like Go's own map iteration) — sort the result first if you need a stable order for more than one key.

package main

import (
	"fmt"

	"github.com/phcp-tech/common-library-golang/cache"
)

func main() {
	c := cache.NewOtterCache()
	_ = c.Set("only-key", "value", 0)

	fmt.Println(c.Keys())
}
Output:
[only-key]

func (*OtterCache) Set

func (c *OtterCache) Set(key string, value interface{}, expire time.Duration) error

Set stores a value in the cache with an optional custom TTL.

Behavior:

  • If expire > 0: the entry's TTL is set to expire and overrides the default expiry configured by ExpiryCalculator.
  • If expire <= 0: no custom TTL is applied and the entry uses the default expiry from ExpiryCalculator (currently 1 hour). Note that this differs from some cache implementations where a zero TTL means "no expiration".
Example

ExampleOtterCache_Set shows the default expire behavior: 0 (or any non-positive duration) does not mean "never expires" — it means "use whatever default TTL this cache was constructed with" (NewOtterCache's default is 1 hour). Pass a positive duration for a custom, per-entry TTL.

package main

import (
	"fmt"
	"time"

	"github.com/phcp-tech/common-library-golang/cache"
)

func main() {
	c := cache.NewOtterCache()
	_ = c.Set("session-token", "abc123", 5*time.Minute)

	val, ok := c.Get("session-token")
	fmt.Println(val, ok)
}
Output:
abc123 true

func (*OtterCache) Size

func (c *OtterCache) Size() int

Size returns an estimated number of entries currently held in the cache.

Example

ExampleOtterCache_Size shows Size reflecting the number of entries currently held.

package main

import (
	"fmt"

	"github.com/phcp-tech/common-library-golang/cache"
)

func main() {
	c := cache.NewOtterCache()
	_ = c.Set("a", 1, 0)
	_ = c.Set("b", 2, 0)

	fmt.Println(c.Size())
}
Output:
2

func (*OtterCache) Update

func (c *OtterCache) Update(key string, value interface{}) error

Update updates the value of the key in the cache without changing its TTL

Example

ExampleOtterCache_Update shows replacing an existing key's value without touching its expiry — unlike Set, Update never resets the TTL clock.

package main

import (
	"fmt"

	"github.com/phcp-tech/common-library-golang/cache"
)

func main() {
	c := cache.NewOtterCache()
	_ = c.Set("counter", 1, 0)
	_ = c.Update("counter", 2)

	val, _ := c.Get("counter")
	fmt.Println(val)
}
Output:
2

func (*OtterCache) Values

func (c *OtterCache) Values() []interface{}

Values returns a snapshot of all values currently stored in the cache.

Example

ExampleOtterCache_Values shows listing every value currently stored — see ExampleOtterCache_Keys about traversal order with more than one entry.

package main

import (
	"fmt"

	"github.com/phcp-tech/common-library-golang/cache"
)

func main() {
	c := cache.NewOtterCache()
	_ = c.Set("only-key", 42, 0)

	fmt.Println(c.Values())
}
Output:
[42]

Jump to

Keyboard shortcuts

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