cache

package
v0.0.0-...-812ebae Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 7, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateKey

func GenerateKey(queryType string, parameters map[string]interface{}, timeRange string) string

GenerateKey 生成缓存键 基于查询类型、参数和时间范围生成MD5哈希

Types

type Alert

type Alert struct {
	Level     string                 `json:"level"` // info, warning, error, critical
	Message   string                 `json:"message"`
	Timestamp time.Time              `json:"timestamp"`
	Metadata  map[string]interface{} `json:"metadata"`
}

Alert 告警信息

type AlertCallback

type AlertCallback func(alert *Alert)

AlertCallback 告警回调函数类型

type AlertThresholds

type AlertThresholds struct {
	LowHitRatePercent      float64       `json:"low_hit_rate_percent"`
	HighMemoryUsagePercent float64       `json:"high_memory_usage_percent"`
	MaxResponseTimeMs      float64       `json:"max_response_time_ms"`
	MaxErrorCount          int64         `json:"max_error_count"`
	MaxSlowOperations      int64         `json:"max_slow_operations"`
	HealthCheckTimeout     time.Duration `json:"health_check_timeout"`
}

AlertThresholds 告警阈值配置

type CacheConfig

type CacheConfig struct {
	MaxSize           int64              `json:"max_size"`           // 最大缓存大小(字节)
	TTL               time.Duration      `json:"ttl"`                // 缓存生存时间
	CleanupInterval   time.Duration      `json:"cleanup_interval"`   // 清理间隔
	CoalescingConfig  *CoalescingConfig  `json:"coalescing_config"`  // 查询合并配置
	ConcurrencyConfig *ConcurrencyConfig `json:"concurrency_config"` // 并发控制配置
}

CacheConfig 缓存配置

func DefaultCacheConfig

func DefaultCacheConfig() *CacheConfig

DefaultCacheConfig 默认缓存配置

type CacheManager

type CacheManager struct {
	// contains filtered or unexported fields
}

CacheManager 缓存管理器

func NewCacheManager

func NewCacheManager(config *CacheConfig) *CacheManager

NewCacheManager 创建新的缓存管理器

func (*CacheManager) ActiveCoalescingGroupsCount

func (cm *CacheManager) ActiveCoalescingGroupsCount() int

ActiveCoalescingGroupsCount 返回活跃合并组数量

func (*CacheManager) Clear

func (cm *CacheManager) Clear()

Clear 清空缓存

func (*CacheManager) Close

func (cm *CacheManager) Close() error

Close 关闭缓存管理器

func (*CacheManager) Delete

func (cm *CacheManager) Delete(key string) bool

Delete 删除缓存数据

func (*CacheManager) ForceCleanup

func (cm *CacheManager) ForceCleanup()

ForceCleanup 强制执行清理

func (*CacheManager) Get

func (cm *CacheManager) Get(key string) (interface{}, bool)

Get 获取缓存数据

func (*CacheManager) GetCoalescingStats

func (cm *CacheManager) GetCoalescingStats() map[string]interface{}

GetCoalescingStats 获取查询合并统计

func (*CacheManager) GetConcurrencyStats

func (cm *CacheManager) GetConcurrencyStats() map[string]interface{}

GetConcurrencyStats 获取并发控制统计

func (*CacheManager) GetKeys

func (cm *CacheManager) GetKeys() []string

GetKeys 返回所有缓存键

func (*CacheManager) GetOrSet

func (cm *CacheManager) GetOrSet(ctx context.Context, key string, fn func(ctx context.Context) (interface{}, error)) (interface{}, error)

GetOrSet 获取缓存,如果不存在则执行函数并缓存结果

func (*CacheManager) GetOrSetWithConcurrency

func (cm *CacheManager) GetOrSetWithConcurrency(ctx context.Context, key string, fn func(ctx context.Context) (interface{}, error)) (interface{}, error)

GetOrSetWithConcurrency 在并发控制下获取或设置缓存

func (*CacheManager) GetStats

func (cm *CacheManager) GetStats() map[string]interface{}

GetStats 获取缓存统计信息

func (*CacheManager) HasActiveCoalescingGroup

func (cm *CacheManager) HasActiveCoalescingGroup(key string) bool

HasActiveCoalescingGroup 检查是否有活跃的合并组

