Documentation
ΒΆ
Index ΒΆ
- Variables
- func ExampleAdvancedPatterns()
- func ExampleAdvancedPatterns1()
- func ExampleAdvancedTypes()
- func ExampleAllDataTypes()
- func ExampleBaseCacheUsage()
- func ExampleBatchOperations()
- func ExampleConcurrencyPatterns()
- func ExampleCreateRedisCache()
- func ExampleErrorHandling()
- func ExampleKeyBuilderIntegration()
- func ExampleMain()
- func ExamplePerformance()
- func ExamplePerformanceBenchmarks()
- func ExamplePerformancePatterns()
- func ExampleRealWorldScenarios()
- func ExampleUtilityOperations()
- func ExampleWithContext()
- func IsConnectionFailed(err error) bool
- func IsDecryption(err error) bool
- func IsEncryption(err error) bool
- func IsInvalidConfig(err error) bool
- func IsInvalidKey(err error) bool
- func IsInvalidValue(err error) bool
- func IsLockExpired(err error) bool
- func IsLockFailed(err error) bool
- func IsNotFound(err error) bool
- func IsNotSupported(err error) bool
- func IsSerialization(err error) bool
- func IsStoreClosed(err error) bool
- func IsTimeout(err error) bool
- type AsyncCacheResult
- type Builder
- func (b *Builder) Build(entity, id string) string
- func (b *Builder) BuildComposite(entityA, idA, entityB, idB string) string
- func (b *Builder) BuildList(entity string, filters map[string]any) string
- func (b *Builder) BuildOrder(orderID string) string
- func (b *Builder) BuildOrg(orgID string) string
- func (b *Builder) BuildProduct(productID string) string
- func (b *Builder) BuildSession(sid string) string
- func (b *Builder) BuildUser(userID string) string
- func (b *Builder) GetConfig() (appName, env string)
- func (b *Builder) IsValidKey(key string) bool
- func (b *Builder) ParseKey(key string) (entity, id string, err error)
- func (b *Builder) Validate() error
- type Cache
- type CacheError
- type CacheWithKeyBuilder
- type Codec
- type DefaultKeyBuilder
- type DefaultKeyHasher
- type JSONCodec
- type KeyBuilder
- type KeyHasher
- type MessagePackCodec
- func (c *MessagePackCodec) Decode(data []byte, v any) error
- func (c *MessagePackCodec) Encode(v any) ([]byte, error)
- func (c *MessagePackCodec) IsCompactFloatsEnabled() bool
- func (c *MessagePackCodec) IsCompactIntsEnabled() bool
- func (c *MessagePackCodec) IsJSONTagEnabled() bool
- func (c *MessagePackCodec) IsMapKeysSorted() bool
- func (c *MessagePackCodec) Name() string
- func (c *MessagePackCodec) SortMapKeys(sort bool)
- func (c *MessagePackCodec) UseCompactFloats(use bool)
- func (c *MessagePackCodec) UseCompactInts(use bool)
- func (c *MessagePackCodec) UseJSONTag(use bool)
- type RedisConfig
- type TypedCache
- func (tc *TypedCache[T]) Close() error
- func (tc *TypedCache[T]) Del(ctx context.Context, keys ...string) <-chan AsyncCacheResult[T]
- func (tc *TypedCache[T]) Exists(ctx context.Context, key string) <-chan AsyncCacheResult[T]
- func (tc *TypedCache[T]) Get(ctx context.Context, key string) <-chan AsyncCacheResult[T]
- func (tc *TypedCache[T]) IncrBy(ctx context.Context, key string, delta int64, ttlIfCreate time.Duration) <-chan AsyncCacheResult[T]
- func (tc *TypedCache[T]) MGet(ctx context.Context, keys ...string) <-chan AsyncCacheResult[T]
- func (tc *TypedCache[T]) MSet(ctx context.Context, items map[string]T, ttl time.Duration) <-chan AsyncCacheResult[T]
- func (tc *TypedCache[T]) Set(ctx context.Context, key string, val T, ttl time.Duration) <-chan AsyncCacheResult[T]
- func (tc *TypedCache[T]) TTL(ctx context.Context, key string) <-chan AsyncCacheResult[T]
- func (tc *TypedCache[T]) WithContext(ctx context.Context) *TypedCache[T]
Constants ΒΆ
This section is empty.
Variables ΒΆ
var ( ErrEmptyAppName = errors.New("app name cannot be empty") ErrEmptyEnv = errors.New("environment cannot be empty") ErrEmptySecret = errors.New("secret cannot be empty") ErrEmptyEntity = errors.New("entity cannot be empty") ErrEmptyID = errors.New("id cannot be empty") ErrEmptySessionID = errors.New("session id cannot be empty") ErrInvalidKeyFormat = errors.New("invalid key format") ErrInvalidKeyPrefix = errors.New("invalid key prefix") ErrHashFailed = errors.New("hash operation failed") ErrBuilderNotValid = errors.New("builder is not valid") )
Common errors
var ( ErrNotFound = errors.New("cache: key not found") ErrTimeout = errors.New("cache: operation timeout") ErrInvalidKey = errors.New("cache: invalid key") ErrInvalidValue = errors.New("cache: invalid value") ErrSerialization = errors.New("cache: serialization error") ErrEncryption = errors.New("cache: encryption error") ErrDecryption = errors.New("cache: decryption error") ErrLockFailed = errors.New("cache: lock acquisition failed") ErrLockExpired = errors.New("cache: lock expired") ErrStoreClosed = errors.New("cache: store is closed") ErrConnectionFailed = errors.New("cache: connection failed") ErrInvalidConfig = errors.New("cache: invalid configuration") ErrNotSupported = errors.New("cache: operation not supported") )
Common cache errors
Functions ΒΆ
func ExampleAdvancedPatterns ΒΆ added in v1.3.3
func ExampleAdvancedPatterns()
ExampleAdvancedPatterns demonstrates advanced caching patterns
func ExampleAdvancedPatterns1 ΒΆ added in v1.3.3
func ExampleAdvancedPatterns1()
ExampleAdvancedPatterns demonstrates advanced caching patterns
func ExampleAdvancedTypes ΒΆ added in v1.3.3
func ExampleAdvancedTypes()
ExampleAdvancedTypes demonstrates advanced Go types
func ExampleAllDataTypes ΒΆ added in v1.3.3
func ExampleAllDataTypes()
ExampleAllDataTypes demonstrates usage with all common Go data types
func ExampleBaseCacheUsage ΒΆ added in v1.3.3
func ExampleBaseCacheUsage()
ExampleBaseCacheUsage demonstrates using the cache without typed wrappers
func ExampleBatchOperations ΒΆ added in v1.3.3
func ExampleBatchOperations()
ExampleBatchOperations demonstrates batch operations with different types
func ExampleConcurrencyPatterns ΒΆ added in v1.3.3
func ExampleConcurrencyPatterns()
ExampleConcurrencyPatterns demonstrates concurrency patterns
func ExampleCreateRedisCache ΒΆ added in v1.3.3
func ExampleCreateRedisCache()
ExampleCreateRedisCache demonstrates using CreateRedisCache function
func ExampleErrorHandling ΒΆ added in v1.3.3
func ExampleErrorHandling()
ExampleErrorHandling demonstrates error handling patterns
func ExampleKeyBuilderIntegration ΒΆ added in v1.3.3
func ExampleKeyBuilderIntegration()
ExampleKeyBuilderIntegration demonstrates comprehensive KeyBuilder usage
func ExampleMain ΒΆ added in v1.3.3
func ExampleMain()
ExampleMain demonstrates how to run all examples
func ExamplePerformance ΒΆ added in v1.3.3
func ExamplePerformance()
ExamplePerformance demonstrates performance considerations
func ExamplePerformanceBenchmarks ΒΆ added in v1.3.3
func ExamplePerformanceBenchmarks()
ExamplePerformanceBenchmarks demonstrates performance testing patterns
func ExamplePerformancePatterns ΒΆ added in v1.3.3
func ExamplePerformancePatterns()
ExamplePerformancePatterns demonstrates performance optimization patterns
func ExampleRealWorldScenarios ΒΆ added in v1.3.3
func ExampleRealWorldScenarios()
ExampleRealWorldScenarios demonstrates real-world usage patterns
func ExampleUtilityOperations ΒΆ added in v1.3.3
func ExampleUtilityOperations()
ExampleUtilityOperations demonstrates utility operations
func ExampleWithContext ΒΆ added in v1.3.3
func ExampleWithContext()
ExampleWithContext demonstrates context usage
func IsConnectionFailed ΒΆ
IsConnectionFailed checks if the error is a connection failure error
func IsDecryption ΒΆ
IsDecryption checks if the error is a decryption error
func IsEncryption ΒΆ
IsEncryption checks if the error is an encryption error
func IsInvalidConfig ΒΆ
IsInvalidConfig checks if the error is an invalid configuration error
func IsInvalidKey ΒΆ
IsInvalidKey checks if the error is an invalid key error
func IsInvalidValue ΒΆ
IsInvalidValue checks if the error is an invalid value error
func IsLockExpired ΒΆ
IsLockExpired checks if the error is a lock expiration error
func IsLockFailed ΒΆ
IsLockFailed checks if the error is a lock failure error
func IsNotFound ΒΆ
IsNotFound checks if the error is a not found error
func IsNotSupported ΒΆ
IsNotSupported checks if the error is a not supported operation error
func IsSerialization ΒΆ
IsSerialization checks if the error is a serialization error
func IsStoreClosed ΒΆ
IsStoreClosed checks if the error is a store closed error
Types ΒΆ
type AsyncCacheResult ΒΆ
type AsyncCacheResult[T any] struct { // Value contains the retrieved value for single-value operations Value T // Values contains multiple values for batch operations (MGet, MSet) Values map[string]T // Found indicates whether the key was found (for Get, Exists operations) Found bool // TTL contains the time-to-live for TTL operations TTL time.Duration // Int contains integer results for IncrBy operations Int int64 // Count contains count results for operations like Del, Flush Count int64 // Keys contains key lists for Keys operations Keys []string // Size contains size information for Size operations Size int64 // Error contains any error that occurred during the operation Error error // Metadata contains additional operation metadata Metadata map[string]interface{} }
AsyncCacheResult represents the result of an asynchronous cache operation
type Builder ΒΆ
type Builder struct {
// contains filtered or unexported fields
}
Builder implements the KeyBuilder interface with namespaced key generation Note: This struct is not thread-safe. If concurrent access is needed, external synchronization should be used.
func NewBuilder ΒΆ
NewBuilder creates a new key builder with validation
func (*Builder) Build ΒΆ
Build creates a namespaced entity key Implements KeyBuilder.Build(entity, id string) string
func (*Builder) BuildComposite ΒΆ
BuildComposite creates a composite key for related entities Implements KeyBuilder.BuildComposite(entityA, idA, entityB, idB string) string
func (*Builder) BuildList ΒΆ
BuildList creates a list key with hashed filters Implements KeyBuilder.BuildList(entity string, filters map[string]any) string
func (*Builder) BuildOrder ΒΆ
BuildOrder creates an order key
func (*Builder) BuildProduct ΒΆ
BuildProduct creates a product key
func (*Builder) BuildSession ΒΆ
BuildSession creates a session key Implements KeyBuilder.BuildSession(sid string) string
func (*Builder) GetConfig ΒΆ
GetConfig returns the Builder's configuration (without the secret for security)
func (*Builder) IsValidKey ΒΆ
IsValidKey checks if a key follows the expected format
type Cache ΒΆ
type Cache interface { WithContext(ctx context.Context) Cache // Non-blocking operations only Get(ctx context.Context, key string) <-chan AsyncCacheResult[any] Set(ctx context.Context, key string, val any, ttl time.Duration) <-chan AsyncCacheResult[any] MGet(ctx context.Context, keys ...string) <-chan AsyncCacheResult[any] MSet(ctx context.Context, items map[string]any, ttl time.Duration) <-chan AsyncCacheResult[any] Del(ctx context.Context, keys ...string) <-chan AsyncCacheResult[any] Exists(ctx context.Context, key string) <-chan AsyncCacheResult[any] TTL(ctx context.Context, key string) <-chan AsyncCacheResult[any] IncrBy(ctx context.Context, key string, delta int64, ttlIfCreate time.Duration) <-chan AsyncCacheResult[any] Close() error }
func CreateRedisCache ΒΆ added in v1.3.3
func CreateRedisCache( addr string, password string, db int, poolSize int, minIdleConns int, maxRetries int, dialTimeout time.Duration, readTimeout time.Duration, writeTimeout time.Duration, enablePipelining bool, enableMetrics bool, healthCheckInterval time.Duration, healthCheckTimeout time.Duration, codec Codec, keyBuilder KeyBuilder, keyHasher KeyHasher, ) (Cache, error)
CreateRedisCacheWithParams creates a Redis cache instance with all parameters as input This function takes all configuration parameters, creates a Redis client, and returns a cache instance
func NewRedisCache ΒΆ added in v1.3.3
func NewRedisCache(client *redis.Client, codec Codec, keyBuilder KeyBuilder, keyHasher KeyHasher) Cache
NewRedisCache creates a new cache instance using go-redis client
type CacheError ΒΆ
type CacheError struct { Op string Key string Message string Err error Code string // Error code for better categorization }
CacheError represents a cache-specific error with additional context
func NewCacheError ΒΆ
func NewCacheError(op, key, message string, err error) *CacheError
NewCacheError creates a new cache error with validation
func NewCacheErrorWithCode ΒΆ
func NewCacheErrorWithCode(op, key, message, code string, err error) *CacheError
NewCacheErrorWithCode creates a new cache error with a specific error code
func (*CacheError) Error ΒΆ
func (e *CacheError) Error() string
Error implements the error interface
func (*CacheError) Unwrap ΒΆ
func (e *CacheError) Unwrap() error
Unwrap returns the underlying error
type CacheWithKeyBuilder ΒΆ added in v1.3.3
type CacheWithKeyBuilder interface { Cache // KeyBuilder helper methods for easier key generation BuildKey(entity, id string) string BuildListKey(entity string, filters map[string]any) string BuildCompositeKey(entityA, idA, entityB, idB string) string BuildSessionKey(sid string) string // Get the underlying KeyBuilder instance GetKeyBuilder() KeyBuilder }
CacheWithKeyBuilder extends the Cache interface with KeyBuilder helper methods
type DefaultKeyBuilder ΒΆ added in v1.3.3
type DefaultKeyBuilder struct{}
Default implementations
func (*DefaultKeyBuilder) Build ΒΆ added in v1.3.3
func (b *DefaultKeyBuilder) Build(entity, id string) string
func (*DefaultKeyBuilder) BuildComposite ΒΆ added in v1.3.3
func (b *DefaultKeyBuilder) BuildComposite(entityA, idA, entityB, idB string) string
func (*DefaultKeyBuilder) BuildList ΒΆ added in v1.3.3
func (b *DefaultKeyBuilder) BuildList(entity string, filters map[string]any) string
func (*DefaultKeyBuilder) BuildSession ΒΆ added in v1.3.3
func (b *DefaultKeyBuilder) BuildSession(sid string) string
type DefaultKeyHasher ΒΆ added in v1.3.3
type DefaultKeyHasher struct{}
func (*DefaultKeyHasher) Hash ΒΆ added in v1.3.3
func (h *DefaultKeyHasher) Hash(data string) string
type JSONCodec ΒΆ
type JSONCodec struct { // AllowNilValues determines whether nil values are allowed to be encoded/decoded AllowNilValues bool // EnableDebugLogging enables debug logging for nil value handling EnableDebugLogging bool }
JSONCodec implements the Codec interface using JSON serialization
func NewJSONCodecWithOptions ΒΆ
NewJSONCodecWithOptions creates a new JSON codec with custom options
type KeyBuilder ΒΆ
type KeyBuilder interface { Build(entity, id string) string BuildList(entity string, filters map[string]any) string BuildComposite(entityA, idA, entityB, idB string) string BuildSession(sid string) string }
KeyBuilder defines the interface for key generation
type MessagePackCodec ΒΆ
type MessagePackCodec struct {
// contains filtered or unexported fields
}
MessagePackCodec implements the Codec interface using MessagePack serialization
func NewMessagePackCodec ΒΆ
func NewMessagePackCodec() *MessagePackCodec
NewMessagePackCodec creates a new MessagePack codec with default settings
func NewMessagePackCodecWithOptions ΒΆ
func NewMessagePackCodecWithOptions(useJSONTag, useCompactInts, useCompactFloats, sortMapKeys bool) *MessagePackCodec
NewMessagePackCodecWithOptions creates a new MessagePack codec with custom options
func (*MessagePackCodec) Decode ΒΆ
func (c *MessagePackCodec) Decode(data []byte, v any) error
Decode deserializes MessagePack bytes to a value
func (*MessagePackCodec) Encode ΒΆ
func (c *MessagePackCodec) Encode(v any) ([]byte, error)
Encode serializes a value to MessagePack bytes
func (*MessagePackCodec) IsCompactFloatsEnabled ΒΆ
func (c *MessagePackCodec) IsCompactFloatsEnabled() bool
IsCompactFloatsEnabled returns whether compact floats are being used
func (*MessagePackCodec) IsCompactIntsEnabled ΒΆ
func (c *MessagePackCodec) IsCompactIntsEnabled() bool
IsCompactIntsEnabled returns whether compact integers are being used
func (*MessagePackCodec) IsJSONTagEnabled ΒΆ
func (c *MessagePackCodec) IsJSONTagEnabled() bool
IsJSONTagEnabled returns whether JSON tags are being used
func (*MessagePackCodec) IsMapKeysSorted ΒΆ
func (c *MessagePackCodec) IsMapKeysSorted() bool
IsMapKeysSorted returns whether map keys are being sorted
func (*MessagePackCodec) Name ΒΆ
func (c *MessagePackCodec) Name() string
Name returns the codec name
func (*MessagePackCodec) SortMapKeys ΒΆ
func (c *MessagePackCodec) SortMapKeys(sort bool)
SortMapKeys enables/disables map key sorting
func (*MessagePackCodec) UseCompactFloats ΒΆ
func (c *MessagePackCodec) UseCompactFloats(use bool)
UseCompactFloats enables/disables compact float encoding
func (*MessagePackCodec) UseCompactInts ΒΆ
func (c *MessagePackCodec) UseCompactInts(use bool)
UseCompactInts enables/disables compact integer encoding
func (*MessagePackCodec) UseJSONTag ΒΆ
func (c *MessagePackCodec) UseJSONTag(use bool)
UseJSONTag enables/disables JSON tag usage for field names
type RedisConfig ΒΆ
type RedisConfig struct { // Redis connection settings Addr string `yaml:"addr" json:"addr" validate:"required,max:256" default:"localhost:6379"` // max 256 chars Password string `yaml:"password" json:"password" validate:"omitempty" default:""` // optional DB int `yaml:"db" json:"db" validate:"gte:0,lte:15" default:"0"` // 0 to 15 // Connection pool settings PoolSize int `yaml:"pool_size" json:"pool_size" validate:"min:1,max:1000" default:"10"` // 1 to 1000 MinIdleConns int `yaml:"min_idle_conns" json:"min_idle_conns" validate:"gte:0" default:"5"` // 0 or more MaxRetries int `yaml:"max_retries" json:"max_retries" validate:"gte:0,lte:10" default:"3"` // 0 to 10 // Timeout settings DialTimeout time.Duration `yaml:"dial_timeout" json:"dial_timeout" validate:"min=100ms,max=5m" default:"5s"` // 100ms to 5min ReadTimeout time.Duration `yaml:"read_timeout" json:"read_timeout" validate:"min=100ms,max=5m" default:"3s"` // 100ms to 5min WriteTimeout time.Duration `yaml:"write_timeout" json:"write_timeout" validate:"min=100ms,max=5m" default:"3s"` // 100ms to 5min // Performance settings EnablePipelining bool `yaml:"enable_pipelining" json:"enable_pipelining"` EnableMetrics bool `yaml:"enable_metrics" json:"enable_metrics"` // Health check settings HealthCheckInterval time.Duration `yaml:"health_check_interval" json:"health_check_interval" validate:"min=1s,max=2m" default:"30s"` // 1s to 2min HealthCheckTimeout time.Duration `yaml:"health_check_timeout" json:"health_check_timeout" validate:"min=1s,max=2m" default:"5s"` // 1s to 2min }
Config holds Redis store configuration
func NewRedisConfig ΒΆ added in v1.3.3
func NewRedisConfig( addr string, password string, db int, poolSize int, minIdleConns int, maxRetries int, dialTimeout time.Duration, readTimeout time.Duration, writeTimeout time.Duration, enablePipelining bool, enableMetrics bool, healthCheckInterval time.Duration, healthCheckTimeout time.Duration, ) *RedisConfig
NewRedisConfigWithParams creates a new RedisConfig with all parameters as input
func (*RedisConfig) ConnectRedisClient ΒΆ added in v1.3.3
func (r *RedisConfig) ConnectRedisClient(ctx context.Context) (*redis.Client, error)
ConnectRedisClient creates a Redis client and tests the connection
func (*RedisConfig) CreateRedisClient ΒΆ added in v1.3.3
func (r *RedisConfig) CreateRedisClient() *redis.Client
CreateRedisClient creates a Redis client from the RedisConfig
func (*RedisConfig) Validate ΒΆ added in v1.3.3
func (r *RedisConfig) Validate() *validatorx.ValidationResult
Validate validates the RedisConfig using go-validatorx
type TypedCache ΒΆ added in v1.3.3
type TypedCache[T any] struct { // contains filtered or unexported fields }
TypedCache provides type-safe operations on top of the base Cache interface
func NewTypedCache ΒΆ added in v1.3.3
func NewTypedCache[T any](cache Cache) *TypedCache[T]
NewTypedCache creates a type-safe wrapper around a Cache instance
func (*TypedCache[T]) Close ΒΆ added in v1.3.3
func (tc *TypedCache[T]) Close() error
Close closes the cache and releases resources
func (*TypedCache[T]) Del ΒΆ added in v1.3.3
func (tc *TypedCache[T]) Del(ctx context.Context, keys ...string) <-chan AsyncCacheResult[T]
Del removes keys from the cache (non-blocking)
func (*TypedCache[T]) Exists ΒΆ added in v1.3.3
func (tc *TypedCache[T]) Exists(ctx context.Context, key string) <-chan AsyncCacheResult[T]
Exists checks if a key exists in the cache (non-blocking)
func (*TypedCache[T]) Get ΒΆ added in v1.3.3
func (tc *TypedCache[T]) Get(ctx context.Context, key string) <-chan AsyncCacheResult[T]
Get retrieves a value from the cache (non-blocking)
func (*TypedCache[T]) IncrBy ΒΆ added in v1.3.3
func (tc *TypedCache[T]) IncrBy(ctx context.Context, key string, delta int64, ttlIfCreate time.Duration) <-chan AsyncCacheResult[T]
IncrBy increments a key by the given delta (non-blocking)
func (*TypedCache[T]) MGet ΒΆ added in v1.3.3
func (tc *TypedCache[T]) MGet(ctx context.Context, keys ...string) <-chan AsyncCacheResult[T]
MGet retrieves multiple values from the cache (non-blocking)
func (*TypedCache[T]) MSet ΒΆ added in v1.3.3
func (tc *TypedCache[T]) MSet(ctx context.Context, items map[string]T, ttl time.Duration) <-chan AsyncCacheResult[T]
MSet stores multiple values in the cache (non-blocking)
func (*TypedCache[T]) Set ΒΆ added in v1.3.3
func (tc *TypedCache[T]) Set(ctx context.Context, key string, val T, ttl time.Duration) <-chan AsyncCacheResult[T]
Set stores a value in the cache (non-blocking)
func (*TypedCache[T]) TTL ΒΆ added in v1.3.3
func (tc *TypedCache[T]) TTL(ctx context.Context, key string) <-chan AsyncCacheResult[T]
TTL gets the time to live of a key (non-blocking)
func (*TypedCache[T]) WithContext ΒΆ added in v1.3.3
func (tc *TypedCache[T]) WithContext(ctx context.Context) *TypedCache[T]
WithContext returns a new typed cache instance with the given context