use LRU cache package

This commit is contained in:
mappu 2016-11-18 20:02:28 +13:00
parent 5f096e52a4
commit 0f4d2af8f0
1 changed files with 19 additions and 23 deletions

View File

@ -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) {