重建 common_utils
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.1 KiB

package common_utils
import (
"context"
"github.com/allegro/bigcache"
"github.com/eko/gocache/lib/v4/cache"
"github.com/eko/gocache/lib/v4/store"
bigcache_store "github.com/eko/gocache/store/bigcache/v4"
redis_store "github.com/eko/gocache/store/redis/v4"
"github.com/redis/go-redis/v9"
"log"
"time"
)
type ChainedCache struct {
LoadableChinCache *cache.LoadableCache[any]
}
func NewChainedCache(redisAddr string) *ChainedCache {
bigCacheClient, _ := bigcache.NewBigCache(bigcache.DefaultConfig(2 * time.Minute))
bigCacheStore := bigcache_store.NewBigcache(bigCacheClient)
redisStore := redis_store.NewRedis(redis.NewClient(&redis.Options{
Addr: redisAddr,
}), store.WithExpiration(2*time.Minute))
cacheManager := cache.NewChain[any](
cache.New[any](bigCacheStore),
cache.New[any](redisStore),
)
loadFunction := func(ctx context.Context, key any) (any, error) {
// ... retrieve value from available source
log.Printf("缓存击穿!!!,key=%s", key.(string))
return nil, nil
}
cacheManagerWithLoad := cache.NewLoadable[any](
loadFunction,
cacheManager,
)
return &ChainedCache{
LoadableChinCache: cacheManagerWithLoad,
}
}