LevelDB style LRU cache for Go, support non GC object.


LRU Cache

Build Status GoDoc

Install

  1. go get github.com/chai2010/cache
  2. go run hello.go

Example

Simple GC Object

This is a simple example:

package main

import (
	"fmt"

	"github.com/chai2010/cache"
)

func main() {
	c := cache.NewLRUCache(100)
	defer c.Close()

	c.Set("key1", "value1", 1)
	value1 := c.Value("key1").(string)
	fmt.Println("key1:", value1)

	c.Set("key2", "value2", 1)
	value2 := c.Value("key2", "null").(string)
	fmt.Println("key2:", value2)

	value3 := c.Value("key3", "null").(string)
	fmt.Println("key3:", value3)

	value4 := c.Value("key4") // value4 is nil
	fmt.Println("key4:", value4)

	fmt.Println("Done")
}

Output:

key1: value1
key2: value2
key3: null
key4: <nil>
Done

Non GC Object

Support non GC object, such as os.File or some cgo memory.

package main

import (
	"fmt"

	"github.com/chai2010/cache"
)

func main() {
	c := cache.NewLRUCache(10)
	defer c.Close()

	id0 := c.NewId()
	id1 := c.NewId()
	id2 := c.NewId()
	fmt.Println("id0:", id0)
	fmt.Println("id1:", id1)
	fmt.Println("id2:", id2)

	// add new
	v1 := "data:123"
	h1 := c.Insert("123", "data:123", len("data:123"), func(key string, value interface{}) {
		fmt.Printf("deleter(%q:%q)\n", key, value)
	})

	// fetch ok
	v2, h2, ok := c.Lookup("123")
	assert(ok)
	assert(h2 != nil)

	// remove
	c.Erase("123")

	// fetch failed
	_, h3, ok := c.Lookup("123")
	assert(!ok)
	assert(h3 == nil)

	// h1&h2 still valid!
	fmt.Printf("user1(%s)\n", v1)
	fmt.Printf("user2(%s)\n", v2.(string))

	// release h1
	// because the h2 handle the value, so the deleter is not ivoked!
	h1.Close()

	// invoke the deleter
	fmt.Println("invoke deleter(123) begin")
	h2.Close()
	fmt.Println("invoke deleter(123) end")

	// add new
	h4 := c.Insert("abc", "data:abc", len("data:abc"), func(key string, value interface{}) {
		fmt.Printf("deleter(%q:%q)\n", key, value)
	})
	// release h4
	// because the cache handle the value, so the deleter is not ivoked!
	h4.Close()

	// cache length
	length := c.Length()
	assert(length == 1)

	// cache size
	size := c.Size()
	assert(size == 8, "size:", size)

	// add h5
	// this will cause the capacity(10) overflow, so the h4 deleter will be invoked
	fmt.Println("invoke deleter(h4) begin")
	h5 := c.Insert("456", "data:456", len("data:456"), func(key string, value interface{}) {
		fmt.Printf("deleter(%q:%q)\n", key, value)
	})
	fmt.Println("invoke deleter(h4) end")

	// must release all handles
	h5.Close()

	// stats
	fmt.Println("StatsJSON:", c.StatsJSON())

	// done
	fmt.Println("Done")
}

func assert(v bool, a ...interface{}) {
	if !v {
		panic(fmt.Sprint(a...))
	}
}

Output:

id0: 1
id1: 2
id2: 3
user1(data:123)
user2(data:123)
invoke deleter(123) begin
deleter("123":"data:123")
invoke deleter(123) end
invoke deleter(h4) begin
deleter("abc":"data:abc")
invoke deleter(h4) end
StatsJSON: {
        "Length": 1,
        "Size": 8,
        "Capacity": 10,
        "OldestAccess": "2015-08-21 18:00:24.0119469 +0800 CST"
}
Done
deleter("456":"data:456")

BUGS

Report bugs to [email protected].

Thanks!

Owner
chai2010
《Go语言高级编程》《Go语法树入门》《WebAssembly标准入门》作者
chai2010
Similar Resources

Package cache is a middleware that provides the cache management for Flamego.

cache Package cache is a middleware that provides the cache management for Flamego. Installation The minimum requirement of Go is 1.16. go get github.

Nov 9, 2022

A mem cache base on other populator cache, add following feacture