func (*CacheManager) MaxSize

func (cm *CacheManager) MaxSize() int64

MaxSize 返回最大缓存大小

func (*CacheManager) Set

func (cm *CacheManager) Set(key string, data interface{}) error

Set 设置缓存数据

func (*CacheManager) SetCleanupInterval

func (cm *CacheManager) SetCleanupInterval(interval time.Duration)

SetCleanupInterval 设置清理间隔

func (*CacheManager) SetWithTTL

func (cm *CacheManager) SetWithTTL(key string, data interface{}, ttl time.Duration) error

SetWithTTL 设置具有自定义TTL的缓存数据

func (*CacheManager) Size

func (cm *CacheManager) Size() int

Size 返回缓存项数量

func (*CacheManager) SubmitToWorkerPool

func (cm *CacheManager) SubmitToWorkerPool(task func()) error

SubmitToWorkerPool 提交任务到工作池

func (*CacheManager) TotalSize

func (cm *CacheManager) TotalSize() int64

TotalSize 返回缓存总大小

func (*CacheManager) Warmup

func (cm *CacheManager) Warmup(ctx context.Context, data map[string]interface{}) error

Warmup 缓存预热

type CacheMetrics

type CacheMetrics struct {
	Hits      int64     `json:"hits"`
	Misses    int64     `json:"misses"`
	Sets      int64     `json:"sets"`
	Deletes   int64     `json:"deletes"`
	Evictions int64     `json:"evictions"`
	StartTime time.Time `json:"start_time"`
	LastReset time.Time `json:"last_reset"`
	// contains filtered or unexported fields
}

CacheMetrics 缓存性能指标

func (*CacheMetrics) GetStats

func (m *CacheMetrics) GetStats() map[string]interface{}

GetStats 获取指标统计

func (*CacheMetrics) HitRate

func (m *CacheMetrics) HitRate() float64

HitRate 计算命中率

func (*CacheMetrics) Reset

func (m *CacheMetrics) Reset()

Reset 重置指标

type CacheMonitor

type CacheMonitor struct {
	// contains filtered or unexported fields
}

CacheMonitor 缓存监控器

func NewCacheMonitor

func NewCacheMonitor(cm *CacheManager, metrics *DetailedCacheMetrics, config *MonitoringConfig) *CacheMonitor

NewCacheMonitor 创建缓存监控器

func (*CacheMonitor) AddAlertCallback

func (m *CacheMonitor) AddAlertCallback(callback AlertCallback)

AddAlertCallback 添加告警回调

func (*CacheMonitor) GetConfiguration

func (m *CacheMonitor) GetConfiguration() *MonitoringConfig

GetConfiguration 获取当前配置

func (*CacheMonitor) GetDebugInfo

func (m *CacheMonitor) GetDebugInfo() map[string]interface{}

GetDebugInfo 获取调试信息

func (*CacheMonitor) GetMonitoringStats

func (m *CacheMonitor) GetMonitoringStats() map[string]interface{}

GetMonitoringStats 获取监控器自身的统计

func (*CacheMonitor) SimulateLoad

func (m *CacheMonitor) SimulateLoad(ctx context.Context, duration time.Duration, opsPerSecond int)

SimulateLoad 模拟负载(用于测试)

func (*CacheMonitor) Start

func (m *CacheMonitor) Start(ctx context.Context) error

Start 启动监控

func (*CacheMonitor) Stop

func (m *CacheMonitor) Stop() error

Stop 停止监控

func (*CacheMonitor) UpdateConfiguration

func (m *CacheMonitor) UpdateConfiguration(config *MonitoringConfig) error

UpdateConfiguration 更新配置

type CacheStorage

type CacheStorage struct {
	// contains filtered or unexported fields
}

CacheStorage 提供线程安全的内存缓存存储

func NewCacheStorage

func NewCacheStorage(maxSize int64) *CacheStorage

NewCacheStorage 创建新的缓存存储实例

func (*CacheStorage) Clear

func (s *CacheStorage) Clear()

Clear 清空所有缓存

func (*CacheStorage) Delete

func (s *CacheStorage) Delete(key string) bool

Delete 删除缓存项

func (*CacheStorage) Get

func (s *CacheStorage) Get(key string) (*CachedResult, bool)

