Files
waf-platform/EdgeNode/internal/encryption/cache.go

82 lines
1.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
package encryption
import (
"sync"
"time"
"github.com/TeaOSLab/EdgeNode/internal/utils/fasttime"
"github.com/TeaOSLab/EdgeNode/internal/utils/ttlcache"
)
// EncryptionCache 加密缓存
type EncryptionCache struct {
cache *ttlcache.Cache[[]byte]
}
var sharedCache *EncryptionCache
var sharedCacheOnce sync.Once
// SharedEncryptionCache 获取共享缓存实例
func SharedEncryptionCache(maxSize int, ttl time.Duration) *EncryptionCache {
sharedCacheOnce.Do(func() {
sharedCache = NewEncryptionCache(maxSize, ttl)
})
return sharedCache
}
// NewEncryptionCache 创建新缓存
func NewEncryptionCache(maxSize int, ttl time.Duration) *EncryptionCache {
cache := ttlcache.NewCache[[]byte](
ttlcache.NewMaxItemsOption(maxSize),
ttlcache.NewGCConfigOption().
WithBaseInterval(ttl).
WithMinInterval(ttl/2).
WithMaxInterval(ttl*2).
WithAdaptive(true),
)
return &EncryptionCache{
cache: cache,
}
}
// Get 获取缓存值
func (this *EncryptionCache) Get(key string) ([]byte, bool) {
item := this.cache.Read(key)
if item == nil {
return nil, false
}
// 检查是否过期
if item.ExpiresAt() < fasttime.Now().Unix() {
return nil, false
}
// 复制数据,避免外部修改
result := make([]byte, len(item.Value))
copy(result, item.Value)
return result, true
}
// Set 设置缓存值
func (this *EncryptionCache) Set(key string, value []byte, ttlSeconds int64) {
// 复制数据,避免外部修改
copied := make([]byte, len(value))
copy(copied, value)
expiresAt := fasttime.Now().Unix() + ttlSeconds
this.cache.Write(key, copied, expiresAt)
}
// Clear 清空缓存TTL 缓存会自动过期,这里不需要手动清空)
func (this *EncryptionCache) Clear() {
// TTL 缓存会自动过期,不需要手动清空
}
// Len 获取缓存大小
func (this *EncryptionCache) Len() int {
return this.cache.Count()
}