Library for communicating with Redis Clusters. Built on top of redis-py lib
npx @tessl/cli install tessl/pypi-redis-py-cluster@2.1.00
# Redis-py-cluster
1
2
A Python client library for Redis Cluster that provides cluster-aware implementations of Redis commands with automatic slot management, node discovery, failover support, and connection pooling. Built on top of the redis-py library, it extends standard Redis functionality to work seamlessly with Redis Cluster's distributed architecture.
3
4
## Package Information
5
6
- **Package Name**: redis-py-cluster
7
- **Language**: Python
8
- **Installation**: `pip install redis-py-cluster`
9
10
## Core Imports
11
12
```python
13
from rediscluster import RedisCluster
14
```
15
16
All public components:
17
18
```python
19
from rediscluster import (
20
RedisCluster,
21
ClusterConnection,
22
ClusterConnectionPool,
23
ClusterBlockingConnectionPool,
24
ClusterPipeline,
25
RedisClusterException,
26
RedisClusterError,
27
ClusterDownException,
28
ClusterDownError,
29
ClusterCrossSlotError,
30
MovedError,
31
AskError,
32
TryAgainError,
33
MasterDownError
34
)
35
```
36
37
## Basic Usage
38
39
```python
40
from rediscluster import RedisCluster
41
42
# Connect to Redis Cluster
43
startup_nodes = [{"host": "127.0.0.1", "port": "7000"}]
44
rc = RedisCluster(startup_nodes=startup_nodes, decode_responses=True)
45
46
# Execute standard Redis commands
47
rc.set("key", "value")
48
result = rc.get("key")
49
50
# Multi-key operations work across cluster nodes
51
rc.mset({"key1": "value1", "key2": "value2", "key3": "value3"})
52
values = rc.mget(["key1", "key2", "key3"])
53
54
# Pipeline operations
55
pipe = rc.pipeline()
56
pipe.set("pkey1", "pvalue1")
57
pipe.get("pkey1")
58
pipe.incr("counter")
59
results = pipe.execute()
60
61
# Cluster management
62
cluster_info = rc.cluster_info()
63
nodes = rc.cluster_nodes()
64
```
65
66
## Architecture
67
68
Redis-py-cluster extends redis-py with cluster-aware functionality:
69
70
- **RedisCluster**: Main client extending Redis class with cluster-specific command implementations
71
- **NodeManager**: Manages cluster topology discovery and slot-to-node mapping
72
- **Connection Pools**: Per-node connection pooling with automatic failover
73
- **Pipeline**: Cluster-aware command batching with proper node routing
74
- **Exception Handling**: Cluster-specific errors like MOVED/ASK redirections
75
76
The library automatically handles Redis Cluster's 16,384 hash slots, discovers node topology, manages failover scenarios, and routes commands to appropriate nodes while maintaining the familiar redis-py API.
77
78
## Capabilities
79
80
### Redis Cluster Client
81
82
The primary interface for interacting with Redis clusters, providing all standard Redis operations with cluster-aware implementations and additional cluster management commands.
83
84
```python { .api }
85
class RedisCluster(Redis):
86
def __init__(self, host=None, port=None, startup_nodes=None,
87
max_connections=None, max_connections_per_node=False,
88
init_slot_cache=True, readonly_mode=False,
89
reinitialize_steps=None, skip_full_coverage_check=False,
90
nodemanager_follow_cluster=False, connection_class=None,
91
read_from_replicas=False, cluster_down_retry_attempts=3,
92
host_port_remap=None, **kwargs)
93
94
@classmethod
95
def from_url(cls, url, **kwargs): ...
96
97
def pubsub(self, **kwargs): ...
98
def pipeline(self, transaction=None, shard_hint=None, read_from_replicas=False): ...
99
def execute_command(self, *args, **kwargs): ...
100
```
101
102
[Redis Cluster Client](./client.md)
103
104
### Connection Management
105
106
Connection classes and pools for managing TCP/SSL connections to cluster nodes with automatic discovery, load balancing, and failover support.
107
108
```python { .api }
109
class ClusterConnection(Connection):
110
def __init__(self, readonly=False, **kwargs): ...
111
112
class ClusterConnectionPool(ConnectionPool):
113
def __init__(self, startup_nodes=None, init_slot_cache=True,
114
connection_class=None, max_connections=None,
115
max_connections_per_node=False, **kwargs): ...
116
117
def get_connection_by_node(self, node): ...
118
def get_connection_by_slot(self, slot): ...
119
```
120
121
[Connection Management](./connections.md)
122
123
### Cluster Pipeline
124
125
Cluster-aware pipeline for batching commands with automatic routing to appropriate nodes while respecting Redis Cluster constraints.
126
127
```python { .api }
128
class ClusterPipeline(RedisCluster):
129
def __init__(self, connection_pool, result_callbacks=None,
130
response_callbacks=None, startup_nodes=None,
131
read_from_replicas=False, cluster_down_retry_attempts=3): ...
132
133
def execute_command(self, *args, **kwargs): ...
134
def execute(self, raise_on_error=True): ...
135
def reset(self): ...
136
```
137
138
[Cluster Pipeline](./pipeline.md)
139
140
### Exception Handling
141
142
Comprehensive exception classes for handling cluster-specific errors, redirections, and failure scenarios.
143
144
```python { .api }
145
class RedisClusterException(Exception): ...
146
class ClusterDownError(ClusterError, ResponseError): ...
147
class MovedError(AskError): ...
148
class AskError(ResponseError):
149
def __init__(self, resp): ...
150
# Properties: slot_id, host, port, node_addr, message
151
```
152
153
[Exception Handling](./exceptions.md)
154
155
### Cluster Pub/Sub
156
157
Cluster-aware publish/subscribe functionality for message broadcasting and real-time communication across cluster nodes.
158
159
```python { .api }
160
class ClusterPubSub(PubSub):
161
def __init__(self, connection_pool, shard_hint=None, ignore_subscribe_messages=False): ...
162
def execute_command(self, *args, **kwargs): ...
163
def subscribe(self, *args, **kwargs): ...
164
def psubscribe(self, *args, **kwargs): ...
165
def get_message(self, timeout=0, ignore_subscribe_messages=False): ...
166
def listen(self): ...
167
```
168
169
[Cluster Pub/Sub](./pubsub.md)
170
171
## Types
172
173
```python { .api }
174
# Startup node specification
175
StartupNode = TypedDict('StartupNode', {
176
'host': str,
177
'port': Union[str, int]
178
})
179
180
# Host/port remapping configuration
181
HostPortRemap = Dict[Tuple[str, int], Tuple[str, int]]
182
183
# Node information from cluster
184
NodeInfo = Dict[str, Union[str, int, List[int]]]
185
186
# Cluster slots mapping
187
SlotsMapping = List[List[Union[int, List[Union[str, int]]]]]
188
```