Get 获取缓存项

func (*CacheStorage) GetKeys

func (s *CacheStorage) GetKeys() []string

GetKeys 返回所有缓存键(用于调试和监控)

func (*CacheStorage) GetStats

func (s *CacheStorage) GetStats() map[string]interface{}

GetStats 获取缓存统计信息

func (*CacheStorage) MaxSize

func (s *CacheStorage) MaxSize() int64

MaxSize 返回最大缓存大小

func (*CacheStorage) Set

func (s *CacheStorage) Set(key string, data interface{}, ttl time.Duration) error

Set 设置缓存项

func (*CacheStorage) Size

func (s *CacheStorage) Size() int

Size 返回缓存项数量

func (*CacheStorage) TotalSize

func (s *CacheStorage) TotalSize() int64

TotalSize 返回缓存总大小

type CachedResult

type CachedResult struct {
	Data        interface{} `json:"data"`
	Timestamp   time.Time   `json:"timestamp"`
	Expiry      time.Time   `json:"expiry"`
	AccessCount int64       `json:"access_count"`
	Size        int64       `json:"size"`
}

CachedResult 表示缓存的结果数据

func (*CachedResult) EstimateSize

func (r *CachedResult) EstimateSize() int64

EstimateSize 估算缓存项的内存大小

func (*CachedResult) IsExpired

func (r *CachedResult) IsExpired() bool

IsExpired 检查缓存项是否已过期

func (*CachedResult) Touch

func (r *CachedResult) Touch()

Touch 更新访问计数和时间戳

type CleanupConfig

type CleanupConfig struct {
	Strategy          CleanupStrategy                 `json:"strategy"`
	CleanupInterval   time.Duration                   `json:"cleanup_interval"`
	Threshold         map[string]interface{}          `json:"threshold"`
	MaxCleanupPercent float64                         `json:"max_cleanup_percent"`
	CleanupCallback   func([]string, CleanupStrategy) `json:"-"`
}

CleanupConfig 清理管理器配置

func DefaultCleanupConfig

func DefaultCleanupConfig() *CleanupConfig

DefaultCleanupConfig 返回默认清理配置

type CleanupItem

type CleanupItem struct {
	Key          string    `json:"key"`
	Size         int64     `json:"size"`
	AccessCount  int64     `json:"access_count"`
	LastAccessed time.Time `json:"last_accessed"`
	CreatedAt    time.Time `json:"created_at"`
	Expiry       time.Time `json:"expiry"`
	Priority     int       `json:"priority"` // 清理优先级,越高越优先清理
}

CleanupItem 清理项信息

func (*CleanupItem) CalculatePriority

func (item *CleanupItem) CalculatePriority() int

CalculatePriority 计算清理优先级

func (*CleanupItem) ShouldClean

func (item *CleanupItem) ShouldClean(strategy CleanupStrategy, threshold map[string]interface{}) bool

ShouldClean 判断是否应该清理这个项目

type CleanupManager

type CleanupManager struct {
	// contains filtered or unexported fields
}

CleanupManager 清理管理器

func NewCleanupManager

func NewCleanupManager(storage *CacheStorage, ttlManager *TTLManager, config *CleanupConfig) *CleanupManager

NewCleanupManager 创建新的清理管理器

func (*CleanupManager) Close

func (cm *CleanupManager) Close() error

Close 关闭清理管理器

func (*CleanupManager) ForceCleanup

func (cm *CleanupManager) ForceCleanup() ([]string, error)

ForceCleanup 强制执行清理

func (*CleanupManager) GetCleanupInterval

func (cm *CleanupManager) GetCleanupInterval() time.Duration

GetCleanupInterval 获取清理间隔

func (*CleanupManager) GetMaxCleanupPercent

func (cm *CleanupManager) GetMaxCleanupPercent() float64

GetMaxCleanupPercent 获取最大清理百分比

func (*CleanupManager) GetStats

func (cm *CleanupManager) GetStats() map[string]interface{}

GetStats 获取清理统计信息

func (*CleanupManager) GetStrategy

func (cm *CleanupManager) GetStrategy() CleanupStrategy

GetStrategy 获取当前清理策略

func (*CleanupManager) GetThreshold

