Map with Expiration in Go
In some cases your application doesn’t need Redis, and internal in-memory map with locks and expiration will suffice.
For example you already know the size of the map and you don’t need to store a lot of data. Use cases could be IP rate limiting, or any other short-lived data.
Here is how you can implement this data structure in Go, let’s call it a TTLMap
:
|
|
This map is safe for concurrent access, and it will clean up old items every second. You can adjust the frequency of the cleanup by changing the time.Tick(time.Second)
to a different duration.
Clearly it lacks a lot of features that Redis has, but it’s a good starting point for simple use cases. There are only three methods Put
, Get
, and Delete
and no wildcards or other advanced features. So if you need more features, you should consider using Redis or another key-value store.
You can use this map like this:
|
|