Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

on miss callback #23

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ type Config struct {
// Optional on refresh callback invoked when the cache is refreshed
// Both RefreshInterval and OnRefresh must be provided to enable background cache refresh
OnRefresh func() map[interface{}]interface{}
// Optional on miss callback invoked when get cache is missing
OnMiss func(key interface{})
}

// Entry pointed to by each list.Element
Expand All @@ -104,6 +106,7 @@ type Cache struct {
expirationInterval time.Duration
onEviction func(key, value interface{})
onExpiration func(key, value interface{})
onMiss func(key interface{})

// Cache statistics
sets int64
Expand Down Expand Up @@ -196,7 +199,7 @@ func New(config Config) *Cache {
}

// Set updates a key:value pair in the cache. Returns true if an eviction
// occurrred, and subsequently invokes the OnEviction callback.
// occurred, and subsequently invokes the OnEviction callback.
func (cache *Cache) Set(key, value interface{}) bool {
cache.mutex.Lock()
defer cache.mutex.Unlock()
Expand Down Expand Up @@ -242,14 +245,15 @@ func (cache *Cache) Get(key interface{}) (interface{}, bool) {

// Entry expired
cache.deleteElement(element)
cache.misses++
if cache.onExpiration != nil {
cache.onExpiration(entry.key, entry.value)
}
return nil, false
}

cache.misses++
Comment on lines 247 to 253
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

collapse miss counter and and return into a single one

if cache.onMiss != nil {
cache.onMiss(key)
}
return nil, false
}

Expand Down
Loading