2020-04-12 03:45:24 +08:00
|
|
|
package chunk_cache
|
2020-03-29 04:43:31 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/karlseguin/ccache"
|
|
|
|
)
|
|
|
|
|
|
|
|
// a global cache for recently accessed file chunks
|
|
|
|
type ChunkCache struct {
|
|
|
|
cache *ccache.Cache
|
|
|
|
}
|
|
|
|
|
2020-03-29 05:07:16 +08:00
|
|
|
func NewChunkCache(maxEntries int64) *ChunkCache {
|
|
|
|
pruneCount := maxEntries >> 3
|
|
|
|
if pruneCount <= 0 {
|
|
|
|
pruneCount = 500
|
|
|
|
}
|
2020-03-29 04:43:31 +08:00
|
|
|
return &ChunkCache{
|
2020-03-29 05:07:16 +08:00
|
|
|
cache: ccache.New(ccache.Configure().MaxSize(maxEntries).ItemsToPrune(uint32(pruneCount))),
|
2020-03-29 04:43:31 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ChunkCache) GetChunk(fileId string) []byte {
|
|
|
|
item := c.cache.Get(fileId)
|
|
|
|
if item == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
data := item.Value().([]byte)
|
|
|
|
item.Extend(time.Hour)
|
|
|
|
return data
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *ChunkCache) SetChunk(fileId string, data []byte) {
|
|
|
|
c.cache.Set(fileId, data, time.Hour)
|
|
|
|
}
|