Redis Backend
mongo_ops.cache.redis_backend
Summary
Redis cache backend with key prefixing and pub/sub invalidation.
Classes
RedisCacheBackend
Bases: CacheBackend
Cache backend backed by Redis with key prefixing.
Values are stored with a configurable key prefix, and deletions publish on a shared invalidation channel so other processes can react.
Notes
Lifecycle:
1 2 | |
Initialize the backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redis_client |
Redis
|
Asynchronous Redis client. |
required |
key_prefix |
str
|
Prefix applied to all keys. Defaults to "". |
''
|
default_ttl |
int
|
Default time-to-live for entries, in seconds. |
300
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If the redis package is not installed. |
Functions
clear_pattern
async
Remove all keys matching a glob pattern via SCAN/DEL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern |
str
|
Glob-style pattern; a trailing |
required |
delete
async
Remove a key and publish an invalidation notice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key |
str
|
The cache key. |
required |
exists
async
Check whether a key is present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key |
str
|
The cache key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the key exists, False otherwise. |
get
async
Fetch a value from the cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key |
str
|
The cache key. |
required |
Returns:
| Type | Description |
|---|---|
bytes | None
|
Optional[bytes]: The cached bytes, or None on a miss. |
get_stats
async
Return a snapshot of cache statistics.
Returns:
| Name | Type | Description |
|---|---|---|
CacheStats |
CacheStats
|
Stats with current_size taken from Redis dbsize. |
publish_invalidate
async
Publish an invalidation notice for a key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key |
str
|
The cache key to broadcast. |
required |
set
async
Store a value in the cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key |
str
|
The cache key. |
required |
value |
bytes
|
The byte-encoded value to store. |
required |
ttl |
Optional[int]
|
Time-to-live in seconds; defaults to the backend default. |
None
|
Functions
decode_value
Decode cache bytes back into a dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data |
bytes
|
UTF-8 JSON bytes produced by encode_value(). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
The decoded dictionary. |
encode_value
Encode a dict into cache-ready bytes.
Non-serializable values (e.g., ObjectId) are coerced with str().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value |
dict
|
The dictionary to encode. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
UTF-8 JSON bytes. |