https://github.com/alexssd7/cache
CDN-like in-memory cache with shielding and Go 1.18 Generics
https://github.com/alexssd7/cache
golang golang-generics
Last synced: 9 months ago
JSON representation
CDN-like in-memory cache with shielding and Go 1.18 Generics
- Host: GitHub
- URL: https://github.com/alexssd7/cache
- Owner: AlexSSD7
- License: mit
- Created: 2021-12-25T11:40:49.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2022-04-24T10:37:12.000Z (about 4 years ago)
- Last Synced: 2025-09-12T03:46:53.212Z (10 months ago)
- Topics: golang, golang-generics
- Language: Go
- Homepage:
- Size: 7.81 KB
- Stars: 0
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# cache
CDN-like, middleware memory cache for Go applications with integrated shielding and Go 1.18 Generics.
## Usage
```go
package main
import (
"context"
"fmt"
"time"
"github.com/AlexSSD7/cache"
)
type Person struct {
Name string
Age uint32
}
func fetchPerson(name string) (*Person, error) {
// Heavy task here, like a DB call.
// Shielding makes the fetch functions
// mutually exclusive, to prevent
// unncecessary duplicate calls
// if there is no cache in memory.
// For the purpose of this example though,
// we will just return sample objects.
switch name {
case "John":
return &Person{Name: "John", Age: 27}, nil
case "Steve":
return &Person{Name: "Steve", Age: 32}, nil
default:
return nil, fmt.Errorf("unknown person with name '%v'", name)
}
}
func main() {
// Create a new ShieldedCache instance with 5-second GC interval.
cache := cache.NewShieldedCache[*Person](time.Second * 5)
cacheCtx, cacheCtxCancel := context.WithCancel(context.Background())
defer cacheCtxCancel()
// Worker is a separate goroutine running in background.
// It is responsible for evicting old, expired objects.
cache.StartWorker(cacheCtx)
// If there is "person_john" object in cache, return it. Otherwise, execute fetchPerson("John").
ret, hit, err := cache.Fetch("person_john", time.Minute, func() (*Person, error) {
return fetchPerson("John")
})
fmt.Printf("result: %+v, hit: %v, err: %v\n", ret.Data, hit, err)
// result: &{Name:John Age:27}, hit: false, err:
ret, hit, err = cache.Fetch("person_john", time.Minute, func() (*Person, error) {
return fetchPerson("John")
})
fmt.Printf("result: %+v, hit: %v, err: %v\n", ret.Data, hit, err)
// result: &{Name:John Age:27}, hit: true, err:
ret, hit, err = cache.Fetch("person_steve", time.Minute, func() (*Person, error) {
return fetchPerson("Steve")
})
fmt.Printf("result: %+v, hit: %v, err: %v\n", ret.Data, hit, err)
// result: &{Name:Steve Age:32}, hit: false, err:
ret, hit, err = cache.Fetch("person_alice", time.Minute, func() (*Person, error) {
return fetchPerson("Alice")
})
fmt.Printf("result: %+v, hit: %v, err: %v\n", ret, hit, err)
// result: , hit: false, err: unknown person with name 'Alice'
}
```
# License
MIT