Skip to content

go impl lrucache reference leveldb & easy use & rich usage

License

Notifications You must be signed in to change notification settings

gersure/lrucache

Repository files navigation

lrucache

golang impl lru cache reference leveldb

  • it's a lru chche
  • very easy to use
  • good performance
  • adapt most application scenario

this's (1<<num_shard_bits(<10)) hash table in cache; modify every hash table use sync.mutex;so it's provide good performance when memory use up to capacity; Earliest insert will be drop

how to use

method 1

    	// use get set delete (just provide string type support)
    	lru := NewLRUCache(1024*1024/*capacity*/, 0/*num shard bits*/) // num_shard_bit is 0, code will auto make one
		
    	lru.Put("key", "value")
    	value := lru.Get("key")
    	//displayed remove
    	lru.Delete("key")

method 2

	lru := NewLRUCache(1024*1024 /*capacity*/, 0 /*num shard bits*/) // num_shard_bit is 0, code will auto make one

	key := []byte("key")
	type V struct {a int; b int}
	value := V{4, 5}

	lru.Insert(key, value, uint64(len(key)+4*2), func(key []byte, entry interface{}) {
		fmt.Println("key:%s will be deleted from cache", key)
	})
	origin := lru.Lookup(key)
	if origin != nil {
		origin_value := origin.(V)
		fmt.Println(origin_value)
	}

method 3; use like redis incr;but merge return old value

	key := []byte("key")
	var merge_value int = 1
	lru := NewLRUCache(1024, 1)
	for i := 0; i < 1000; i++ {
		lru.Merge(key, merge_value, 4, IntMergeOperator, IntChargeOperator) // real value = value+1
	}

more use case, you can see lrucache_test.go

About

go impl lrucache reference leveldb & easy use & rich usage

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages