Redis¶
The utkit.store.redis module provides a singleton-backed Redis client with a simple interface for common cache and store operations, built on top of redis-py.
Installation¶
redis is part of the optional store extras. Install utkit with the store extra:
Or with uv:
Quick start¶
from utkit.store.redis import RedisManager
redis = RedisManager(url="redis://localhost:6379/0")
redis.set("user:1", {"name": "Alice", "role": "admin"}, ttl=3600)
user = redis.get("user:1")
print(user) # {'name': 'Alice', 'role': 'admin'}
RedisManager¶
A class that wraps a shared redis.Redis client instance. The underlying connection is created once per process (singleton pattern) and reused across all RedisManager instances.
Values are automatically serialised to JSON on write and deserialised on read, so you can store any JSON-compatible Python object.
Constructor¶
| Parameter | Type | Description |
|---|---|---|
url |
str |
Redis connection URL, e.g. redis://localhost:6379/0 or rediss://user:pass@host:6380/0 for TLS |
set¶
Stores a value under the given key, serialised as JSON.
| Parameter | Type | Default | Description |
|---|---|---|---|
key |
str |
— | The Redis key |
value |
Any |
— | Any JSON-serialisable value |
ttl |
int \| None |
None |
Expiry in seconds. None means no expiry. |
Returns: bool — True if the key was set successfully.
Raises: RuntimeError — if the Redis operation fails.
get¶
Retrieves and deserialises the value stored at a key.
| Parameter | Type | Description |
|---|---|---|
key |
str |
The Redis key to retrieve |
Returns: The deserialised Python value, or None if the key does not exist.
Raises: RuntimeError — if the Redis operation fails.
delete¶
Deletes a key from Redis.
| Parameter | Type | Description |
|---|---|---|
key |
str |
The Redis key to delete |
Returns: int — the number of keys deleted (1 if found and deleted, 0 if the key did not exist).
Raises: RuntimeError — if the Redis operation fails.
exists¶
Checks whether a key exists in Redis.
| Parameter | Type | Description |
|---|---|---|
key |
str |
The Redis key to check |
Returns: bool — True if the key exists, False otherwise.
expire¶
Sets or updates the TTL (time-to-live) of an existing key.
| Parameter | Type | Description |
|---|---|---|
key |
str |
The Redis key to update |
ttl |
int |
Expiry time in seconds |
Returns: bool — True if the TTL was set, False if the key does not exist.
Connection URLs¶
| Scheme | Description |
|---|---|
redis://host:port/db |
Standard unencrypted connection |
rediss://host:port/db |
TLS-encrypted connection |
redis://:password@host:port/db |
Password-authenticated connection |
unix:///path/to/socket.sock |
Unix domain socket |