From 0f4d2af8f0b691866e9a354411b77178bd511df5 Mon Sep 17 00:00:00 2001 From: mappu Date: Fri, 18 Nov 2016 20:02:28 +1300 Subject: [PATCH] use LRU cache package --- Thumbnailer.go | 42 +++++++++++++++++++----------------------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/Thumbnailer.go b/Thumbnailer.go index 475ab63..ef27601 100644 --- a/Thumbnailer.go +++ b/Thumbnailer.go @@ -2,53 +2,49 @@ package thumbnail import ( "fmt" - "image" "image/jpeg" "image/png" "os" "strings" - "sync" + + lru "github.com/hashicorp/golang-lru" ) type Thumbnailer struct { - Width int - Height int - MaxCacheSize int + Width int + Height int - cacheMtx sync.RWMutex - thumbCache map[string][]byte + thumbCache *lru.Cache // threadsafe } -func NewThumbnailer() *Thumbnailer { +func NewThumbnailer(Width, Height, MaxCacheSize int) *Thumbnailer { + thumbCache, err := lru.New(MaxCacheSize) + if err != nil { + panic(err) + } + return &Thumbnailer{ - Width: 100, - Height: 100, - MaxCacheSize: 10, - thumbCache: make(map[string][]byte, 0), + Width: Width, + Height: Height, + thumbCache: thumbCache, } } func (this *Thumbnailer) RenderFile(absPath string) ([]byte, error) { - this.cacheMtx.RLock() - tcache, ok := this.thumbCache[absPath] - this.cacheMtx.RUnlock() + thumb, ok := this.thumbCache.Get(absPath) if ok { - return tcache, nil + return thumb.([]byte), nil } // Add to cache - tcache, err := this.RenderFile_NoCache(absPath) + thumb, err := this.RenderFile_NoCache(absPath) if err != nil { return nil, err } - this.cacheMtx.Lock() - // FIXME prune old cached thumbnails - this.thumbCache[absPath] = tcache - this.cacheMtx.Unlock() - - return tcache, nil + this.thumbCache.Add(absPath, thumb) + return thumb.([]byte), nil } func (this *Thumbnailer) RenderFile_NoCache(absPath string) ([]byte, error) {