Documentation
¶
Overview ¶
Package cache provides a caching orchestration layer implementation Supports multi-storage backend, event-driven failure, centralized configuration management
Index ¶
- Constants
- Variables
- type CacheInvalidator
- type CacheStats
- type CacheableConfig
- type ChainStore
- func (s *ChainStore) Close() error
- func (s *ChainStore) Delete(ctx context.Context, key string) error
- func (s *ChainStore) DeleteByPrefix(ctx context.Context, prefix string) error
- func (s *ChainStore) Exists(ctx context.Context, key string) bool
- func (s *ChainStore) Get(ctx context.Context, key string) ([]byte, error)
- func (s *ChainStore) Name() string
- func (s *ChainStore) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
- type Config
- type DefaultOrchestrator
- func (o *DefaultOrchestrator) Call(ctx context.Context, name string, args ...any) (any, error)
- func (o *DefaultOrchestrator) Close() error
- func (o *DefaultOrchestrator) GetStore(name string) (Store, error)
- func (o *DefaultOrchestrator) Invalidate(ctx context.Context, name string, args ...any) error
- func (o *DefaultOrchestrator) InvalidateByPattern(ctx context.Context, name string, pattern string) error
- func (o *DefaultOrchestrator) RegisterLoader(name string, loader LoaderFunc)
- func (o *DefaultOrchestrator) RegisterStore(name string, store Store)
- func (o *DefaultOrchestrator) SetSerializer(s Serializer)
- func (o *DefaultOrchestrator) Stats() *CacheStats
- type InvalidationRule
- type JSONSerializer
- type KeyBuilderFunc
- type LoaderFunc
- type MemoryStore
- func (s *MemoryStore) Close() error
- func (s *MemoryStore) Delete(ctx context.Context, key string) error
- func (s *MemoryStore) DeleteByPrefix(ctx context.Context, prefix string) error
- func (s *MemoryStore) Exists(ctx context.Context, key string) bool
- func (s *MemoryStore) Get(ctx context.Context, key string) ([]byte, error)
- func (s *MemoryStore) Name() string
- func (s *MemoryStore) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
- func (s *MemoryStore) Size() int
- type Orchestrator
- type RedisStore
- func (s *RedisStore) Close() error
- func (s *RedisStore) Delete(ctx context.Context, key string) error
- func (s *RedisStore) DeleteByPattern(ctx context.Context, pattern string) error
- func (s *RedisStore) DeleteByPrefix(ctx context.Context, prefix string) error
- func (s *RedisStore) Exists(ctx context.Context, key string) bool
- func (s *RedisStore) Get(ctx context.Context, key string) ([]byte, error)
- func (s *RedisStore) Name() string
- func (s *RedisStore) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
- type Serializer
- type Store
- type StoreConfig
Constants ¶
const ( // Cache layer error code: 70xxxx ErrCodeCacheMiss = 1 ErrCodeStoreNotFound = 2 ErrCodeLoaderNotFound = 3 ErrCodeSerialize = 4 ErrCodeDeserialize = 5 ErrCodeStoreGet = 6 ErrCodeStoreSet = 7 ErrCodeStoreDelete = 8 ErrCodeConfigInvalid = 9 ErrCodeCacheableNotFound = 10 )
Error code definitions
const (
ModuleCode = 70 // Cache module code
)
module code
Variables ¶
var ( // ErrCacheMiss cache miss ErrCacheMiss = errcode.New( ModuleCode, ErrCodeCacheMiss, "cache", "error.cache.miss", "缓存未命中", http.StatusOK, ) // ErrStoreNotFound Storage backend not found ErrStoreNotFound = errcode.New( ModuleCode, ErrCodeStoreNotFound, "cache", "error.cache.store_not_found", "存储后端未找到", http.StatusInternalServerError, ) // ErrorLoaderNotFound Loader not found ErrLoaderNotFound = errcode.New( ModuleCode, ErrCodeLoaderNotFound, "cache", "error.cache.loader_not_found", "缓存加载器未注册", http.StatusInternalServerError, ) // ErrSerialize serialization error ErrSerialize = errcode.New( ModuleCode, ErrCodeSerialize, "cache", "error.cache.serialize", "序列化失败", http.StatusInternalServerError, ) // Deserialization error ErrDeserialize = errcode.New( ModuleCode, ErrCodeDeserialize, "cache", "error.cache.deserialize", "反序列化失败", http.StatusInternalServerError, ) // ErrStoreGet Store retrieval error ErrStoreGet = errcode.New( ModuleCode, ErrCodeStoreGet, "cache", "error.cache.store_get", "存储获取失败", http.StatusInternalServerError, ) // ErrorStoreSettings store settings error ErrStoreSet = errcode.New( ModuleCode, ErrCodeStoreSet, "cache", "error.cache.store_set", "存储设置失败", http.StatusInternalServerError, ) // ErrStoreDelete storage deletion error ErrStoreDelete = errcode.New( ModuleCode, ErrCodeStoreDelete, "cache", "error.cache.store_delete", "存储删除失败", http.StatusInternalServerError, ) // ErrConfigInvalid Configuration invalid ErrConfigInvalid = errcode.New( ModuleCode, ErrCodeConfigInvalid, "cache", "error.cache.config_invalid", "缓存配置无效", http.StatusInternalServerError, ) // ErrCacheableNotFound Cache item not found ErrCacheableNotFound = errcode.New( ModuleCode, ErrCodeCacheableNotFound, "cache", "error.cache.cacheable_not_found", "缓存项未配置", http.StatusInternalServerError, ) )
Functions ¶
This section is empty.
Types ¶
type CacheInvalidator ¶
type CacheInvalidator interface {
// Returns the parameters list used for constructing cache keys
// For example: ArticleDeletedEvent returns []any{articleID}
CacheArgs() []any
}
CacheInvalidator cache invalidation interface After an event implements this interface, the cache component can automatically extract parameters to precisely invalidate caches
type CacheStats ¶
type CacheStats struct {
Hits int64 `json:"hits"`
Misses int64 `json:"misses"`
Invalidates int64 `json:"invalidates"`
Errors int64 `json:"errors"`
ByName map[string]int64 `json:"by_name"`
}
CacheStats cache statistics
type CacheableConfig ¶
type CacheableConfig struct {
// Name Cache item name (unique identifier)
Name string `mapstructure:"name"`
// KeyPattern key pattern, supports placeholders {0}, {1}, {hash}
KeyPattern string `mapstructure:"key_pattern"`
// TTL expiration time
TTL time.Duration `mapstructure:"ttl"`
// Store backend name
Store string `mapstructure:"store"`
// Whether to overlay local cache
LocalCache bool `mapstructure:"local_cache"`
// List of events for failed dependencies
DependsOn []string `mapstructure:"depends_on"`
// Enabled whether to enable
Enabled bool `mapstructure:"enabled"`
}
CacheableConfig cache item configuration
type ChainStore ¶
type ChainStore struct {
// contains filtered or unexported fields
}
ChainStore chained cache storage (multi-level caching)
func NewChainStore ¶
func NewChainStore(name string, stores ...Store) *ChainStore
NewChainStore creates chain storage
func (*ChainStore) Delete ¶
func (s *ChainStore) Delete(ctx context.Context, key string) error
Delete from all layers
func (*ChainStore) DeleteByPrefix ¶
func (s *ChainStore) DeleteByPrefix(ctx context.Context, prefix string) error
DeleteByPrefix delete by prefix from all layers
func (*ChainStore) Exists ¶
func (s *ChainStore) Exists(ctx context.Context, key string) bool
Exists Check if there is any existence (existence in any layer is sufficient)
type Config ¶
type Config struct {
// Enabled whether to enable caching
Enabled bool `mapstructure:"enabled"`
// DefaultTTL default expiration time
DefaultTTL time.Duration `mapstructure:"default_ttl"`
// DefaultStore default storage backend
DefaultStore string `mapstructure:"default_store"`
// Stores backend configuration
Stores map[string]StoreConfig `mapstructure:"stores"`
// Cacheable item configuration
Cacheables []CacheableConfig `mapstructure:"cacheables"`
// InvalidationRules invalidation rules
InvalidationRules []InvalidationRule `mapstructure:"invalidation_rules"`
}
Configuration for cache component
type DefaultOrchestrator ¶
type DefaultOrchestrator struct {
// contains filtered or unexported fields
}
DefaultOrchestrator default cache orchestration center implementation
func NewOrchestrator ¶
func NewOrchestrator(cfg *Config, dispatcher event.Dispatcher, log *logger.CtxZapLogger) *DefaultOrchestrator
NewOrchestrator creates the orchestrator center
func (*DefaultOrchestrator) Close ¶
func (o *DefaultOrchestrator) Close() error
Close Orchestrator Center
func (*DefaultOrchestrator) GetStore ¶
func (o *DefaultOrchestrator) GetStore(name string) (Store, error)
GetStore Retrieve storage backend
func (*DefaultOrchestrator) Invalidate ¶
Invalidate specified cache manually
func (*DefaultOrchestrator) InvalidateByPattern ¶
func (o *DefaultOrchestrator) InvalidateByPattern(ctx context.Context, name string, pattern string) error
InvalidateByPattern invalidate by pattern
func (*DefaultOrchestrator) RegisterLoader ¶
func (o *DefaultOrchestrator) RegisterLoader(name string, loader LoaderFunc)
RegisterLoader registers data loader
func (*DefaultOrchestrator) RegisterStore ¶
func (o *DefaultOrchestrator) RegisterStore(name string, store Store)
RegisterStore register storage backend
func (*DefaultOrchestrator) SetSerializer ¶
func (o *DefaultOrchestrator) SetSerializer(s Serializer)
SetSerializer set serializer
func (*DefaultOrchestrator) Stats ¶
func (o *DefaultOrchestrator) Stats() *CacheStats
Get cache statistics
type InvalidationRule ¶
type InvalidationRule struct {
// Event name for a failed trigger event
Event string `mapstructure:"event"`
// Invalidate list of cache items to be invalidated
Invalidate []string `mapstructure:"invalidate"`
// Pattern fails according to mode, e.g., "user:*"
// Note: Use only when bulk invalidation is needed; precise invalidation is recommended using the CacheInvalidator interface
Pattern string `mapstructure:"pattern"`
}
InvalidationRule invalidation rule
type JSONSerializer ¶
type JSONSerializer struct{}
JSONSerializer JSON serializer
func (*JSONSerializer) Deserialize ¶
func (s *JSONSerializer) Deserialize(data []byte, v any) error
Deserialize JSON to object
func (*JSONSerializer) Name ¶
func (s *JSONSerializer) Name() string
Name Returns the serializer name
type KeyBuilderFunc ¶
KeyBuilderFunc Key generation function
type LoaderFunc ¶
Loader function for data loading Call this function to retrieve data when cache miss occurs
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore memory cache storage
func NewMemoryStore ¶
func NewMemoryStore(name string, maxSize int) *MemoryStore
Create memory store
func (*MemoryStore) Delete ¶
func (s *MemoryStore) Delete(ctx context.Context, key string) error
Delete cache
func (*MemoryStore) DeleteByPrefix ¶
func (s *MemoryStore) DeleteByPrefix(ctx context.Context, prefix string) error
DeleteByPrefix delete by prefix
func (*MemoryStore) Exists ¶
func (s *MemoryStore) Exists(ctx context.Context, key string) bool
Exists check if Key exists
type Orchestrator ¶
type Orchestrator interface {
// RegisterLoader register data loader
RegisterLoader(name string, loader LoaderFunc)
// Call execute cache call
// Automatically handle cache reads, cache misses loading, and cache writes
Call(ctx context.Context, name string, args ...any) (any, error)
// Invalidate specified cache manually
Invalidate(ctx context.Context, name string, args ...any) error
// InvalidateByPattern invalidate by pattern
InvalidateByPattern(ctx context.Context, name string, pattern string) error
// GetStore Retrieve storage backend
GetStore(name string) (Store, error)
// RegisterStore register storage backend
RegisterStore(name string, store Store)
// Get cache statistics
Stats() *CacheStats
}
Orchestrator caching orchestration center interface
type RedisStore ¶
type RedisStore struct {
// contains filtered or unexported fields
}
RedisStore Redis cache storage
func NewRedisStore ¶
func NewRedisStore(name string, client *redis.Client, keyPrefix string) *RedisStore
Create new Redis storage
func (*RedisStore) Delete ¶
func (s *RedisStore) Delete(ctx context.Context, key string) error
Delete cache
func (*RedisStore) DeleteByPattern ¶
func (s *RedisStore) DeleteByPattern(ctx context.Context, pattern string) error
DeleteByPattern delete by pattern (supports wildcards)
func (*RedisStore) DeleteByPrefix ¶
func (s *RedisStore) DeleteByPrefix(ctx context.Context, prefix string) error
DeleteByPrefix delete by prefix
func (*RedisStore) Exists ¶
func (s *RedisStore) Exists(ctx context.Context, key string) bool
Exists check if Key exists
type Serializer ¶
type Serializer interface {
// Serialize object to byte array
Serialize(v any) ([]byte, error)
// Deserialize byte array to object
Deserialize(data []byte, v any) error
// Return serializer name
Name() string
}
Serializer serialization interface
type Store ¶
type Store interface {
// Name Returns the storage backend name
Name() string
// Get cache value
// Return ErrCacheMiss indicates a cache miss
Get(ctx context.Context, key string) ([]byte, error)
// Set cache value
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
// Delete cache
Delete(ctx context.Context, key string) error
// DeleteByPrefix delete by prefix
DeleteByPrefix(ctx context.Context, prefix string) error
// Exists check if Key exists
Exists(ctx context.Context, key string) bool
// Close storage connection
Close() error
}
Store cache storage interface All storage backends must implement this interface
type StoreConfig ¶
type StoreConfig struct {
// Type storage: redis, memory, chain
Type string `mapstructure:"type"`
// Redis related configuration
Instance string `mapstructure:"instance"` // Redis instance name
KeyPrefix string `mapstructure:"key_prefix"` // Key prefix
// Memory related configurations
MaxSize int `mapstructure:"max_size"` // Maximum item count
MaxMemory string `mapstructure:"max_memory"` // Maximum memory
Eviction string `mapstructure:"eviction"` // Eviction strategy: lru, lfu
// Chain related configurations
Layers []string `mapstructure:"layers"` // cache layer list
}
StoreConfig stores backend configuration