Skip to content
This repository has been archived by the owner on Aug 25, 2023. It is now read-only.
/ golang-lru Public archive
forked from hashicorp/golang-lru

Fork of the hashicorp LRU package which implements a fixed-size thread-safe LRU cache.

License

Notifications You must be signed in to change notification settings

paskal/golang-lru

 
 

Repository files navigation

golang-lru

Important: this is outdated as the expirable cache was merged to the upstream. Please use https://github.com/hashicorp/golang-lru/tree/master/expirable instead.

This provides a fork of the hashicorp lru package which implements a fixed-size thread-safe LRU cache. The original is based on the cache in Groupcache.

Documentation

Full docs are available on Go Packages

LRU cache example

package main

import (
	"fmt"

	"github.com/paskal/golang-lru/v2"
)

func main() {
	l, _ := lru.New[int, *string](128)
	for i := 0; i < 256; i++ {
		l.Add(i, nil)
	}

	if l.Len() != 128 {
		panic(fmt.Sprintf("bad len: %v", l.Len()))
	}
}

Expirable LRU cache example

package main

import (
	"fmt"
	"time"

	"github.com/paskal/golang-lru/v2/simplelru"
)

func main() {
	// make cache with short TTL and 3 max keys, purgeEvery time.Millisecond * 10
	cache := simplelru.NewExpirableLRU[string, string](3, nil, time.Millisecond*5, time.Millisecond*10)
	// expirable cache need to be closed after used
	defer cache.Close()

	// set value under key1.
	cache.Add("key1", "val1")

	// get value under key1
	r, ok := cache.Get("key1")

	// check for OK value
	if ok {
		fmt.Printf("value before expiration is found: %v, value: %q\n", ok, r)
	}

	time.Sleep(time.Millisecond * 11)

	// get value under key1 after key expiration
	r, ok = cache.Get("key1")
	fmt.Printf("value after expiration is found: %v, value: %q\n", ok, r)

	// set value under key2, would evict old entry because it is already expired.
	cache.Add("key2", "val2")

	fmt.Printf("Cache len: %d", cache.Len())
	// Output:
	// value before expiration is found: true, value: "val1"
	// value after expiration is found: false, value: ""
	// Cache len: 1
}

About

Fork of the hashicorp LRU package which implements a fixed-size thread-safe LRU cache.

Resources

License

Stars

Watchers

Forks

Languages

  • Go 100.0%