41 lines
860 B
Go
41 lines
860 B
Go
package cache
|
|
|
|
import (
|
|
"reflect"
|
|
|
|
"git.sdf.org/jchenry/x"
|
|
)
|
|
|
|
type tieredCache[K comparable, V any] struct {
|
|
inner Interface[K, V]
|
|
outer Interface[K, V]
|
|
}
|
|
|
|
func NewTieredCache[K comparable, V any](inner, outer Interface[K, V]) Interface[K, V] {
|
|
x.Assert(inner != nil, "cache.NewTieredCache: inner cannot be nil")
|
|
x.Assert(outer != nil, "cache.NewTieredCache: outer cannot be nil")
|
|
return &tieredCache[K, V]{
|
|
inner: inner,
|
|
outer: outer,
|
|
}
|
|
}
|
|
|
|
func (t *tieredCache[K, V]) Get(key K) V {
|
|
var zero, value V
|
|
value = t.inner.Get(key)
|
|
if reflect.DeepEqual(value, zero) {
|
|
value = t.outer.Get(key)
|
|
// if required, add value to inner cache for future requests
|
|
}
|
|
return value
|
|
}
|
|
|
|
func (t *tieredCache[K, V]) Put(key K, value V) {
|
|
t.inner.Put(key, value)
|
|
|
|
// add key to outer cache asynchronously
|
|
go func(key K) {
|
|
t.outer.Put(key, value)
|
|
}(key)
|
|
}
|