pkg/cache 定义框架通用缓存抽象,并提供内存实现。
Cache 接口,屏蔽具体存储实现。NewMemoryCache,供 Engine 内部直接使用。LRUCache 作为轻量级本地淘汰容器,适合独立场景。type Cache interface
Get(ctx, key)Set(ctx, key, value, ttl)Delete(ctx, key)Exists(ctx, key)Clear(ctx)Close()type BatchCache interface
MGet / MSet / MDeletetype AtomicCache interface
GetOrSet / Increment / Decrementtype StatsCache interface
Stats() / ResetStats()NewMemoryCache(opts ...MemoryOption) Cache
NewLRU(capacity int) *LRUCache
container/list 的 LRU 容器Get / Set / Delete / Len / ClearCache 接口ErrNotFoundErrExpiredWithMaxSize(size int):最大 key 数,超过后淘汰最旧项WithDefaultTTL(ttl time.Duration):Set 时未显式指定 TTL 的默认值WithCleanupInterval(d time.Duration):过期清理周期;设为 0 可关闭后台清理当前仓库未内置 Redis 实现。若需要 Redis,可自行实现 Cache / BatchCache / AtomicCache,再通过 Engine.WithCache 注入。
package main
import (
"context"
"time"
"github.com/darkit/gin/pkg/cache"
)
func main() {
c := cache.NewMemoryCache(
cache.WithMaxSize(1000),
cache.WithDefaultTTL(5*time.Minute),
cache.WithCleanupInterval(time.Minute),
)
defer c.Close()
_ = c.Set(context.Background(), "user:1", []byte("alice"), time.Minute)
_, _ = c.Get(context.Background(), "user:1")
}
mc := cache.NewMemoryCache()
if batch, ok := mc.(cache.BatchCache); ok {
_ = batch.MSet(context.Background(), map[string][]byte{
"a": []byte("1"),
"b": []byte("2"),
}, time.Minute)
}
type RedisCache struct{}
func (r *RedisCache) Get(ctx context.Context, key string) ([]byte, error) { return nil, nil }
func (r *RedisCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error { return nil }
func (r *RedisCache) Delete(ctx context.Context, key string) error { return nil }
func (r *RedisCache) Exists(ctx context.Context, key string) (bool, error) { return false, nil }
func (r *RedisCache) Clear(ctx context.Context) error { return nil }
func (r *RedisCache) Close() error { return nil }
gin.New() 默认注入 cache.NewMemoryCache() 作为内部缓存。e.WithCache(customCache) 替换实现。e := gin.New()
e.WithCache(cache.NewMemoryCache(cache.WithDefaultTTL(10 * time.Minute)))