ttlcache

package module
v0.0.0-...-f9979b1 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2024 License: MIT Imports: 2 Imported by: 0

README

TTL cache

Build Status Go Report Card GoDoc Licence MIT

Simple thread-safe expiring in-memory cache.

Usage example

package main

import (
	"fmt"
	"time"

	"github.com/jsageryd/ttlcache"
)

func main() {
	cache := ttlcache.New(5 * time.Second)
	cache.Set("foo", "bar")
	if value, ok := cache.Get("foo"); ok {
		fmt.Println("Value:", value) // (type assert value as needed)
	} else {
		fmt.Println("Key not found")
	}
}

Note

For every new key that is set a goroutine is spawned to expire that key after the timeout. This keeps the implementation clean and simple. Already existing keys keep the same goroutine if they are set again before they have expired. While it should not generally be an issue to spawn many thousand goroutines, if you have a very large amount of things to cache, this package is not for you. So keep that in mind. Consider Qcache.

Documentation

Overview

Package ttlcache provides a cache whose items expire after set TTL.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache interface {
	Expire(key interface{})
	ExpireAll()
	Get(key interface{}) (interface{}, bool)
	Set(key interface{}, value interface{})
}

Cache is a key-value cache for arbitrary values

func New

func New(ttl time.Duration) Cache

New returns a new cache. ttl is the time to live for its items.

Jump to

Keyboard shortcuts

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