use LRU cache package

This commit is contained in:
mappu 2016-11-18 20:02:28 +13:00
parent 5f096e52a4
commit 0f4d2af8f0

View File

@ -2,53 +2,49 @@ package thumbnail
import ( import (
"fmt" "fmt"
"image"
"image/jpeg" "image/jpeg"
"image/png" "image/png"
"os" "os"
"strings" "strings"
"sync"
lru "github.com/hashicorp/golang-lru"
) )
type Thumbnailer struct { type Thumbnailer struct {
Width int Width int
Height int Height int
MaxCacheSize int
cacheMtx sync.RWMutex thumbCache *lru.Cache // threadsafe
thumbCache map[string][]byte
} }
func NewThumbnailer() *Thumbnailer { func NewThumbnailer(Width, Height, MaxCacheSize int) *Thumbnailer {
thumbCache, err := lru.New(MaxCacheSize)
if err != nil {
panic(err)
}
return &Thumbnailer{ return &Thumbnailer{
Width: 100, Width: Width,
Height: 100, Height: Height,
MaxCacheSize: 10, thumbCache: thumbCache,
thumbCache: make(map[string][]byte, 0),
} }
} }
func (this *Thumbnailer) RenderFile(absPath string) ([]byte, error) { 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 { if ok {
return tcache, nil return thumb.([]byte), nil
} }
// Add to cache // Add to cache
tcache, err := this.RenderFile_NoCache(absPath) thumb, err := this.RenderFile_NoCache(absPath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
this.cacheMtx.Lock() this.thumbCache.Add(absPath, thumb)
// FIXME prune old cached thumbnails return thumb.([]byte), nil
this.thumbCache[absPath] = tcache
this.cacheMtx.Unlock()
return tcache, nil
} }
func (this *Thumbnailer) RenderFile_NoCache(absPath string) ([]byte, error) { func (this *Thumbnailer) RenderFile_NoCache(absPath string) ([]byte, error) {