Documentation
¶
Index ¶
- Constants
- Variables
- func Bool(value bool) *bool
- func EscapeRedisGlobLiteral(value string) string
- func RedisPrefixPattern(prefix string) string
- type CacheType
- type CollectionPageStore
- type Decoder
- type Encoder
- type Entry
- type ExtendedMetrics
- type FieldsEmptyStore
- type GuardedPatternStore
- type HashFieldsStore
- type Item
- type LoadParams
- type LoadThroughBatchAdminItem
- type LoadThroughBatchAdminResponse
- type LoadThroughBatchError
- type LoadThroughBatchOptions
- type LoadThroughBatchResult
- type LoadThroughBatchSummary
- type LoadThroughItem
- type LoadThroughOptions
- type Loader
- type LockGuard
- type Logger
- type LookupMetrics
- type LookupResult
- type LookupState
- type Manager
- func (m *Manager) DeleteByKey(ctx context.Context, key string) error
- func (m *Manager) DeleteByPrefix(ctx context.Context, prefix string) error
- func (m *Manager) Get(ctx context.Context, key string, dest any) (bool, error)
- func (m *Manager) GetOrRefresh(ctx context.Context, key string, dest any) (LookupResult, error)
- func (m *Manager) GetOrRefreshWithLoader(ctx context.Context, key string, dest any, loader Loader) (LookupResult, error)
- func (m *Manager) GetOrRefreshWithOptions(ctx context.Context, key string, dest any, options LoadThroughOptions) (LookupResult, error)
- func (m *Manager) GetState(ctx context.Context, key string, dest any) (LookupResult, error)
- func (m *Manager) IsFixedKey(key string) bool
- func (m *Manager) Items() []Item
- func (m *Manager) LoadThrough(ctx context.Context, key string, dest any, loader Loader) (LookupResult, error)
- func (m *Manager) LoadThroughBatch(ctx context.Context, items []LoadThroughItem) []LoadThroughBatchResult
- func (m *Manager) LoadThroughBatchWithBatchOptions(ctx context.Context, items []LoadThroughItem, options LoadThroughBatchOptions) []LoadThroughBatchResult
- func (m *Manager) LoadThroughBatchWithSummary(ctx context.Context, items []LoadThroughItem) ([]LoadThroughBatchResult, LoadThroughBatchSummary, error)
- func (m *Manager) LoadThroughBatchWithSummaryOptions(ctx context.Context, items []LoadThroughItem, options LoadThroughBatchOptions) ([]LoadThroughBatchResult, LoadThroughBatchSummary, error)
- func (m *Manager) LoadThroughWithOptions(ctx context.Context, key string, dest any, options LoadThroughOptions) (LookupResult, error)
- func (m *Manager) RefreshAll(ctx context.Context) error
- func (m *Manager) RefreshAllDetailed(ctx context.Context) []RefreshBatchResult
- func (m *Manager) RefreshAllWithSummary(ctx context.Context) ([]RefreshBatchResult, RefreshBatchSummary, error)
- func (m *Manager) RefreshByKey(ctx context.Context, key string, fields ...string) error
- func (m *Manager) RefreshByKeys(ctx context.Context, keys []string) error
- func (m *Manager) RefreshByKeysDetailed(ctx context.Context, keys []string) []RefreshBatchResult
- func (m *Manager) RefreshByKeysWithSummary(ctx context.Context, keys []string) ([]RefreshBatchResult, RefreshBatchSummary, error)
- type MarkerReplaceStore
- type Metrics
- type Option
- func WithDecoder(decoder Decoder) Option
- func WithEmptyMarker(marker string, ttl time.Duration) Option
- func WithGoUtilsLogger(logger utils.Logger) Option
- func WithKeyPrefix(prefix string) Option
- func WithLoaderConcurrency(concurrency int) Option
- func WithLoaderTimeout(timeout time.Duration) Option
- func WithLockRenewInterval(interval time.Duration) Option
- func WithLockTTL(ttl time.Duration) Option
- func WithLogKeyRedaction(enabled bool) Option
- func WithLogger(logger Logger) Option
- func WithMetrics(metrics Metrics) Option
- func WithPrefixDeleteConcurrency(concurrency int) Option
- func WithPrefixEpochTTL(ttl time.Duration) Option
- func WithPrefixKeyIndex(enabled bool) Option
- func WithPrefixKeyIndexTTL(ttl time.Duration) Option
- func WithRebuildContextPolicy(policy RebuildContextPolicy) Option
- func WithRebuildResultTTL(ttl time.Duration) Option
- func WithRefreshConcurrency(concurrency int) Option
- func WithScanCount(count int64) Option
- func WithScanFallback(enabled bool) Option
- func WithWait(step time.Duration, times int) Option
- type PipelineExecError
- type PrefixIndexMutation
- type PrefixIndexStore
- type PrefixMutationTopologyStore
- type PrefixMutationValidator
- type PrefixReplaceMutation
- type PrefixReplaceStore
- type PrometheusMetrics
- func (m *PrometheusMetrics) RecordCacheHit(ctx context.Context, index string)
- func (m *PrometheusMetrics) RecordCacheMiss(ctx context.Context, index string)
- func (m *PrometheusMetrics) RecordEmptyMarkerWrite(ctx context.Context, index string)
- func (m *PrometheusMetrics) RecordLoaderError(ctx context.Context, index string, err error)
- func (m *PrometheusMetrics) RecordLockFailed(ctx context.Context, index string)
- func (m *PrometheusMetrics) RecordLookupRefreshTriggered(ctx context.Context, index string)
- func (m *PrometheusMetrics) RecordLookupState(ctx context.Context, index string, state LookupState)
- func (m *PrometheusMetrics) RecordPrefixDelete(ctx context.Context, index string, prefix string, count int64)
- func (m *PrometheusMetrics) RecordPrefixRetry(ctx context.Context, index string)
- func (m *PrometheusMetrics) RecordPrefixWait(ctx context.Context, index string)
- func (m *PrometheusMetrics) RecordRefresh(ctx context.Context, index string, result string, duration time.Duration)
- func (m *PrometheusMetrics) RecordRefreshBatch(ctx context.Context, mode string, result string, total int, success int, ...)
- func (m *PrometheusMetrics) RecordRefreshEntryCount(ctx context.Context, index string, count int)
- func (m *PrometheusMetrics) RecordScanFallback(ctx context.Context, index string, prefix string)
- func (m *PrometheusMetrics) RecordWaitTimeout(ctx context.Context, index string)
- type PrometheusMetricsConfig
- type PrometheusMetricsOption
- func WithPrometheusNamespace(namespace string) PrometheusMetricsOption
- func WithPrometheusRefreshBuckets(buckets []float64) PrometheusMetricsOption
- func WithPrometheusRefreshEntryBuckets(buckets []float64) PrometheusMetricsOption
- func WithPrometheusRegisterer(registerer prometheus.Registerer) PrometheusMetricsOption
- func WithPrometheusSubsystem(subsystem string) PrometheusMetricsOption
- type ReadPageOptions
- type ReadPageResult
- type RebuildContextPolicy
- type RedisStore
- func (s *RedisStore) AcquireRefreshLock(ctx context.Context, key string, value string, ttl time.Duration) (bool, string, error)
- func (s *RedisStore) AllowsPrefixMutation(prefix string) bool
- func (s *RedisStore) ApplyMutation(ctx context.Context, mutation StoreMutation) error
- func (s *RedisStore) DeleteHashFields(ctx context.Context, guards []LockGuard, key string, registryKey string, ...) error
- func (s *RedisStore) DeletePatternGuarded(ctx context.Context, pattern string, count int64, guards []LockGuard) (int64, error)
- func (s *RedisStore) DeletePrefixIndexKeys(ctx context.Context, indexKey string, count int64, guards []LockGuard) (int64, error)
- func (s *RedisStore) Exists(ctx context.Context, key string) (bool, error)
- func (s *RedisStore) ExistsMulti(ctx context.Context, keys ...string) (map[string]bool, error)
- func (s *RedisStore) HasFieldsEmpty(ctx context.Context, registryKey string, fieldsID string) (bool, error)
- func (s *RedisStore) Read(ctx context.Context, key string, typ CacheType) (any, error)
- func (s *RedisStore) ReadPage(ctx context.Context, key string, typ CacheType, options ReadPageOptions) (ReadPageResult, error)
- func (s *RedisStore) RefreshLock(ctx context.Context, key string, value string, ttl time.Duration) (bool, error)
- func (s *RedisStore) ReleaseLock(ctx context.Context, key string, value string) (bool, error)
- func (s *RedisStore) ReplaceFieldsWithEmpty(ctx context.Context, guards []LockGuard, key string, registryKey string, ...) error
- func (s *RedisStore) ReplacePrefix(ctx context.Context, mutation PrefixReplaceMutation) (int64, error)
- func (s *RedisStore) ReplaceWithMarker(ctx context.Context, guards []LockGuard, marker Entry, deleteKeys ...string) error
- func (s *RedisStore) ValidatePrefixMutation(ctx context.Context, prefix string) error
- func (s *RedisStore) ValidateTablecacheStore() error
- type RedisStoreOption
- func WithDefaultJitterRatio(ratio float64) RedisStoreOption
- func WithMaxCollectionReadCount(limit int64) RedisStoreOption
- func WithMaxCollectionWriteCount(limit int) RedisStoreOption
- func WithPipelineRetries(retries int) RedisStoreOption
- func WithRedisEncoder(encoder Encoder) RedisStoreOption
- func WithUnlinkChunkSize(size int) RedisStoreOption
- type RefreshBatchAdminItem
- type RefreshBatchAdminResponse
- type RefreshBatchError
- type RefreshBatchMetrics
- type RefreshBatchResult
- type RefreshBatchSummary
- type ScanFallbackMetrics
- type Store
- type StoreMutation
- type StoreValidator
- type Target
- type ZMember
Constants ¶
const ( // AdminCodeOK 表示管理页操作执行成功。 AdminCodeOK = "ok" // AdminCodePartialFailure 表示批量操作中存在失败项。 AdminCodePartialFailure = "partial_failure" // AdminCodeInvalidRequest 表示请求或配置不符合当前缓存操作约束。 AdminCodeInvalidRequest = "invalid_request" // AdminCodeTargetNotFound 表示请求的缓存目标未注册。 AdminCodeTargetNotFound = "target_not_found" // AdminCodeLoaderRequired 表示缓存目标缺少回源加载器。 AdminCodeLoaderRequired = "loader_required" // AdminCodeWaitTimeout 表示等待缓存重建超时。 AdminCodeWaitTimeout = "wait_timeout" AdminCodeRefreshUnavailable = "refresh_unavailable" // AdminCodeCacheMiss 表示缓存最终仍未命中。 AdminCodeCacheMiss = "cache_miss" // AdminCodeDataNotFound 表示源数据不存在。 AdminCodeDataNotFound = "data_not_found" // AdminCodeInvalidKey 表示缓存 key 或前缀不符合约束。 AdminCodeInvalidKey = "invalid_key" // AdminCodeScanDisabled 表示当前禁止前缀删除降级扫描。 AdminCodeScanDisabled = "scan_fallback_disabled" // AdminCodeCollectionTooLarge 表示缓存集合超过安全上限。 AdminCodeCollectionTooLarge = "collection_too_large" // AdminCodeInternalError 表示未公开内部细节的执行错误。 AdminCodeInternalError = "internal_error" )
const (
// DefaultEmptyMarker 表示空值缓存占位符,用于缓存穿透保护。
DefaultEmptyMarker = "__empty__"
)
Variables ¶
var ( // ErrTargetNotFound 表示没有找到匹配的缓存目标配置。 ErrTargetNotFound = errors.New("tablecache target not found") // ErrLoaderRequired 表示缓存目标缺少数据加载函数。 ErrLoaderRequired = errors.New("tablecache loader required") // ErrWaitRebuildTimeout 表示等待其它实例重建缓存超时。 ErrWaitRebuildTimeout = errors.New("tablecache wait rebuild timeout") // ErrRefreshLockLost 表示当前实例在刷新过程中失去重建锁所有权。 ErrRefreshLockLost = errors.New("tablecache refresh lock lost") // ErrCacheMiss 表示缓存未命中。 ErrCacheMiss = errors.New("tablecache cache miss") // ErrNotFound 表示加载器确认源数据不存在,可触发空值占位。 ErrNotFound = errors.New("tablecache data not found") // ErrKeyPrefixRequired 表示刷新、删除或写回操作必须使用已带 Manager 指定前缀的实际 Redis key。 ErrKeyPrefixRequired = errors.New("tablecache key prefix required") // ErrInvalidClusterHashTag 表示 key 中的花括号无法安全生成 Redis Cluster 同槽元信息 key。 ErrInvalidClusterHashTag = errors.New("tablecache invalid redis cluster hash tag key") // ErrDistributedPrefixHashTagRequired 表示分布式 Redis 的前缀全量写删缺少固定 hash tag。 ErrDistributedPrefixHashTagRequired = errors.New("tablecache distributed prefix hash tag required") // ErrEntryKeyOutOfScope 表示加载器返回了不属于当前缓存目标管理范围的写入 key。 ErrEntryKeyOutOfScope = errors.New("tablecache entry key out of target scope") // ErrRefreshInvalidated 表示刷新期间发生显式删除,当前刷新结果已失效。 ErrRefreshInvalidated = errors.New("tablecache refresh invalidated") // ErrScanFallbackDisabled 表示 DeleteByPrefix 需要降级 SCAN,但当前配置禁止降级。 ErrScanFallbackDisabled = errors.New("tablecache scan fallback disabled") // ErrCollectionTooLarge 表示集合读写超过配置上限。 ErrCollectionTooLarge = errors.New("tablecache collection too large") // ErrInvalidKeyPrefix 表示 key 前缀不符合生产安全配置。 ErrInvalidKeyPrefix = errors.New("tablecache invalid key prefix") // ErrInvalidConfig 表示 Manager 或 Target 配置存在不安全取值。 ErrInvalidConfig = errors.New("tablecache invalid config") // ErrPartialHashUnsupported 表示当前 Store 或目标配置不支持安全的 Hash 局部刷新。 ErrPartialHashUnsupported = errors.New("tablecache partial hash unsupported") // ErrPrefixReplaceUnsupported 表示 Store 不支持无破坏的前缀全量替换。 ErrPrefixReplaceUnsupported = errors.New("tablecache prefix replace unsupported") // ErrPrefixDeleteUnsupported 表示 Store 不支持带锁校验的前缀删除。 ErrPrefixDeleteUnsupported = errors.New("tablecache prefix delete unsupported") // ErrRedisTopologyUnsupported 表示当前 Redis 客户端拓扑不能安全满足 table-cache 一致性契约。 ErrRedisTopologyUnsupported = errors.New("tablecache redis topology unsupported") // ErrMarkerReplaceUnsupported 表示 Store 不支持 marker 与旧缓存的安全切换。 ErrMarkerReplaceUnsupported = errors.New("tablecache marker replace unsupported") )
var ErrPrefixIndexUntrusted = errors.New("tablecache prefix index untrusted")
ErrPrefixIndexUntrusted 表示前缀索引完整性证据缺失,调用方必须撤销 ready 并降级全节点 SCAN。
Functions ¶
func EscapeRedisGlobLiteral ¶ added in v1.22.2
EscapeRedisGlobLiteral 转义 Redis glob 元字符,避免业务前缀被解释成通配表达式。
func RedisPrefixPattern ¶ added in v1.22.2
RedisPrefixPattern 把 Redis key 前缀转换成只匹配该字面前缀的 glob pattern。
Types ¶
type CacheType ¶
type CacheType string
CacheType 表示 Redis 目标数据结构类型。
const ( // TypeString 表示 Redis String 缓存类型。 TypeString CacheType = "string" // TypeHash 表示 Redis Hash 缓存类型。 TypeHash CacheType = "hash" // TypeList 表示 Redis List 缓存类型。 TypeList CacheType = "list" // TypeSet 表示 Redis Set 缓存类型。 TypeSet CacheType = "set" // TypeZSet 表示 Redis ZSet 缓存类型。 TypeZSet CacheType = "zset" )
type CollectionPageStore ¶
type CollectionPageStore interface {
// ReadPage 按缓存类型分页读取 Redis 原始值。
ReadPage(ctx context.Context, key string, typ CacheType, options ReadPageOptions) (ReadPageResult, error)
}
CollectionPageStore 表示可选的集合分页读取能力。 RedisStore 默认实现该接口;业务可用它替代 HGetAll/LRange 0 -1 等全量读取。
type Entry ¶
type Entry struct {
Key string // Key 是最终写入的 Redis key
Type CacheType // Type 是最终写入的 Redis 数据结构类型
Value any // Value 是写入值,类型由 Type 决定
TTL time.Duration // TTL 是当前 key 的基础过期时间
Jitter time.Duration // Jitter 是当前 key 的过期时间抖动范围
Overwrite *bool // Overwrite 控制是否覆盖旧值;nil 默认覆盖,String/List 不支持 false
}
Entry 表示一次写入 Redis 的标准缓存数据。
type ExtendedMetrics ¶
type ExtendedMetrics interface {
Metrics
// RecordLoaderError 记录加载器回源错误次数与错误信息。
RecordLoaderError(ctx context.Context, index string, err error)
// RecordEmptyMarkerWrite 记录空值占位写入次数。
RecordEmptyMarkerWrite(ctx context.Context, index string)
// RecordWaitTimeout 记录等待其它实例重建超时次数。
RecordWaitTimeout(ctx context.Context, index string)
// RecordPrefixWait 记录前缀全量刷新阻塞单 key 刷新的次数。
RecordPrefixWait(ctx context.Context, index string)
// RecordPrefixRetry 记录单 key 刷新因前缀全量刷新而重试的次数。
RecordPrefixRetry(ctx context.Context, index string)
// RecordPrefixDelete 记录前缀删除次数与删除 key 数量。
RecordPrefixDelete(ctx context.Context, index string, prefix string, count int64)
// RecordRefreshEntryCount 记录单次刷新写入条数。
RecordRefreshEntryCount(ctx context.Context, index string, count int)
}
ExtendedMetrics 定义可选的细分指标接口;实现后 Manager 会自动记录更丰富的生产排障指标。
type FieldsEmptyStore ¶ added in v1.22.2
type FieldsEmptyStore interface {
// ReplaceFieldsWithEmpty 删除请求字段并按独立 TTL 登记字段组合为空。
ReplaceFieldsWithEmpty(ctx context.Context, guards []LockGuard, key string, registryKey string, fieldsID string, fields []string, ttl time.Duration) error
// HasFieldsEmpty 判断字段组合是否仍在有效期内。
HasFieldsEmpty(ctx context.Context, registryKey string, fieldsID string) (bool, error)
}
FieldsEmptyStore 定义 Hash 字段组合空值的有界 registry 能力。
type GuardedPatternStore ¶ added in v1.22.2
type GuardedPatternStore interface {
// DeletePatternGuarded 仅在全部 guard 仍归当前请求持有时删除每批匹配 key。
DeletePatternGuarded(ctx context.Context, pattern string, count int64, guards []LockGuard) (int64, error)
}
GuardedPatternStore 定义带锁 owner 原子校验的 SCAN 删除能力。
type HashFieldsStore ¶ added in v1.22.2
type HashFieldsStore interface {
// DeleteHashFields 仅在全部 guard 仍归当前请求持有时删除指定 Hash 字段,并清除该 Hash 的字段空值 registry。
DeleteHashFields(ctx context.Context, guards []LockGuard, key string, registryKey string, fields []string) error
}
HashFieldsStore 定义带锁删除部分 Hash 字段的能力。 RedisStore 默认实现该接口;fields 回源为空时必须删除请求范围内的旧值,不能把过期字段继续当成命中。
type Item ¶
type Item struct {
Index string `json:"index"` // Index 是缓存目标索引
Title string `json:"title"` // Title 是缓存目标展示名称
Key string `json:"key"` // Key 是注册后的固定 Redis key 或 Redis key 前缀
KeyTitle string `json:"keyTitle"` // KeyTitle 是 Redis key 展示模板
Type string `json:"type"` // Type 是 Redis 数据类型
Remark string `json:"remark"` // Remark 是缓存说明
}
Item 表示缓存管理页可展示的缓存目标。
type LoadParams ¶
type LoadParams struct {
Target Target // Target 是当前命中的缓存目标配置
Key string // Key 是本次请求刷新或读取的 Redis key
Index string // Index 是缓存目标索引
KeyParts []string // KeyParts 是去掉目标前缀后的 key 片段
Fields []string // Fields 是 Hash 等二级索引字段,用于局部刷新
}
LoadParams 表示缓存目标加载时的上下文参数。
type LoadThroughBatchAdminItem ¶
type LoadThroughBatchAdminItem struct {
Key string `json:"key"` // Key 是当前批量项的缓存 key
Success bool `json:"success"` // Success 表示当前批量项是否执行成功
Code string `json:"code"` // Code 是稳定且不包含内部细节的结果码
Message string `json:"message"` // Message 是可安全展示的结果文案
State LookupState `json:"state"` // State 是当前批量项最终命中状态
Refreshed bool `json:"refreshed"` // Refreshed 表示当前批量项是否参与了执行、等待或复用刷新结果
Error error `json:"-"` // Error 保留原始错误,供调用方在受控日志中使用
}
LoadThroughBatchAdminItem 表示管理页可直接返回的单条批量读穿结果。
type LoadThroughBatchAdminResponse ¶
type LoadThroughBatchAdminResponse struct {
Success bool `json:"success"` // Success 表示整批是否全部成功
Code string `json:"code"` // Code 是稳定且不包含内部细节的结果码
Message string `json:"message"` // Message 是面向管理页展示的安全文案
Error error `json:"-"` // Error 保留整批聚合错误,供调用方在受控日志中使用
Summary LoadThroughBatchSummary `json:"summary"` // Summary 是当前批量结果的汇总统计
Items []LoadThroughBatchAdminItem `json:"items"` // Items 是当前批量每一项的明细结果
}
LoadThroughBatchAdminResponse 表示管理页批量读穿接口可直接返回的标准 JSON 结构。
func BuildLoadThroughBatchAdminResponse ¶
func BuildLoadThroughBatchAdminResponse(results []LoadThroughBatchResult) LoadThroughBatchAdminResponse
BuildLoadThroughBatchAdminResponse 根据批量结果构建管理页标准响应结构。
func BuildLoadThroughBatchAdminResponseWithSummary ¶
func BuildLoadThroughBatchAdminResponseWithSummary(results []LoadThroughBatchResult, summary LoadThroughBatchSummary, err error) LoadThroughBatchAdminResponse
BuildLoadThroughBatchAdminResponseWithSummary 根据批量结果、汇总信息和聚合错误构建管理页标准响应结构。
type LoadThroughBatchError ¶
type LoadThroughBatchError struct {
Summary LoadThroughBatchSummary // Summary 是当前批量结果的汇总信息
}
LoadThroughBatchError 表示批量读穿存在失败项的聚合错误。
func (*LoadThroughBatchError) Error ¶
func (e *LoadThroughBatchError) Error() string
Error 返回批量读穿聚合错误描述。
type LoadThroughBatchOptions ¶
type LoadThroughBatchOptions struct {
Concurrency int // Concurrency 是本批次读穿的并发度,0 表示沿用 Manager 默认配置,有效范围为0到256
DefaultOptions LoadThroughOptions // DefaultOptions 是本批次所有条目的默认读穿参数,条目级 Options 优先级更高
}
LoadThroughBatchOptions 表示一批读穿请求的批次级配置。
type LoadThroughBatchResult ¶
type LoadThroughBatchResult struct {
Key string `json:"key"` // Key 是当前批量项的缓存 key
LookupResult LookupResult `json:"lookupResult"` // LookupResult 是当前批量项的读取结果
Error error `json:"-"` // Error 是当前批量项的执行错误
}
LoadThroughBatchResult 表示单条批量读穿请求的执行结果。
type LoadThroughBatchSummary ¶
type LoadThroughBatchSummary struct {
Total int `json:"total"` // Total 是批量请求总数
Success int `json:"success"` // Success 是执行成功的条数
Failed int `json:"failed"` // Failed 是执行失败的条数
Hit int `json:"hit"` // Hit 是最终命中缓存数据的条数
Miss int `json:"miss"` // Miss 是最终仍未命中的条数
Empty int `json:"empty"` // Empty 是命中空值占位的条数
Refreshed int `json:"refreshed"` // Refreshed 是批次中参与刷新流程的条数
FailedKeys []string `json:"failedKeys"` // FailedKeys 是执行失败的 key 列表
}
LoadThroughBatchSummary 表示一批读穿请求的汇总结果。
func SummarizeLoadThroughBatchResults ¶
func SummarizeLoadThroughBatchResults(results []LoadThroughBatchResult) LoadThroughBatchSummary
SummarizeLoadThroughBatchResults 汇总批量读穿结果,便于任务调度和批处理统一判断。
func (LoadThroughBatchSummary) HasError ¶
func (s LoadThroughBatchSummary) HasError() bool
HasError 返回当前批量汇总是否包含失败项。
type LoadThroughItem ¶
type LoadThroughItem struct {
Key string // Key 是本次批量读穿的目标缓存 key
Dest any // Dest 是当前 key 的反序列化目标对象
Options LoadThroughOptions // Options 是当前 key 的读穿可选参数
}
LoadThroughItem 表示一条批量读穿请求。
type LoadThroughOptions ¶
type LoadThroughOptions struct {
Fields []string // Fields 是本次读穿时透传给 Loader 的字段列表,适用于 Hash 等局部刷新场景
Loader Loader // Loader 是本次调用临时覆盖的回源加载器,nil 表示继续使用 Target.Loader
LoaderTimeout time.Duration // LoaderTimeout 是本次读穿回源超时时间,优先级高于 Target.LoaderTimeout
AllowEmptyMarker *bool // AllowEmptyMarker 控制本次 miss 回源是否允许写入空值占位,nil 表示沿用目标配置
ContextPolicy *RebuildContextPolicy // ContextPolicy 控制本次读穿是否忽略调用方取消信号,nil 表示沿用管理器配置
}
LoadThroughOptions 表示单次读穿缓存调用的可选参数。
type Loader ¶
type Loader func(ctx context.Context, params LoadParams) ([]Entry, error)
Loader 表示缓存目标的数据加载函数,由业务项目自行适配数据库、RPC 或其它数据源。
type LockGuard ¶ added in v1.22.2
type LockGuard struct {
Key string // Key 是刷新锁 Redis key
Owner string // Owner 是抢锁前生成且仅当前请求持有的随机标识
}
LockGuard 表示一次 Redis 提交必须仍持有的分布式锁 owner。
type Logger ¶
type Logger interface {
// Infof 输出信息日志。
Infof(format string, args ...any)
// Warnf 输出警告日志。
Warnf(format string, args ...any)
}
Logger 定义可选的 printf 风格日志接口。 go-utils.Logger 应通过 WithGoUtilsLogger 接入。
type LookupMetrics ¶
type LookupMetrics interface {
Metrics
// RecordLookupState 记录读取最终状态(hit/miss/empty)。
RecordLookupState(ctx context.Context, index string, state LookupState)
// RecordLookupRefreshTriggered 记录 GetOrRefresh/LoadThrough 在 miss 后触发回源刷新的次数。
RecordLookupRefreshTriggered(ctx context.Context, index string)
}
LookupMetrics 定义读取链路细分指标接口,用于区分 hit/miss/empty 与读穿刷新触发次数。
type LookupResult ¶
type LookupResult struct {
State LookupState `json:"state"` // State 是本次读取最终状态
Refreshed bool `json:"refreshed"` // Refreshed 表示本次 miss 是否参与了刷新流程,包括执行、等待或复用同一轮结果
}
LookupResult 表示一次缓存读取或“读取后按需刷新”的结果。
type LookupState ¶
type LookupState string
LookupState 表示缓存读取状态。
const ( // LookupStateHit 表示缓存命中且已成功写入目标对象。 LookupStateHit LookupState = "hit" // LookupStateMiss 表示缓存未命中,且当前没有空值占位。 LookupStateMiss LookupState = "miss" // LookupStateEmpty 表示缓存已确认源数据为空,命中了空值占位。 LookupStateEmpty LookupState = "empty" )
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager 管理一组表数据缓存目标,负责刷新、锁保护、TTL 抖动与空值占位。
func NewManager ¶
NewManager 创建通用表缓存管理器。
func (*Manager) DeleteByKey ¶
DeleteByKey 删除指定 Redis key;前缀删除请使用 DeleteByPrefix。
func (*Manager) DeleteByPrefix ¶
DeleteByPrefix 删除指定 Redis key 前缀下的所有缓存。
func (*Manager) GetOrRefresh ¶
GetOrRefresh 先读取缓存;仅当真实未命中时触发刷新,命中空值占位时直接返回 empty。
func (*Manager) GetOrRefreshWithLoader ¶
func (m *Manager) GetOrRefreshWithLoader(ctx context.Context, key string, dest any, loader Loader) (LookupResult, error)
GetOrRefreshWithLoader 先读取缓存;miss 时使用本次传入的 Loader 回源、回填并返回最新结果。
func (*Manager) GetOrRefreshWithOptions ¶
func (m *Manager) GetOrRefreshWithOptions(ctx context.Context, key string, dest any, options LoadThroughOptions) (LookupResult, error)
GetOrRefreshWithOptions 先读取缓存;miss 时按本次 options 配置执行回源、回填并返回最新结果。
func (*Manager) IsFixedKey ¶
IsFixedKey 判断 key 是否为固定内置缓存 key,模板和前缀型 key 不纳入固定 key。
func (*Manager) LoadThrough ¶
func (m *Manager) LoadThrough(ctx context.Context, key string, dest any, loader Loader) (LookupResult, error)
LoadThrough 提供更贴近业务侧语义的读穿缓存入口,内部复用 GetOrRefreshWithLoader。
func (*Manager) LoadThroughBatch ¶
func (m *Manager) LoadThroughBatch(ctx context.Context, items []LoadThroughItem) []LoadThroughBatchResult
LoadThroughBatch 批量执行读穿缓存;每个条目独立返回结果,单条失败不会中断整批处理。
func (*Manager) LoadThroughBatchWithBatchOptions ¶
func (m *Manager) LoadThroughBatchWithBatchOptions(ctx context.Context, items []LoadThroughItem, options LoadThroughBatchOptions) []LoadThroughBatchResult
LoadThroughBatchWithBatchOptions 批量执行读穿缓存,并支持批次级默认参数和并发度覆盖。
func (*Manager) LoadThroughBatchWithSummary ¶
func (m *Manager) LoadThroughBatchWithSummary(ctx context.Context, items []LoadThroughItem) ([]LoadThroughBatchResult, LoadThroughBatchSummary, error)
LoadThroughBatchWithSummary 批量执行读穿缓存,并返回汇总信息与聚合错误,便于任务调度快速判定整批状态。
func (*Manager) LoadThroughBatchWithSummaryOptions ¶
func (m *Manager) LoadThroughBatchWithSummaryOptions(ctx context.Context, items []LoadThroughItem, options LoadThroughBatchOptions) ([]LoadThroughBatchResult, LoadThroughBatchSummary, error)
LoadThroughBatchWithSummaryOptions 批量执行读穿缓存,并支持批次级默认参数、并发覆盖和汇总结果返回。
func (*Manager) LoadThroughWithOptions ¶
func (m *Manager) LoadThroughWithOptions(ctx context.Context, key string, dest any, options LoadThroughOptions) (LookupResult, error)
LoadThroughWithOptions 提供带可选参数的完整读穿缓存入口,适用于字段级局部刷新和临时覆盖 Loader。
func (*Manager) RefreshAll ¶
RefreshAll 刷新全部允许批量重建的缓存目标。
func (*Manager) RefreshAllDetailed ¶
func (m *Manager) RefreshAllDetailed(ctx context.Context) []RefreshBatchResult
RefreshAllDetailed 刷新全部允许批量重建的缓存目标,并逐项返回执行结果。
func (*Manager) RefreshAllWithSummary ¶
func (m *Manager) RefreshAllWithSummary(ctx context.Context) ([]RefreshBatchResult, RefreshBatchSummary, error)
RefreshAllWithSummary 刷新全部允许批量重建的缓存目标,并返回汇总信息与聚合错误。
func (*Manager) RefreshByKey ¶
RefreshByKey 根据 Redis key 刷新匹配的缓存目标。
func (*Manager) RefreshByKeys ¶
RefreshByKeys 批量刷新多个缓存 key;同 key 会自动去重。
func (*Manager) RefreshByKeysDetailed ¶
func (m *Manager) RefreshByKeysDetailed(ctx context.Context, keys []string) []RefreshBatchResult
RefreshByKeysDetailed 批量刷新多个缓存 key,并逐项返回执行结果。
func (*Manager) RefreshByKeysWithSummary ¶
func (m *Manager) RefreshByKeysWithSummary(ctx context.Context, keys []string) ([]RefreshBatchResult, RefreshBatchSummary, error)
RefreshByKeysWithSummary 批量刷新多个缓存 key,并返回汇总信息与聚合错误。
type MarkerReplaceStore ¶ added in v1.22.2
type MarkerReplaceStore interface {
// ReplaceWithMarker 先写入 marker,成功后再删除同槽旧 key。
ReplaceWithMarker(ctx context.Context, guards []LockGuard, marker Entry, deleteKeys ...string) error
}
MarkerReplaceStore 定义 String marker 与旧缓存的一致切换能力。
type Metrics ¶
type Metrics interface {
// RecordRefresh 记录一次刷新执行的结果与耗时。
RecordRefresh(ctx context.Context, index string, result string, duration time.Duration)
// RecordCacheHit 记录一次缓存命中次数。
RecordCacheHit(ctx context.Context, index string)
// RecordCacheMiss 记录一次缓存未命中次数。
RecordCacheMiss(ctx context.Context, index string)
// RecordLockFailed 记录一次分布式锁竞争失败次数。
RecordLockFailed(ctx context.Context, index string)
}
Metrics 定义 tablecache 运行指标记录接口,可由 Prometheus、StatsD 或自定义埋点实现。
type Option ¶
type Option func(*Manager)
Option 表示 Manager 的可选配置。
func WithEmptyMarker ¶
WithEmptyMarker 设置空值缓存占位内容和默认过期时间。
func WithGoUtilsLogger ¶
WithGoUtilsLogger 设置 go-utils.Logger 日志适配器。 推荐在项目已统一使用 utils.Configure(utils.WithLogger(...)) 时直接传入 utils.Log()。
func WithKeyPrefix ¶
WithKeyPrefix 设置业务缓存 key 命名空间前缀,用于把 tablecache 管理的业务数据与其它 Redis key 隔离。 默认前缀为 "tc:";配置必须以冒号结尾,刷新、删除和写回只接受已带该前缀的实际 Redis key。
func WithLoaderConcurrency ¶ added in v1.22.2
WithLoaderConcurrency 设置单个 Manager 同时执行的 Loader 数量。
func WithLoaderTimeout ¶
WithLoaderTimeout 设置默认 Loader 超时时间。
func WithLockRenewInterval ¶
WithLockRenewInterval 设置缓存重建锁续期间隔。
func WithLogKeyRedaction ¶
WithLogKeyRedaction 设置事件日志中 key/prefix/lock_name/err 等可能携带业务 key 的字段是否只输出摘要,默认开启。
func WithPrefixDeleteConcurrency ¶
WithPrefixDeleteConcurrency 设置 DeleteByPrefix 同时扫描删除的 pattern 数。 默认 1 表示保守串行;大 keyspace 且可接受更高 Redis 瞬时压力时可提高到 2~4 来缩短清理耗时。
func WithPrefixEpochTTL ¶
WithPrefixEpochTTL 设置前缀全量刷新代际元信息保留时间。
func WithPrefixKeyIndex ¶
WithPrefixKeyIndex 设置是否启用前缀 key 索引。 启用后 Manager 会在前缀目标写入时维护索引,并在 DeleteByPrefix 时优先按索引删除;降级 SCAN 仍要求 Store 实现 GuardedPatternStore。
func WithPrefixKeyIndexTTL ¶
WithPrefixKeyIndexTTL 设置前缀 key 索引与可信标记的保留时间。 TTL 过短会让删除更容易降级到 SCAN;TTL 过长会保留更多可能已过期的成员,建议按业务缓存最长 TTL 配置。
func WithRebuildContextPolicy ¶
func WithRebuildContextPolicy(policy RebuildContextPolicy) Option
WithRebuildContextPolicy 设置缓存重建上下文取消策略。
func WithRebuildResultTTL ¶
WithRebuildResultTTL 设置重建完成元信息保留时间。
func WithRefreshConcurrency ¶
WithRefreshConcurrency 设置 RefreshAll 和 RefreshByKeys 的有限并发度。
func WithScanCount ¶
WithScanCount 设置前缀缓存清理时的 Redis SCAN count。
func WithScanFallback ¶
WithScanFallback 设置 DeleteByPrefix 在前缀索引不可用时是否允许降级 SCAN。 默认关闭;仅在受控维护窗口显式开启,让线上调用优先建立可信索引或转后台任务。
type PipelineExecError ¶
type PipelineExecError struct {
Operation string // Operation 表示本次 Pipeline 执行的操作名称(用于日志与排障归类)
FailedKeys []string // FailedKeys 表示本次 Pipeline 中检测到失败的 key 列表(已排序去重)
Cause error // Cause 是底层错误原因
}
PipelineExecError 表示 Pipeline 执行失败的增强错误信息。 在部分命令失败(例如 cluster 路由抖动、网络短暂错误)时可携带失败 key 列表,便于线上快速定位与重试。
func (*PipelineExecError) Error ¶
func (e *PipelineExecError) Error() string
Error 返回稳定的 Pipeline 失败摘要,避免日志输出过长 key 列表。
func (*PipelineExecError) Unwrap ¶
func (e *PipelineExecError) Unwrap() error
Unwrap 返回底层错误,便于 errors.Is 和 errors.As 继续匹配。
type PrefixIndexMutation ¶
type PrefixIndexMutation struct {
IndexKey string // IndexKey 是前缀目标对应的索引集合 Redis key
TTL time.Duration // TTL 是安全超集索引加入成员时刷新的有效保留时间,由 Store 校验
Keys []string // Keys 是需要加入索引集合的真实 Redis key 成员列表
}
PrefixIndexMutation 描述一次前缀索引集合的成员变更。
type PrefixIndexStore ¶
type PrefixIndexStore interface {
// DeletePrefixIndexKeys 分批遍历安全超集索引并删除真实 Redis key,索引成员在线保留。
DeletePrefixIndexKeys(ctx context.Context, indexKey string, count int64, guards []LockGuard) (int64, error)
}
PrefixIndexStore 定义按前缀安全超集索引删除的能力,用于大 keyspace 下绕开全库 SCAN。 RedisStore 默认实现该接口;自定义 Store 未实现时,Manager 仅可通过 GuardedPatternStore 执行带锁 guard 的 SCAN 降级。
type PrefixMutationTopologyStore ¶ added in v1.22.2
type PrefixMutationTopologyStore interface {
// AllowsPrefixMutation 表示当前部署能否安全执行该前缀的全量写删与索引维护。
AllowsPrefixMutation(prefix string) bool
}
PrefixMutationTopologyStore 暴露无需网络探测的前缀原子提交拓扑能力。
type PrefixMutationValidator ¶ added in v1.22.2
type PrefixMutationValidator interface {
// ValidatePrefixMutation 拒绝无法与前缀锁原子提交的分布式跨槽前缀。
ValidatePrefixMutation(ctx context.Context, prefix string) error
}
PrefixMutationValidator 在回源前校验前缀全量写删能否安全执行。
type PrefixReplaceMutation ¶ added in v1.22.2
type PrefixReplaceMutation struct {
Guards []LockGuard // Guards 是每批真实写删必须原子校验的锁 owner
Prefix string // Prefix 是全量替换的业务前缀,用于校验分布式 Redis 的同槽约束
Entries []Entry // Entries 是本次快照需要写入的业务或元信息条目
KeepKeys []string // KeepKeys 是替换成功后必须保留的真实 Redis key,通常覆盖 Entries 及本轮保留元信息
DeletePatterns []string // DeletePatterns 是旧索引不可信时用于枚举旧 key 的已转义 Redis glob pattern
IndexKey string // IndexKey 是前缀目标的索引 manifest key
ReadyKey string // ReadyKey 是当前索引可信标记,只用于选择索引或 SCAN 枚举路径
IndexTTL time.Duration // IndexTTL 是索引可信窗口,分片成员会保留更长的安全窗口
ScanCount int64 // ScanCount 是索引或 keyspace 分页枚举的单批建议数量
}
PrefixReplaceMutation 描述一次前缀全量快照替换。
type PrefixReplaceStore ¶ added in v1.22.2
type PrefixReplaceStore interface {
// ReplacePrefix 写入当前快照并删除旧快照中的过期 key,返回实际删除数量。
ReplacePrefix(ctx context.Context, mutation PrefixReplaceMutation) (int64, error)
}
PrefixReplaceStore 定义前缀目标的安全全量替换能力。 实现必须先完整校验并写入新数据,再删除不在 KeepKeys 中的旧数据;失败时允许保留冗余数据,但不能先清空旧前缀。
type PrometheusMetrics ¶
type PrometheusMetrics struct {
// contains filtered or unexported fields
}
PrometheusMetrics 提供 Metrics、ExtendedMetrics、LookupMetrics 的 Prometheus 实现。
func NewPrometheusMetrics ¶
func NewPrometheusMetrics(opts ...PrometheusMetricsOption) (*PrometheusMetrics, error)
NewPrometheusMetrics 创建 Prometheus 指标适配器,默认兼容重复注册场景。
func (*PrometheusMetrics) RecordCacheHit ¶
func (m *PrometheusMetrics) RecordCacheHit(ctx context.Context, index string)
RecordCacheHit 记录基础缓存命中次数。
func (*PrometheusMetrics) RecordCacheMiss ¶
func (m *PrometheusMetrics) RecordCacheMiss(ctx context.Context, index string)
RecordCacheMiss 记录基础缓存未命中次数。
func (*PrometheusMetrics) RecordEmptyMarkerWrite ¶
func (m *PrometheusMetrics) RecordEmptyMarkerWrite(ctx context.Context, index string)
RecordEmptyMarkerWrite 记录空值占位写入次数。
func (*PrometheusMetrics) RecordLoaderError ¶
func (m *PrometheusMetrics) RecordLoaderError(ctx context.Context, index string, err error)
RecordLoaderError 记录 Loader 错误次数。
func (*PrometheusMetrics) RecordLockFailed ¶
func (m *PrometheusMetrics) RecordLockFailed(ctx context.Context, index string)
RecordLockFailed 记录锁竞争失败次数。
func (*PrometheusMetrics) RecordLookupRefreshTriggered ¶
func (m *PrometheusMetrics) RecordLookupRefreshTriggered(ctx context.Context, index string)
RecordLookupRefreshTriggered 记录读穿触发刷新次数。
func (*PrometheusMetrics) RecordLookupState ¶
func (m *PrometheusMetrics) RecordLookupState(ctx context.Context, index string, state LookupState)
RecordLookupState 记录一次逻辑读取的最终状态。
func (*PrometheusMetrics) RecordPrefixDelete ¶
func (m *PrometheusMetrics) RecordPrefixDelete(ctx context.Context, index string, prefix string, count int64)
RecordPrefixDelete 记录前缀删除次数和实际删除 key 总数。
func (*PrometheusMetrics) RecordPrefixRetry ¶
func (m *PrometheusMetrics) RecordPrefixRetry(ctx context.Context, index string)
RecordPrefixRetry 记录单 key 因前缀全量刷新重试的次数。
func (*PrometheusMetrics) RecordPrefixWait ¶
func (m *PrometheusMetrics) RecordPrefixWait(ctx context.Context, index string)
RecordPrefixWait 记录前缀全量刷新阻塞单 key 的次数。
func (*PrometheusMetrics) RecordRefresh ¶
func (m *PrometheusMetrics) RecordRefresh(ctx context.Context, index string, result string, duration time.Duration)
RecordRefresh 记录刷新次数和刷新耗时。
func (*PrometheusMetrics) RecordRefreshBatch ¶
func (m *PrometheusMetrics) RecordRefreshBatch(ctx context.Context, mode string, result string, total int, success int, failed int)
RecordRefreshBatch 记录批量刷新与全量刷新任务的次数、规模和成功失败条目数。
func (*PrometheusMetrics) RecordRefreshEntryCount ¶
func (m *PrometheusMetrics) RecordRefreshEntryCount(ctx context.Context, index string, count int)
RecordRefreshEntryCount 记录单次刷新写入条数。
func (*PrometheusMetrics) RecordScanFallback ¶
func (m *PrometheusMetrics) RecordScanFallback(ctx context.Context, index string, prefix string)
RecordScanFallback 记录实际执行的前缀删除降级 SCAN 次数。
func (*PrometheusMetrics) RecordWaitTimeout ¶
func (m *PrometheusMetrics) RecordWaitTimeout(ctx context.Context, index string)
RecordWaitTimeout 记录等待重建超时次数。
type PrometheusMetricsConfig ¶
type PrometheusMetricsConfig struct {
Namespace string // Namespace 是 Prometheus 指标命名空间
Subsystem string // Subsystem 是 Prometheus 指标子系统
Registerer prometheus.Registerer // Registerer 是指标注册器,nil 时默认使用全局注册器
RefreshBuckets []float64 // RefreshBuckets 是刷新耗时直方图桶
RefreshEntryBuckets []float64 // RefreshEntryBuckets 是单次刷新写入条数直方图桶
}
PrometheusMetricsConfig 表示 Prometheus 指标适配器的构造配置。
type PrometheusMetricsOption ¶
type PrometheusMetricsOption func(*PrometheusMetricsConfig)
PrometheusMetricsOption 表示 Prometheus 指标适配器的可选配置。
func WithPrometheusNamespace ¶
func WithPrometheusNamespace(namespace string) PrometheusMetricsOption
WithPrometheusNamespace 设置 Prometheus 指标命名空间。
func WithPrometheusRefreshBuckets ¶
func WithPrometheusRefreshBuckets(buckets []float64) PrometheusMetricsOption
WithPrometheusRefreshBuckets 设置刷新耗时直方图桶。
func WithPrometheusRefreshEntryBuckets ¶
func WithPrometheusRefreshEntryBuckets(buckets []float64) PrometheusMetricsOption
WithPrometheusRefreshEntryBuckets 设置单次刷新写入条数直方图桶。
func WithPrometheusRegisterer ¶
func WithPrometheusRegisterer(registerer prometheus.Registerer) PrometheusMetricsOption
WithPrometheusRegisterer 设置 Prometheus 指标注册器。
func WithPrometheusSubsystem ¶
func WithPrometheusSubsystem(subsystem string) PrometheusMetricsOption
WithPrometheusSubsystem 设置 Prometheus 指标子系统。
type ReadPageOptions ¶
type ReadPageOptions struct {
Fields []string // Fields 是 Hash 指定字段读取列表;非空时优先使用 HMGET
Start int64 // Start 是 List/ZSet 范围读取的起始下标
Stop int64 // Stop 是 List/ZSet 范围读取的结束下标;为 0 时按 Count 或 Store 默认页大小自动计算
Cursor uint64 // Cursor 是 Hash/Set 游标扫描的起始游标
Match string // Match 是 Hash/Set 游标扫描的匹配表达式
Count int64 // Count 是本页建议读取数量;小于等于 0 时使用 Store 默认 SCAN count
}
ReadPageOptions 表示集合类型分页读取配置。
type ReadPageResult ¶
type ReadPageResult struct {
Value any // Value 是当前页 Redis 原始值,类型与 Read 返回值保持一致
Cursor uint64 // Cursor 是 Hash/Set 下一页游标;0 表示遍历完成
}
ReadPageResult 表示集合类型分页读取结果。
type RebuildContextPolicy ¶
type RebuildContextPolicy int
RebuildContextPolicy 表示缓存重建上下文的取消信号策略。
const ( // RebuildContextInheritCancel 表示重建上下文继承调用方取消信号。 RebuildContextInheritCancel RebuildContextPolicy = iota // RebuildContextIgnoreCancel 表示重建上下文保留调用方上下文值,但忽略调用方取消信号。 RebuildContextIgnoreCancel )
func RebuildPolicy ¶
func RebuildPolicy(value RebuildContextPolicy) *RebuildContextPolicy
RebuildPolicy 返回重建上下文策略指针,便于 LoadThroughOptions 显式设置单次调用策略。
type RedisStore ¶
type RedisStore struct {
// contains filtered or unexported fields
}
RedisStore 是基于 go-redis 的 Store 适配器,可直接服务 go-zero、Gin、Kratos 等 Go 框架。
func NewRedisStore ¶
func NewRedisStore(client redis.UniversalClient, opts ...RedisStoreOption) *RedisStore
NewRedisStore 创建 go-redis 存储适配器。
func (*RedisStore) AcquireRefreshLock ¶ added in v1.22.2
func (s *RedisStore) AcquireRefreshLock(ctx context.Context, key string, value string, ttl time.Duration) (bool, string, error)
AcquireRefreshLock 原子获取刷新锁,失败时在同一脚本内返回当前owner。
func (*RedisStore) AllowsPrefixMutation ¶ added in v1.22.2
func (s *RedisStore) AllowsPrefixMutation(prefix string) bool
AllowsPrefixMutation 判断前缀在当前明确拓扑下是否具备原子 guard 条件。
func (*RedisStore) ApplyMutation ¶
func (s *RedisStore) ApplyMutation(ctx context.Context, mutation StoreMutation) error
ApplyMutation 按“索引先加、业务写删原子提交”的故障安全顺序提交变更。
func (*RedisStore) DeleteHashFields ¶ added in v1.22.2
func (s *RedisStore) DeleteHashFields(ctx context.Context, guards []LockGuard, key string, registryKey string, fields []string) error
DeleteHashFields 删除本次请求的旧 Hash 字段和字段空值 registry,保留同 key 的其它字段与 TTL。
func (*RedisStore) DeletePatternGuarded ¶ added in v1.22.2
func (s *RedisStore) DeletePatternGuarded(ctx context.Context, pattern string, count int64, guards []LockGuard) (int64, error)
DeletePatternGuarded 对每批 SCAN 结果原子校验 owner 后删除。
func (*RedisStore) DeletePrefixIndexKeys ¶
func (s *RedisStore) DeletePrefixIndexKeys(ctx context.Context, indexKey string, count int64, guards []LockGuard) (int64, error)
DeletePrefixIndexKeys 分页删除索引内的真实 key,并返回实际删除数量。
func (*RedisStore) ExistsMulti ¶
ExistsMulti 批量判断 Redis key 是否存在,返回 map 只包含传入的有效 key。
func (*RedisStore) HasFieldsEmpty ¶ added in v1.22.2
func (s *RedisStore) HasFieldsEmpty(ctx context.Context, registryKey string, fieldsID string) (bool, error)
HasFieldsEmpty 判断字段组合空值状态是否仍在独立有效期内。
func (*RedisStore) ReadPage ¶
func (s *RedisStore) ReadPage(ctx context.Context, key string, typ CacheType, options ReadPageOptions) (ReadPageResult, error)
ReadPage 按缓存类型分页读取 Redis 原始值,避免大集合必须一次性全量读取。
func (*RedisStore) RefreshLock ¶
func (s *RedisStore) RefreshLock(ctx context.Context, key string, value string, ttl time.Duration) (bool, error)
RefreshLock 仅当锁值与持有者标识一致时续期锁。
func (*RedisStore) ReleaseLock ¶
ReleaseLock 仅当锁值与持有者标识一致时释放锁,避免误删其它实例刚抢到的锁。
func (*RedisStore) ReplaceFieldsWithEmpty ¶ added in v1.22.2
func (s *RedisStore) ReplaceFieldsWithEmpty(ctx context.Context, guards []LockGuard, key string, registryKey string, fieldsID string, fields []string, ttl time.Duration) error
ReplaceFieldsWithEmpty 删除请求字段,并登记字段组合为空。
func (*RedisStore) ReplacePrefix ¶ added in v1.22.2
func (s *RedisStore) ReplacePrefix(ctx context.Context, mutation PrefixReplaceMutation) (int64, error)
ReplacePrefix 安全替换前缀快照;任一步失败时不会先删除旧快照。
func (*RedisStore) ReplaceWithMarker ¶ added in v1.22.2
func (s *RedisStore) ReplaceWithMarker(ctx context.Context, guards []LockGuard, marker Entry, deleteKeys ...string) error
ReplaceWithMarker 先写入 String marker,成功后再删除同槽旧缓存。
func (*RedisStore) ValidatePrefixMutation ¶ added in v1.22.2
func (s *RedisStore) ValidatePrefixMutation(ctx context.Context, prefix string) error
ValidatePrefixMutation 在 Store 拓扑校验后拒绝 Cluster 普通跨槽前缀。
func (*RedisStore) ValidateTablecacheStore ¶ added in v1.22.2
func (s *RedisStore) ValidateTablecacheStore() error
ValidateTablecacheStore 执行 Manager 构造期专用的 RedisStore 校验。
type RedisStoreOption ¶
type RedisStoreOption func(*RedisStore)
RedisStoreOption 表示 RedisStore 可选配置。
func WithDefaultJitterRatio ¶
func WithDefaultJitterRatio(ratio float64) RedisStoreOption
WithDefaultJitterRatio 设置未显式配置 Jitter 时的默认 TTL 抖动比例;0 表示关闭默认抖动。
func WithMaxCollectionReadCount ¶
func WithMaxCollectionReadCount(limit int64) RedisStoreOption
WithMaxCollectionReadCount 设置全量读取 Hash/List/Set/ZSet 前允许的最大成员数;默认5000,0表示显式不限制。
func WithMaxCollectionWriteCount ¶
func WithMaxCollectionWriteCount(limit int) RedisStoreOption
WithMaxCollectionWriteCount 设置单个 Entry 写入集合成员数上限;默认5000,0表示显式不限制。
func WithPipelineRetries ¶
func WithPipelineRetries(retries int) RedisStoreOption
WithPipelineRetries 设置批量删除与覆盖写的瞬时失败重试次数。
func WithRedisEncoder ¶
func WithRedisEncoder(encoder Encoder) RedisStoreOption
WithRedisEncoder 设置 Redis 复杂值序列化函数。
func WithUnlinkChunkSize ¶
func WithUnlinkChunkSize(size int) RedisStoreOption
WithUnlinkChunkSize 设置批量删除时单个 Pipeline 的 UNLINK 命令数量。 较大的 chunk 可减少网络往返,较小的 chunk 可降低单次请求体积和 Redis 侧瞬时压力。
type RefreshBatchAdminItem ¶
type RefreshBatchAdminItem struct {
Key string `json:"key"` // Key 是当前批量项的缓存 key
Success bool `json:"success"` // Success 表示当前批量项是否刷新成功
Code string `json:"code"` // Code 是稳定且不包含内部细节的结果码
Message string `json:"message"` // Message 是可安全展示的结果文案
Error error `json:"-"` // Error 保留原始错误,供调用方在受控日志中使用
}
RefreshBatchAdminItem 表示管理页可直接返回的单条批量刷新结果。
type RefreshBatchAdminResponse ¶
type RefreshBatchAdminResponse struct {
Success bool `json:"success"` // Success 表示整批是否全部成功
Code string `json:"code"` // Code 是稳定且不包含内部细节的结果码
Message string `json:"message"` // Message 是面向管理页展示的安全文案
Error error `json:"-"` // Error 保留整批聚合错误,供调用方在受控日志中使用
Summary RefreshBatchSummary `json:"summary"` // Summary 是当前批量结果的汇总统计
Items []RefreshBatchAdminItem `json:"items"` // Items 是当前批量每一项的明细结果
}
RefreshBatchAdminResponse 表示管理页批量刷新接口可直接返回的标准 JSON 结构。
func BuildRefreshBatchAdminResponse ¶
func BuildRefreshBatchAdminResponse(results []RefreshBatchResult) RefreshBatchAdminResponse
BuildRefreshBatchAdminResponse 根据批量刷新结果构建管理页标准响应结构。
func BuildRefreshBatchAdminResponseWithSummary ¶
func BuildRefreshBatchAdminResponseWithSummary(results []RefreshBatchResult, summary RefreshBatchSummary, err error) RefreshBatchAdminResponse
BuildRefreshBatchAdminResponseWithSummary 根据批量刷新结果、汇总信息和聚合错误构建管理页标准响应结构。
type RefreshBatchError ¶
type RefreshBatchError struct {
Summary RefreshBatchSummary // Summary 是当前批量刷新结果的汇总信息
}
RefreshBatchError 表示批量刷新存在失败项的聚合错误。
type RefreshBatchMetrics ¶
type RefreshBatchMetrics interface {
Metrics
// RecordRefreshBatch 记录批量刷新/全量刷新任务的汇总信息。
RecordRefreshBatch(ctx context.Context, mode string, result string, total int, success int, failed int)
}
RefreshBatchMetrics 定义批量刷新与全量刷新任务的汇总指标接口。
type RefreshBatchResult ¶
type RefreshBatchResult struct {
Key string `json:"key"` // Key 是当前批量项的缓存 key
Error error `json:"-"` // Error 是当前批量项的执行错误
}
RefreshBatchResult 表示单条批量刷新请求的执行结果。
type RefreshBatchSummary ¶
type RefreshBatchSummary struct {
Total int `json:"total"` // Total 是批量请求总数
Success int `json:"success"` // Success 是执行成功的条数
Failed int `json:"failed"` // Failed 是执行失败的条数
FailedKeys []string `json:"failedKeys"` // FailedKeys 是执行失败的 key 列表
}
RefreshBatchSummary 表示一批刷新请求的汇总结果。
func SummarizeRefreshBatchResults ¶
func SummarizeRefreshBatchResults(results []RefreshBatchResult) RefreshBatchSummary
SummarizeRefreshBatchResults 汇总批量刷新结果,便于管理页和预热任务统一判断。
func (RefreshBatchSummary) HasError ¶
func (s RefreshBatchSummary) HasError() bool
HasError 返回当前批量刷新汇总是否包含失败项。
type ScanFallbackMetrics ¶
type ScanFallbackMetrics interface {
Metrics
// RecordScanFallback 记录一次 DeleteByPrefix 索引未命中后的 SCAN 降级。
RecordScanFallback(ctx context.Context, index string, prefix string)
}
ScanFallbackMetrics 定义前缀删除降级全库扫描的可选指标。
type Store ¶
type Store interface {
// AcquireRefreshLock 原子获取刷新锁;竞争失败时同时返回当前 owner。
AcquireRefreshLock(ctx context.Context, key string, value string, ttl time.Duration) (locked bool, owner string, err error)
// ApplyMutation 按故障安全顺序提交一次缓存变更。
ApplyMutation(ctx context.Context, mutation StoreMutation) error
// Exists 判断指定 key 是否存在。
Exists(ctx context.Context, key string) (bool, error)
// ExistsMulti 批量判断 key 是否存在,返回 map[key]exists。
ExistsMulti(ctx context.Context, keys ...string) (map[string]bool, error)
// Read 按缓存类型读取 Redis 原始值。
Read(ctx context.Context, key string, typ CacheType) (any, error)
// RefreshLock 仅当锁值与持有者标识一致时续期锁。
RefreshLock(ctx context.Context, key string, value string, ttl time.Duration) (bool, error)
// ReleaseLock 仅当锁值与持有者标识一致时释放锁,避免误删其它实例刚抢到的锁。
ReleaseLock(ctx context.Context, key string, value string) (bool, error)
}
Store 定义 Manager 依赖的读取、批量变更和分布式锁契约。
type StoreMutation ¶
type StoreMutation struct {
Guards []LockGuard // Guards 是业务写删同一原子边界内必须校验的锁 owner
DeleteKeys []string // DeleteKeys 是需要删除的真实 Redis key 列表,来源于旧业务 key、空值元信息或重建结果元信息
WriteEntries []Entry // WriteEntries 是需要写入的缓存条目,来源于 Loader 结果或内部元信息
AddIndex []PrefixIndexMutation // AddIndex 表示需要把哪些 key 加入前缀索引集合,通常来源于写入成功的业务 key 或元信息 key
}
StoreMutation 描述一次缓存刷新或清理需要提交到底层 Store 的变更集合。
type StoreValidator ¶ added in v1.22.2
type StoreValidator interface {
// ValidateTablecacheStore 校验 Store 配置能否安全服务 table-cache。
ValidateTablecacheStore() error
}
StoreValidator 定义 table-cache 构造期专用校验能力,避免碰撞自定义 Store 的通用 Validate 方法。
type Target ¶
type Target struct {
Index string // Index 是缓存目标索引,通常等于 Redis key 第一个冒号前的前缀
Title string // Title 是缓存目标中文名称
Key string // Key 是不含 Manager keyPrefix 的逻辑 key 或前缀,前缀型目标以冒号结尾
KeyTitle string // KeyTitle 是不含 Manager keyPrefix 的展示模板
Type CacheType // Type 是 Redis 数据结构类型
Remark string // Remark 是缓存用途说明
TTL time.Duration // TTL 是业务缓存基础过期时间,0 表示不过期
Jitter time.Duration // Jitter 是 TTL 最大抖动范围,用于降低缓存雪崩风险
EmptyTTL time.Duration // EmptyTTL 是空值占位缓存过期时间,用于缓存穿透保护
LoaderTimeout time.Duration // LoaderTimeout 是当前目标回源加载超时时间,0 表示使用管理器默认值
RefreshAll bool // RefreshAll 表示刷新全部缓存时是否包含该目标
AllowEmptyMarker bool // AllowEmptyMarker 表示加载空数据时是否写入空值占位
Loader Loader // Loader 是缓存回源加载器
}
Target 描述一个可刷新、可展示、可复用的表数据缓存目标。