chunk_cache_in_memory.go 761 B

123456789101112131415161718192021222324252627282930313233343536
  1. package chunk_cache
  2. import (
  3. "time"
  4. "github.com/karlseguin/ccache/v2"
  5. )
  6. // a global cache for recently accessed file chunks
  7. type ChunkCacheInMemory struct {
  8. cache *ccache.Cache
  9. }
  10. func NewChunkCacheInMemory(maxEntries int64) *ChunkCacheInMemory {
  11. pruneCount := maxEntries >> 3
  12. if pruneCount <= 0 {
  13. pruneCount = 500
  14. }
  15. return &ChunkCacheInMemory{
  16. cache: ccache.New(ccache.Configure().MaxSize(maxEntries).ItemsToPrune(uint32(pruneCount))),
  17. }
  18. }
  19. func (c *ChunkCacheInMemory) GetChunk(fileId string) []byte {
  20. item := c.cache.Get(fileId)
  21. if item == nil {
  22. return nil
  23. }
  24. data := item.Value().([]byte)
  25. item.Extend(time.Hour)
  26. return data
  27. }
  28. func (c *ChunkCacheInMemory) SetChunk(fileId string, data []byte) {
  29. c.cache.Set(fileId, data, time.Hour)
  30. }