https://github.com/mkelcik/memory-cache
in memory cache package
https://github.com/mkelcik/memory-cache
cache go golang memory-cache thread-safe ttl ttl-cache ttl-cache-implementation
Last synced: 4 months ago
JSON representation
in memory cache package
- Host: GitHub
- URL: https://github.com/mkelcik/memory-cache
- Owner: mkelcik
- License: mit
- Created: 2023-11-08T21:20:16.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2024-03-27T10:04:27.000Z (almost 2 years ago)
- Last Synced: 2025-01-06T09:29:09.359Z (about 1 year ago)
- Topics: cache, go, golang, memory-cache, thread-safe, ttl, ttl-cache, ttl-cache-implementation
- Language: Go
- Homepage:
- Size: 16.6 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
## Simple thread save memory cache
Features:
* generic
* thread save
* TTL
* optional fixed size (after defined capacity is reached, oldest element is distracted)
* async GC of expired keys
### How to use
```go
package main
import (
"fmt"
mcache "github.com/mkelcik/memory-cache"
"time"
)
type CacheValue struct {
Value int
}
func main() {
// define type of key and value
// first parameter is pre allocation size
// if second parameter is true, cache is limited to this size, if false the cache can grow beyond this capacity
// third parameter is ttl duration for records, if is set to 0 the cache items never expire
// last parameter is GC interval in seconds, if set to 0, GC will never start automatically
cache := mcache.NewCache[int, CacheValue](100, false, 60 * time.Second, 120 * time.Second)
// set data to cache
for i := 1; i <= 100; i++ {
cache.Set(i, CacheValue{Value: 1})
}
// read from cache
itemFromCache, ok := cache.Get(1)
if ok {
fmt.Println("value is:", itemFromCache.Value)
}
}
```
#### Execute GC manually
If you need more control over destroying expired key, you can run GC manually when you see fit
```go
cache.GCRun()
```