func (cm *CleanupManager) GetThreshold() map[string]interface{}

GetThreshold 获取清理阈值

func (*CleanupManager) IsRunning

func (cm *CleanupManager) IsRunning() bool

IsRunning 检查清理管理器是否正在运行

func (*CleanupManager) PredictNextCleanup

func (cm *CleanupManager) PredictNextCleanup() map[string]interface{}

PredictNextCleanup 预测下次清理的项目数量

func (*CleanupManager) SetCleanupInterval

func (cm *CleanupManager) SetCleanupInterval(interval time.Duration)

SetCleanupInterval 设置清理间隔

func (*CleanupManager) SetMaxCleanupPercent

func (cm *CleanupManager) SetMaxCleanupPercent(percent float64)

SetMaxCleanupPercent 设置最大清理百分比

func (*CleanupManager) SetStrategy

func (cm *CleanupManager) SetStrategy(strategy CleanupStrategy)

SetStrategy 设置清理策略

func (*CleanupManager) SetThreshold

func (cm *CleanupManager) SetThreshold(threshold map[string]interface{})

SetThreshold 设置清理阈值

type CleanupStats

type CleanupStats struct {
	TotalCleanups       int64                     `json:"total_cleanups"`
	TotalItemsCleaned   int64                     `json:"total_items_cleaned"`
	TotalSpaceFreed     int64                     `json:"total_space_freed"`
	LastCleanupTime     time.Time                 `json:"last_cleanup_time"`
	LastCleanupDuration time.Duration             `json:"last_cleanup_duration"`
	AverageCleanupTime  time.Duration             `json:"average_cleanup_time"`
	StrategyUsage       map[CleanupStrategy]int64 `json:"strategy_usage"`
	// contains filtered or unexported fields
}

CleanupStats 清理统计信息

func NewCleanupStats

func NewCleanupStats() *CleanupStats

NewCleanupStats 创建新的清理统计

func (*CleanupStats) GetStats

func (s *CleanupStats) GetStats() map[string]interface{}

GetStats 获取统计信息

func (*CleanupStats) RecordCleanup

func (s *CleanupStats) RecordCleanup(strategy CleanupStrategy, itemsCleaned int64, spaceFreed int64, duration time.Duration)

RecordCleanup 记录清理操作

type CleanupStrategy

type CleanupStrategy int

CleanupStrategy 清理策略

const (
	// StrategyTTLOnly 只清理过期项
	StrategyTTLOnly CleanupStrategy = iota
	// StrategyLRU LRU清理策略
	StrategyLRU
	// StrategySize 基于大小的清理策略
	StrategySize
	// StrategyMixed 混合策略(TTL + LRU + Size)
	StrategyMixed
)

type CoalescingConfig

type CoalescingConfig struct {
	Timeout      time.Duration `json:"timeout"`       // 合并组超时时间
	CleanupDelay time.Duration `json:"cleanup_delay"` // 清理延迟时间
}

CoalescingConfig 查询合并配置

func DefaultCoalescingConfig

func DefaultCoalescingConfig() *CoalescingConfig

DefaultCoalescingConfig 默认查询合并配置

type CoalescingGroup

type CoalescingGroup struct {
	// contains filtered or unexported fields
}

CoalescingGroup 查询合并组

func NewCoalescingGroup

func NewCoalescingGroup(timeout time.Duration) *CoalescingGroup

NewCoalescingGroup 创建新的查询合并组

func (*CoalescingGroup) IsExpired

func (g *CoalescingGroup) IsExpired() bool

IsExpired 检查合并组是否已过期

type CoalescingResult

type CoalescingResult struct {
	// contains filtered or unexported fields
}

CoalescingResult 查询合并结果

type CoalescingStats

type CoalescingStats struct {
	TotalRequests  int64 `json:"total_requests"`  // 总请求数
	MergedRequests int64 `json:"merged_requests"` // 合并的请求数
	ActiveGroups   int64 `json:"active_groups"`   // 当前活跃的合并组数
	SavedQueries   int64 `json:"saved_queries"`   // 节省的查询次数
	// contains filtered or unexported fields
}

CoalescingStats 查询合并统计

func (*CoalescingStats) GetSavingsRate

func (s *CoalescingStats) GetSavingsRate() float64