memcache a mem cache base on other populator cache, add following feacture add lazy load(using expired data, and load it asynchronous) add singlefligh

Oct 28, 2021

Cache - A simple cache implementation

Cache A simple cache implementation LRU Cache An in memory cache implementation

Jan 25, 2022

Gin-cache - Gin cache middleware with golang

Gin-cache - Gin cache middleware with golang

Nov 28, 2022

🦉owlcache is a lightweight, high-performance, non-centralized, distributed Key/Value memory-cached data sharing application written by Go

 🦉owlcache is a lightweight, high-performance, non-centralized, distributed Key/Value memory-cached data sharing application written by Go

🦉owlcache is a lightweight, high-performance, non-centralized, distributed Key/Value memory-cached data sharing application written by Go . keyword : golang cache、go cache、golang nosql

Nov 5, 2022

groupcache is a caching and cache-filling library, intended as a replacement for memcached in many cases.

groupcache Summary groupcache is a distributed caching and cache-filling library, intended as a replacement for a pool of memcached nodes in many case

Dec 31, 2022

☔️ A complete Go cache library that brings you multiple ways of managing your caches

☔️ A complete Go cache library that brings you multiple ways of managing your caches

Gocache Guess what is Gocache? a Go cache library. This is an extendable cache library that brings you a lot of features for caching data. Overview He

Jan 1, 2023

fastcache - fast thread-safe inmemory cache for big number of entries in Go

Fast thread-safe inmemory cache for big number of entries in Go. Minimizes GC overhead

Dec 27, 2022
Comments
  • add example for realtime worker

    add example for realtime worker

    Shared cache:

    dataCache := cache.NewLRUCache(32)
    defer dataCache.Close()
    
    todoCache := cache.NewLRUCache(32)
    defer todoCache.Close()
    

    Forground user:

    // if cache missing, push to todoCache
    if v := dataCache.Value(key); v == nil {
        todoCache.PushFront(key, func() {
            // load data slowly
            // put data to dataCache
        }, 1)
    }
    

    Background worker:

    for {
        if h := todoCache.PopFront(); h != nil {
            h.Value().(func())() // do the work
            h.Release()
        }
    }
    
Related tags
Lru - A simple LRU cache using go generics

LRU Cache A simple LRU cache using go generics. Examples Basic usage. func main(

Nov 9, 2022
Cache library for golang. It supports expirable Cache, LFU, LRU and ARC.
Cache library for golang. It supports expirable Cache, LFU, LRU and ARC.

GCache Cache library for golang. It supports expirable Cache, LFU, LRU and ARC. Features Supports expirable Cache, LFU, LRU and ARC. Goroutine safe. S

Dec 30, 2022
lru: the most concise and efficient LRU algorithm based on golang

lru This package of lru is the most concise and efficient LRU algorithm based on golang. Example Quick start: package main import ( "fmt" "github.

Dec 27, 2021
Least-recently-used-LRU- - Design CacheEvictionPolicy with 2 strategy LRU(Least recently used)

Least-recently-used-LRU- Design CacheEvictionPolicy with 2 strategy LRU(Least re

Jan 4, 2022
An in-memory cache library for golang. It supports multiple eviction policies: LRU, LFU, ARC

GCache Cache library for golang. It supports expirable Cache, LFU, LRU and ARC. Features Supports expirable Cache, LFU, LRU and ARC. Goroutine safe. S

May 31, 2021
LRU-based cache package for Go.

cache is LRU-based cache package written in vanilla Go - with no package dependency. LRU stands for Least Recently Used and it is one of the famous cache replacement algorithm

Sep 8, 2022
Thread-safe LRU cache with permanency and context-based expiration

go-wlru Thread-safe LRU cache with permanency and context-based expiration Operational Complexity (Time) Operation Best Average Worst Access Θ(1) Θ(1)

Mar 7, 2022
Solution for Leetcode problem: 146. LRU Cache

Solution for Leetcode problem: 146. LRU Cache link My solution for the above lee

Jan 30, 2022
gdcache is a pure non-intrusive distributed cache library implemented by golang
gdcache is a pure non-intrusive distributed cache library implemented by golang

gdcache is a pure non-intrusive distributed cache library implemented by golang, you can use it to implement your own distributed cache

Sep 26, 2022
Dec 28, 2022