Skip to content

A Go package providing a simple LRU cache with generics.

License

Notifications You must be signed in to change notification settings

tunabay/go-cache

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-cache

Go Reference MIT License

Overview

Package cache implements a simple LRU cache with generics.

It provides a mechanism for caching resources that are time consuming to create or retrieve. The main feature is that the creation process runs only once even when multiple go-routines concurrently request for a key that does not exist in the cache.

Originally implemented for a small web program that dynamically generates images based on the requested URI.

Usage

import (
	"fmt"
	"sync"
	"time"

	"github.com/tunabay/go-cache"
)

type MyResource struct {
	data string
}

func CreateResource(key string) (*MyResource, time.Time, error) {
	time.Sleep(time.Second >> 2) // slow creation
	return &MyResource{data: "data " + key}, time.Time{}, nil
}

func main() {
	myCache := cache.New[string, *MyResource](CreateResource)

	showResource := func(key string) {
		val, cached, _, err := myCache.Get(key)
		if err != nil {
			panic(err)
		}
		var tag string
		if cached {
			tag = " (cached)"
		}
		fmt.Printf("%s -> %q%s\n", key, val.data, tag)
	}

	var wg sync.WaitGroup
	for i := 0; i < 12; i++ {
		wg.Add(1)
		go func(n int) {
			defer wg.Done()
			key := fmt.Sprintf("key-%d", n&3)
			showResource(key)
		}(i)
	}
	wg.Wait()
}

Run in Go Playground

Documentation and more examples

License

go-cache is available under the MIT license. See the LICENSE file for more information.