GetSavingsRate 获取节省率

func (*CoalescingStats) GetStats

func (s *CoalescingStats) GetStats() map[string]interface{}

GetStats 获取统计信息

func (*CoalescingStats) Reset

func (s *CoalescingStats) Reset()

Reset 重置统计

type ConcurrencyConfig

type ConcurrencyConfig struct {
	MaxConcurrency int           `json:"max_concurrency"`  // 最大并发数
	WorkerPoolSize int           `json:"worker_pool_size"` // 工作池大小
	QueueSize      int           `json:"queue_size"`       // 队列大小
	RateLimit      time.Duration `json:"rate_limit"`       // 速率限制间隔
	BurstLimit     int           `json:"burst_limit"`      // 突发限制
}

ConcurrencyConfig 并发管理配置

func DefaultConcurrencyConfig

func DefaultConcurrencyConfig() *ConcurrencyConfig

DefaultConcurrencyConfig 默认并发配置

type ConcurrencyLimiter

type ConcurrencyLimiter interface {
	// Acquire 获取并发槽位
	Acquire(ctx context.Context) error
	// Release 释放并发槽位
	Release()
	// TryAcquire 尝试获取槽位,不阻塞
	TryAcquire() bool
	// Available 返回可用槽位数
	Available() int
	// InUse 返回正在使用的槽位数
	InUse() int
	// Close 关闭限制器
	Close() error
}

ConcurrencyLimiter 并发限制器接口

type ConcurrencyManager

type ConcurrencyManager struct {
	// contains filtered or unexported fields
}

ConcurrencyManager 并发管理器

func NewConcurrencyManager

func NewConcurrencyManager(config *ConcurrencyConfig) *ConcurrencyManager

NewConcurrencyManager 创建并发管理器

func (*ConcurrencyManager) Close

func (cm *ConcurrencyManager) Close() error

Close 关闭并发管理器

func (*ConcurrencyManager) ExecuteWithLimits

func (cm *ConcurrencyManager) ExecuteWithLimits(ctx context.Context, task func() error) error

ExecuteWithLimits 在并发限制下执行任务

func (*ConcurrencyManager) GetStats

func (cm *ConcurrencyManager) GetStats() map[string]interface{}

GetStats 获取并发管理统计信息

func (*ConcurrencyManager) SubmitToWorkerPool

func (cm *ConcurrencyManager) SubmitToWorkerPool(task func()) error

SubmitToWorkerPool 提交任务到工作池

type ConcurrencyStats

type ConcurrencyStats struct {
	ConcurrentRequests int64 `json:"concurrent_requests"` // 当前并发请求数
	TotalRequests      int64 `json:"total_requests"`      // 总请求数
	RejectedRequests   int64 `json:"rejected_requests"`   // 被拒绝的请求数
	AverageWaitTime    int64 `json:"average_wait_time"`   // 平均等待时间(毫秒)
	// contains filtered or unexported fields
}

ConcurrencyStats 并发管理统计

type DetailedCacheMetrics

type DetailedCacheMetrics struct {
	*CacheMetrics // 嵌入基础指标

	// 详细的性能统计
	GetResponseTime    *ResponseTimeStats
	SetResponseTime    *ResponseTimeStats
	DeleteResponseTime *ResponseTimeStats
	MemoryUsage        *MemoryUsageStats

	KeyAccessFrequency map[string]int64 `json:"key_access_frequency"`
	HourlyStats        map[int]int64    `json:"hourly_stats"`      // 按小时统计命中数
	TypeStats          map[string]int64 `json:"type_stats"`        // 按数据类型统计
	SizeDistribution   map[string]int64 `json:"size_distribution"` // 大小分布统计
	ErrorCount         int64            `json:"error_count"`
	LastErrorTime      time.Time        `json:"last_error_time"`
	LastError          string           `json:"last_error"`

	// 性能阈值监控
	SlowOperationThreshold time.Duration
	SlowOperationCount     int64
	LargeItemThreshold     int64
	LargeItemCount         int64
	// contains filtered or unexported fields
}

DetailedCacheMetrics 扩展的缓存指标

func NewDetailedCacheMetrics

func NewDetailedCacheMetrics(maxSize int64) *DetailedCacheMetrics

