kos/pkg/cache/memcache.go

76 lines
1.6 KiB
Go
Raw Normal View History

2023-04-23 17:57:36 +08:00
package cache
import (
"context"
2024-11-12 17:47:28 +08:00
"git.nobla.cn/golang/kos/util/env"
2023-04-23 17:57:36 +08:00
"github.com/patrickmn/go-cache"
2023-06-30 14:16:16 +08:00
"os"
2023-04-23 17:57:36 +08:00
"time"
)
2023-06-30 14:16:16 +08:00
var (
memCacheDefaultExpired time.Duration
memCacheCleanupInterval time.Duration
)
func init() {
memCacheDefaultExpired, _ = time.ParseDuration(env.Get("MEMCACHE_DEFAULT_EXPIRED", "1h"))
memCacheCleanupInterval, _ = time.ParseDuration(env.Get("MEMCACHE_CLEANUP_INTERVAL", "10m"))
if memCacheDefaultExpired < time.Second*5 {
memCacheDefaultExpired = time.Second * 5
}
if memCacheCleanupInterval < time.Minute {
memCacheCleanupInterval = time.Minute
}
}
2023-04-23 17:57:36 +08:00
type MemCache struct {
engine *cache.Cache
}
2023-09-20 11:05:08 +08:00
func (cache *MemCache) Try(ctx context.Context, key string, cb LoadFunc) (buf []byte, err error) {
2023-06-30 14:16:16 +08:00
var (
ok bool
)
2023-09-20 11:05:08 +08:00
if buf, ok = cache.Get(ctx, key); ok {
return buf, nil
2023-06-30 14:16:16 +08:00
}
if cb == nil {
return nil, os.ErrNotExist
}
2023-09-20 11:05:08 +08:00
if buf, err = cb(ctx); err == nil {
cache.Set(ctx, key, buf)
2023-06-30 14:16:16 +08:00
}
return
}
2023-09-20 11:05:08 +08:00
func (cache *MemCache) Set(ctx context.Context, key string, buf []byte) {
cache.engine.Set(key, buf, 0)
2023-04-23 17:57:36 +08:00
}
2023-09-20 11:05:08 +08:00
func (cache *MemCache) SetEx(ctx context.Context, key string, buf []byte, expire time.Duration) {
cache.engine.Set(key, buf, expire)
2023-04-23 17:57:36 +08:00
}
2023-09-20 11:05:08 +08:00
func (cache *MemCache) Get(ctx context.Context, key string) (buf []byte, ok bool) {
var (
val any
)
if val, ok = cache.engine.Get(key); ok {
buf, ok = val.([]byte)
}
return
2023-04-23 17:57:36 +08:00
}
func (cache *MemCache) Del(ctx context.Context, key string) {
cache.engine.Delete(key)
}
func NewMemCache() *MemCache {
return &MemCache{
2023-06-30 14:16:16 +08:00
engine: cache.New(memCacheDefaultExpired, memCacheCleanupInterval),
2023-04-23 17:57:36 +08:00
}
}