项目作者: codeation

项目描述 :
Go asynchronous LRU cache
高级语言: Go
项目地址: git://github.com/codeation/lru.git
创建时间: 2020-12-11T14:24:06Z
项目社区:https://github.com/codeation/lru

开源协议:MIT License

下载


lru

A lru is an asynchronous LRU cache (generic version).

GoDoc

  • based on golang map structure
  • prevents infinite cache growth
  • designed for asynchronous use

Usage

For example, caching the output of the ioutil.ReadFile function to reduce disk I/O.

  1. package main
  2. import (
  3. "log"
  4. "os"
  5. "github.com/codeation/lru"
  6. )
  7. func readFileContent(key string) ([]byte, error) {
  8. log.Println("read once")
  9. return os.ReadFile(key)
  10. }
  11. func main() {
  12. cache := lru.NewSyncLRU(1024, readFileContent)
  13. for i := 0; i < 10; i++ {
  14. data, err := cache.Get("input.txt")
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. log.Printf("file size is %d\n", len(data))
  19. }
  20. }

The lru.NewSyncLRU parameter is the number of cache items until the last used item is removed from the cache. The second parameter is a func to get the value for the specified key and error.

The parameter of cache.Get func is a key (filename in this case). An error is returned when the function returns an error.