NewDetailedCacheMetrics 创建详细的缓存指标实例

func (*DetailedCacheMetrics) GetDetailedStats

func (m *DetailedCacheMetrics) GetDetailedStats() map[string]interface{}

GetDetailedStats 获取详细统计信息

func (*DetailedCacheMetrics) GetHealthStatus

func (m *DetailedCacheMetrics) GetHealthStatus() map[string]interface{}

GetHealthStatus 获取缓存健康状态

func (*DetailedCacheMetrics) RecordDelete

func (m *DetailedCacheMetrics) RecordDelete(key string, duration time.Duration, size int64)

RecordDelete 记录Delete操作

func (*DetailedCacheMetrics) RecordError

func (m *DetailedCacheMetrics) RecordError(err error)

RecordError 记录错误

func (*DetailedCacheMetrics) RecordEviction

func (m *DetailedCacheMetrics) RecordEviction(count int, totalSize int64)

RecordEviction 记录淘汰操作

func (*DetailedCacheMetrics) RecordGet

func (m *DetailedCacheMetrics) RecordGet(key string, hit bool, duration time.Duration, size int64)

RecordGet 记录Get操作

func (*DetailedCacheMetrics) RecordSet

func (m *DetailedCacheMetrics) RecordSet(key string, duration time.Duration, size int64, dataType string)

RecordSet 记录Set操作

func (*DetailedCacheMetrics) Reset

func (m *DetailedCacheMetrics) Reset()

Reset 重置所有指标

func (*DetailedCacheMetrics) SetThresholds

func (m *DetailedCacheMetrics) SetThresholds(slowOpThreshold time.Duration, largeItemThreshold int64)

SetThresholds 设置性能阈值

func (*DetailedCacheMetrics) StartPeriodicReporting

func (m *DetailedCacheMetrics) StartPeriodicReporting(ctx context.Context, interval time.Duration, callback func(stats map[string]interface{}))

StartPeriodicReporting 启动定期报告

type MemoryUsageStats

type MemoryUsageStats struct {
	// contains filtered or unexported fields
}

MemoryUsageStats 内存使用统计

func NewMemoryUsageStats

func NewMemoryUsageStats(maxSize int64, maxHistory int) *MemoryUsageStats

NewMemoryUsageStats 创建内存使用统计实例

func (*MemoryUsageStats) GetStats

func (s *MemoryUsageStats) GetStats() map[string]interface{}

GetStats 获取内存使用统计

func (*MemoryUsageStats) RecordAllocation

func (s *MemoryUsageStats) RecordAllocation(size int64)

RecordAllocation 记录内存分配

func (*MemoryUsageStats) RecordDeallocation

func (s *MemoryUsageStats) RecordDeallocation(size int64)

RecordDeallocation 记录内存释放

type MonitoringConfig

type MonitoringConfig struct {
	EnableHTTPEndpoints bool             `json:"enable_http_endpoints"`
	HTTPPort            int              `json:"http_port"`
	LoggingEnabled      bool             `json:"logging_enabled"`
	LogLevel            string           `json:"log_level"` // debug, info, warn, error
	MetricsInterval     time.Duration    `json:"metrics_interval"`
	HealthCheckInterval time.Duration    `json:"health_check_interval"`
	AlertThresholds     *AlertThresholds `json:"alert_thresholds"`
}

MonitoringConfig 监控配置

func DefaultMonitoringConfig

func DefaultMonitoringConfig() *MonitoringConfig

DefaultMonitoringConfig 默认监控配置

type QueryCoalescer

type QueryCoalescer struct {
	// contains filtered or unexported fields
}

QueryCoalescer 查询合并器

func NewQueryCoalescer

func NewQueryCoalescer(config *CoalescingConfig) *QueryCoalescer

NewQueryCoalescer 创建新的查询合并器

func (*QueryCoalescer) ActiveGroupsCount

func (qc *QueryCoalescer) ActiveGroupsCount() int

ActiveGroupsCount 返回当前活跃的合并组数量

func (*QueryCoalescer) Close

func (qc *QueryCoalescer) Close() error

Close 关闭查询合并器

func (*QueryCoalescer) Execute

func (qc *QueryCoalescer) Execute(ctx context.Context, key string, fn func(ctx context.Context) (interface{}, error)) (interface{}, error)

