Created
September 15, 2020 09:44
-
-
Save hazcod/8f6dee847ca35ce273d62ac1c20e4b1d to your computer and use it in GitHub Desktop.
Go sync.map with TTL and per-second scavenging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type TTLMap struct { | |
TTL time.Duration | |
data sync.Map | |
} | |
type expireEntry struct { | |
ExpiresAt time.Time | |
Value interface{} | |
} | |
func (t *ExpiringCertMap) Store(key string, val interface{}) { | |
t.data.Store(key, expireEntry{ | |
ExpiresAt: time.Now().Add(t.TTL), | |
Value: val, | |
}) | |
} | |
func (t *ExpiringCertMap) Load(key string) (val interface{}) { | |
entry, ok := t.data.Load(key) | |
if !ok { return nil } | |
expireEntry := entry.(expireEntry) | |
if expireEntry.ExpiresAt.After(time.Now()) { return nil } | |
return expireEntry.Value | |
} | |
func NewTTLMap(ttl time.Duration) (m ExpiringCertMap) { | |
m.TTL = ttl | |
go func() { | |
for now := range time.Tick(time.Second) { | |
m.data.Range(func(k, v interface{}) bool { | |
if v.(expireEntry).ExpiresAt.After(now) { | |
m.data.Delete(k) | |
} | |
return true | |
}) | |
} | |
}() | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
leaks the goroutine, which may not or may be a problem.