Skip to content

Commit

Permalink
Merge pull request #126 from minotar/mem-exp
Browse files Browse the repository at this point in the history
Remove items from memory cache after the given time
  • Loading branch information
LukeHandle committed Dec 31, 2014
2 parents 3120c17 + 715c8a7 commit 0aded9e
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 3 deletions.
17 changes: 17 additions & 0 deletions cache_memory.go
Expand Up @@ -2,6 +2,7 @@ package main

import (
"github.com/minotar/minecraft"
"time"
)

const (
Expand Down Expand Up @@ -65,6 +66,17 @@ func (c *CacheMemory) pull(username string) minecraft.Skin {
return c.Skins[username]
}

// Removes the username from the cache
func (c *CacheMemory) remove(username string) {
index := indexOf(username, c.Usernames)
if index == -1 {
return
}

key := c.Usernames[index]
delete(c.Skins, key)
}

// Adds the skin to the cache, remove the oldest, expired skin if the cache
// list is full.
func (c *CacheMemory) add(username string, skin minecraft.Skin) {
Expand All @@ -77,6 +89,11 @@ func (c *CacheMemory) add(username string, skin minecraft.Skin) {
}

c.Skins[username] = skin

// After the expiration time, remove the item from the cache.
time.AfterFunc(time.Duration(config.Server.Ttl)*time.Second, func() {
c.remove(username)
})
}

// The byte size of the cache. Fairly rough... don't really want to venture
Expand Down
2 changes: 1 addition & 1 deletion cache_redis.go
Expand Up @@ -113,7 +113,7 @@ func (c *CacheRedis) add(username string, skin minecraft.Skin) {
_ = png.Encode(skinBuf, skin.Image)

// read into err so that it's set for the defer
err = client.Cmd("SETEX", "skins:"+username, config.Redis.Ttl, skinBuf.Bytes()).Err
err = client.Cmd("SETEX", "skins:"+username, strconv.Itoa(config.Server.Ttl), skinBuf.Bytes()).Err
}

func (c *CacheRedis) remove(username string) {
Expand Down
3 changes: 2 additions & 1 deletion config.example.gcfg
Expand Up @@ -7,12 +7,13 @@ cache = memory
# Whether to store statistics about API usage. This requires a
# redis connection if true (fill the config below).
statisticsEnabled = false
# The duration, in seconds we should store item in our cache. Default: 48 hrs
ttl = 172800

[redis]
# If you're using Redis caching, you should fill this section out.
# Otherwise, don't worry about it
address = 127.0.0.1:6379
ttl = 172800
# "auth" is optional, it can be left blank if you don't need authentication.
auth =
# We'll place this before skin caches in Redis to prevent conflicts.
Expand Down
2 changes: 1 addition & 1 deletion configuration.go
Expand Up @@ -19,11 +19,11 @@ type Configuration struct {
Address string
Cache string
StatisticsEnabled bool
Ttl int
}

Redis struct {
Address string
Ttl string
Auth string
Prefix string
PoolSize int
Expand Down

0 comments on commit 0aded9e

Please sign in to comment.