Execute 执行查询合并逻辑

func (*QueryCoalescer) GetStats

func (qc *QueryCoalescer) GetStats() map[string]interface{}

GetStats 获取查询合并统计信息

func (*QueryCoalescer) HasActiveGroup

func (qc *QueryCoalescer) HasActiveGroup(key string) bool

HasActiveGroup 检查是否有特定key的活跃合并组

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter 速率限制器

func NewRateLimiter

func NewRateLimiter(rate time.Duration, burst int) *RateLimiter

NewRateLimiter 创建速率限制器

func (*RateLimiter) Available

func (rl *RateLimiter) Available() int

Available 返回可用令牌数

func (*RateLimiter) Close

func (rl *RateLimiter) Close() error

Close 关闭速率限制器

func (*RateLimiter) TryWait

func (rl *RateLimiter) TryWait() bool

TryWait 尝试获取令牌,不阻塞

func (*RateLimiter) Wait

func (rl *RateLimiter) Wait(ctx context.Context) error

Wait 等待获取令牌

type ResponseTimeStats

type ResponseTimeStats struct {
	// contains filtered or unexported fields
}

ResponseTimeStats 响应时间统计

func NewResponseTimeStats

func NewResponseTimeStats(maxSamples int) *ResponseTimeStats

NewResponseTimeStats 创建响应时间统计实例

func (*ResponseTimeStats) Clear

func (s *ResponseTimeStats) Clear()

Clear 清除所有统计数据

func (*ResponseTimeStats) GetStats

func (s *ResponseTimeStats) GetStats() map[string]interface{}

GetStats 获取响应时间统计信息

func (*ResponseTimeStats) Record

func (s *ResponseTimeStats) Record(duration time.Duration)

Record 记录一次响应时间

type SemaphoreLimiter

type SemaphoreLimiter struct {
	// contains filtered or unexported fields
}

SemaphoreLimiter 信号量并发限制器

func NewSemaphoreLimiter

func NewSemaphoreLimiter(capacity int) *SemaphoreLimiter

NewSemaphoreLimiter 创建信号量并发限制器

func (*SemaphoreLimiter) Acquire

func (s *SemaphoreLimiter) Acquire(ctx context.Context) error

Acquire 获取并发槽位

func (*SemaphoreLimiter) Available

func (s *SemaphoreLimiter) Available() int

Available 返回可用槽位数

func (*SemaphoreLimiter) Close

func (s *SemaphoreLimiter) Close() error

Close 关闭限制器

func (*SemaphoreLimiter) InUse

func (s *SemaphoreLimiter) InUse() int

InUse 返回正在使用的槽位数

func (*SemaphoreLimiter) Release

func (s *SemaphoreLimiter) Release()

Release 释放并发槽位

func (*SemaphoreLimiter) TryAcquire

func (s *SemaphoreLimiter) TryAcquire() bool

TryAcquire 尝试获取槽位,不阻塞

type TTLConfig

type TTLConfig struct {
	DefaultTTL      time.Duration                                  `json:"default_ttl"`
	MaxTTL          time.Duration                                  `json:"max_ttl"`
	MinTTL          time.Duration                                  `json:"min_ttl"`
	ExpiredCallback func(key string)                               `json:"-"`
	UpdateCallback  func(key string, oldTTL, newTTL time.Duration) `json:"-"`
}

TTLConfig TTL管理器配置

func DefaultTTLConfig

func DefaultTTLConfig() *TTLConfig

DefaultTTLConfig 返回默认TTL配置

type TTLEntry

type TTLEntry struct {
	Key       string        `json:"key"`
	Expiry    time.Time     `json:"expiry"`
	CreatedAt time.Time     `json:"created_at"`
	TTL       time.Duration `json:"ttl"`
}

TTLEntry TTL条目信息

func (*TTLEntry) IsExpired

func (e *TTLEntry) IsExpired() bool

IsExpired 检查TTL条目是否过期

func (*TTLEntry) RemainingTTL

func (e *TTLEntry) RemainingTTL() time.Duration

RemainingTTL 返回剩余的TTL时间

type TTLError

type TTLError struct {
	Op  string
	Key string
	Err string
}

TTLError TTL操作错误

func (*TTLError) Error

