Skip to content

Commit

Permalink
Make cache memory bound
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed Jun 25, 2020
1 parent 48dbb59 commit ce83e78
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
11 changes: 8 additions & 3 deletions cache/namedmemcache/named_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,14 @@ package namedmemcache

import (
"sync"
"time"

"github.com/BurntSushi/locker"
"github.com/karlseguin/ccache"
)

var cc = ccache.New(ccache.Configure().MaxSize(100).ItemsToPrune(100))

// Cache holds the cached values.
type Cache struct {
nlocker *locker.Locker
Expand Down Expand Up @@ -58,10 +62,11 @@ func (c *Cache) Clear() {
// key is invoced only once for this cache.
func (c *Cache) GetOrCreate(key string, create func() (interface{}, error)) (interface{}, error) {
c.mu.RLock()
entry, found := c.cache[key]
v := cc.Get(key)
c.mu.RUnlock()

if found {
if v != nil {
entry := v.Value().(cacheEntry)
return entry.value, entry.err
}

Expand All @@ -72,7 +77,7 @@ func (c *Cache) GetOrCreate(key string, create func() (interface{}, error)) (int
value, err := create()

c.mu.Lock()
c.cache[key] = cacheEntry{value: value, err: err}
cc.Set(key, cacheEntry{value: value, err: err}, time.Minute)
c.mu.Unlock()

return value, err
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ require (
github.com/google/go-cmp v0.3.2-0.20191028172631-481baca67f93
github.com/gorilla/websocket v1.4.1
github.com/jdkato/prose v1.1.1
github.com/karlseguin/ccache v2.0.3+incompatible
github.com/kr/pretty v0.2.0 // indirect
github.com/kyokomi/emoji v2.2.1+incompatible
github.com/magefile/mage v1.9.0
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,9 @@ github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/karlseguin/ccache v1.0.1 h1:0gpC6z1qtv0cKmsi5Su5tTB6bJ2vm9bfOLACpDEB/Ro=
github.com/karlseguin/ccache v2.0.3+incompatible h1:j68C9tWOROiOLWTS/kCGg9IcJG+ACqn5+0+t8Oh83UU=
github.com/karlseguin/ccache v2.0.3+incompatible/go.mod h1:CM9tNPzT6EdRh14+jiW8mEF9mkNZuuE51qmgGYUB93w=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
Expand Down

0 comments on commit ce83e78

Please sign in to comment.