Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/borislavv/go-cache
Cache implementation for golang
https://github.com/borislavv/go-cache
cache golang golang-library in-memory-caching thread-safe
Last synced: about 8 hours ago
JSON representation
Cache implementation for golang
- Host: GitHub
- URL: https://github.com/borislavv/go-cache
- Owner: Borislavv
- License: mit
- Created: 2023-11-29T07:16:31.000Z (10 months ago)
- Default Branch: master
- Last Pushed: 2024-01-02T06:27:46.000Z (9 months ago)
- Last Synced: 2024-01-02T07:47:53.857Z (9 months ago)
- Topics: cache, golang, golang-library, in-memory-caching, thread-safe
- Homepage:
- Size: 9.77 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# go-cache
## Cache implementation for golang
Interface:
```
type Cacher interface {
Get(key string, fn func(CacheItem) (data interface{}, err error)) (data interface{}, err error)
Delete(key string)
}type CacheItem interface {
SetTTL(ttl time.Duration)
}
```Create a new instance of cache:
```
ctx, _ := context.WithCancel(context.Background())
storage := cache.NewMapCacheStorage(ctx)
displacer := cache.NewCacheDisplacer(ctx, time.Second*1)
cache := cache.NewCache(storage, displacer)
```Usage:
```
package mainimport (
"context"
"fmt"
"github.com/Borislavv/go-cache"
"time"
)const UserExampleID = 1
type User struct {
ID int
}func main() {
ctx, _ := context.WithCancel(context.Background())storage := cache.NewMapCacheStorage(ctx)
displacer := cache.NewCacheDisplacer(ctx, time.Second*1)
cacher := cache.NewCache(storage, displacer)cacheKey := fmt.Sprintf("userID_%v", UserExampleID)
userInterface, _ := cacher.Get(cacheKey, func(item cache.CacheItem) (data interface{}, err error) {
item.SetTTL(time.Hour)
return fetchUserByID(UserExampleID), nil
})cachedUser, _ := userInterface.(*User)
fmt.Printf("userID is %d\n", cachedUser.ID)
// output:
// user fetched from storage
// userID is 1userInterface, _ = cacher.Get(cacheKey, func(item cache.CacheItem) (data interface{}, err error) {
item.SetTTL(time.Hour)
return fetchUserByID(UserExampleID), nil
})cachedUser, _ = userInterface.(*User)
fmt.Printf("userID is %d\n", cachedUser.ID)
// output:
// userID is 1
}func fetchUserByID(id int) *User {
fmt.Println("user fetched from storage")
return &User{ID: id}
}// Total output:
// user fetched from storage
// userID is 1
// userID is 1
```