ttlcache

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2022 License: MIT Imports: 3 Imported by: 10

README

Go TTL Cache

donation link

A Simple Cache That Expires Items.

When getting an item from the cache, the ttl is updated and reset to the current time. This helps prevent frequently accessed items from expiring.

This package uses the haxmap package for better performance.

Installation


  go get github.com/AspieSoft/go-ttlcache

Usage


import (
  "time"

  "github.com/AspieSoft/go-ttlcache"
)

var cache *ttlcache.Cache[string, interface{}]

func main(){
  // create a new cache with a time to live
  cache = ttlcache.New[string, interface{}](2 * time.Hour)

  // optional auto deletion interval (default: 1 hour)
  cache = ttlcache.New[string, interface{}](2 * time.Hour, 4 * time.Hour)

  cache.Set("Item1", 10)
  cache.Set("Item2", 20)

  if value, ok := cache.Get("Item1"); ok {
    // value = 10
  }

  cache.Len() // returns the number of items that have not expired

  cache.MapLen() // returns the total number of items actually stored in the cache (expired items may still be stored, but the ok value will return false if expired)

  if value, ok := cache.Get("Item2"); !ok {
    // Item2 has expired, but the cache may still hold this value and return it
  }

  // reset the cache expire time to keep this value longer
  cache.Touch("Item2")

  // change the time to live
  cache.TTL(1 * time.Hour)

  // optional also change auto deletion interval
  cache.TTL(12 * time.Hour, 24 * time.Hour)

}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache[T hashable, J any] struct {
	Touch func(key T)
	Get   func(key T) (J, bool)
	Set   func(key T, value J)
	Del   func(key T)

	TTL func(ttl time.Duration, delInterval ...time.Duration)

	ForEach func(lambda func(key T, value J))

	Len      func() uintptr
	MapLen   func() uintptr
	Fillrate func() uintptr

	Grow func(newSize uintptr)
}

func New

func New[T hashable, J any](ttl time.Duration, delInterval ...time.Duration) *Cache[T, J]

Jump to

Keyboard shortcuts

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