func (e *TTLError) Error() string

type TTLManager

type TTLManager struct {
	// contains filtered or unexported fields
}

TTLManager TTL管理器

func NewTTLManager

func NewTTLManager(config *TTLConfig) *TTLManager

NewTTLManager 创建新的TTL管理器

func (*TTLManager) CleanupExpired

func (tm *TTLManager) CleanupExpired() int

CleanupExpired 清理所有过期的键

func (*TTLManager) Close

func (tm *TTLManager) Close() error

Close 关闭TTL管理器

func (*TTLManager) Delete

func (tm *TTLManager) Delete(key string) bool

Delete 删除键的TTL管理

func (*TTLManager) Extend

func (tm *TTLManager) Extend(key string, additionalTTL time.Duration) error

Extend 延长键的TTL时间

func (*TTLManager) Get

func (tm *TTLManager) Get(key string) (*TTLEntry, bool)

Get 获取键的TTL信息

func (*TTLManager) GetAllEntries

func (tm *TTLManager) GetAllEntries() map[string]*TTLEntry

GetAllEntries 获取所有TTL条目(用于调试)

func (*TTLManager) GetDefaultTTL

func (tm *TTLManager) GetDefaultTTL() time.Duration

GetDefaultTTL 获取默认TTL

func (*TTLManager) GetExpiredKeys

func (tm *TTLManager) GetExpiredKeys() []string

GetExpiredKeys 获取所有已过期的键

func (*TTLManager) GetRemainingTTL

func (tm *TTLManager) GetRemainingTTL(key string) (time.Duration, bool)

GetRemainingTTL 获取键的剩余TTL时间

func (*TTLManager) GetStats

func (tm *TTLManager) GetStats() map[string]interface{}

GetStats 获取TTL管理器统计信息

func (*TTLManager) IsExpired

func (tm *TTLManager) IsExpired(key string) bool

IsExpired 检查键是否已过期

func (*TTLManager) Refresh

func (tm *TTLManager) Refresh(key string, ttl ...time.Duration) error

Refresh 刷新键的TTL,重置为默认或指定时间

func (*TTLManager) Set

func (tm *TTLManager) Set(key string, ttl time.Duration) error

Set 设置键的TTL

func (*TTLManager) SetDefaultTTL

func (tm *TTLManager) SetDefaultTTL(ttl time.Duration)

SetDefaultTTL 设置默认TTL

func (*TTLManager) Size

func (tm *TTLManager) Size() int

Size 返回TTL条目数量

type WorkerPool

type WorkerPool struct {
	// contains filtered or unexported fields
}

WorkerPool 工作池并发控制器

func NewWorkerPool

func NewWorkerPool(workers int, queueSize int) *WorkerPool

NewWorkerPool 创建工作池

func (*WorkerPool) Close

func (wp *WorkerPool) Close() error

Close 关闭工作池

func (*WorkerPool) GetStats

func (wp *WorkerPool) GetStats() map[string]interface{}

GetStats 获取工作池统计信息

func (*WorkerPool) QueueLength

func (wp *WorkerPool) QueueLength() int

QueueLength 返回队列长度

func (*WorkerPool) Submit

func (wp *WorkerPool) Submit(task func()) error

Submit 提交任务到工作池

func (*WorkerPool) SubmitWithTimeout

func (wp *WorkerPool) SubmitWithTimeout(task func(), timeout time.Duration) error

SubmitWithTimeout 在指定超时时间内提交任务

func (*WorkerPool) TrySubmit

func (wp *WorkerPool) TrySubmit(task func()) bool

TrySubmit 尝试提交任务,不阻塞

type WorkerPoolStats

type WorkerPoolStats struct {
	TasksSubmitted int64 `json:"tasks_submitted"` // 提交的任务数
	TasksCompleted int64 `json:"tasks_completed"` // 完成的任务数
	TasksFailed    int64 `json:"tasks_failed"`    // 失败的任务数
	ActiveTasks    int64 `json:"active_tasks"`    // 当前活跃的任务数
	// contains filtered or unexported fields
}

WorkerPoolStats 工作池统计信息

func (*WorkerPoolStats) GetStats

func (s *WorkerPoolStats) GetStats() map[string]interface{}

GetStats 获取统计信息

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL