or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-support.mdcluster-support.mdconnection-management.mdcore-client.mddistributed-locking.mderror-handling.mdhigh-availability.mdindex.mdpipelines-transactions.mdpubsub-messaging.md

connection-management.mddocs/

0

# Connection Management

1

2

Redis connection management provides efficient connection pooling, SSL support, and various connection types for optimal performance and security. Connection pools manage multiple connections to reduce overhead and improve throughput.

3

4

## Capabilities

5

6

### Connection Pool Classes

7

8

Connection pools manage multiple connections to Redis servers for improved performance and resource management.

9

10

```python { .api }

11

class ConnectionPool:

12

def __init__(

13

self,

14

connection_class: Type[Connection] = Connection,

15

max_connections: Optional[int] = None,

16

retry_on_timeout: bool = False,

17

retry_on_error: Optional[List[Type[Exception]]] = None,

18

**connection_kwargs

19

): ...

20

21

def get_connection(self, command_name: str, **kwargs) -> Connection: ...

22

23

def make_connection(self) -> Connection: ...

24

25

def release(self, connection: Connection) -> None: ...

26

27

def disconnect(self, inuse_connections: bool = True) -> None: ...

28

29

def reset(self) -> None: ...

30

31

@classmethod

32

def from_url(cls, url: str, **kwargs) -> "ConnectionPool": ...

33

34

class BlockingConnectionPool(ConnectionPool):

35

def __init__(

36

self,

37

max_connections: int = 50,

38

timeout: int = 20,

39

connection_class: Type[Connection] = Connection,

40

queue_class: Type = None,

41

**connection_kwargs

42

): ...

43

```

44

45

### Connection Classes

46

47

Different connection types for various Redis deployment scenarios and security requirements.

48

49

```python { .api }

50

class Connection:

51

def __init__(

52

self,

53

host: str = "localhost",

54

port: int = 6379,

55

db: int = 0,

56

username: Optional[str] = None,

57

password: Optional[str] = None,

58

socket_timeout: Optional[float] = None,

59

socket_connect_timeout: Optional[float] = None,

60

socket_keepalive: bool = False,

61

socket_keepalive_options: Optional[Dict[str, int]] = None,

62

socket_type: int = 0,

63

retry_on_timeout: bool = False,

64

retry_on_error: Optional[List[Type[Exception]]] = None,

65

encoding: str = "utf-8",

66

encoding_errors: str = "strict",

67

decode_responses: bool = False,

68

parser_class: Type = None,

69

socket_read_size: int = 65536,

70

health_check_interval: int = 0,

71

client_name: Optional[str] = None,

72

lib_name: Optional[str] = None,

73

lib_version: Optional[str] = None,

74

**kwargs

75

): ...

76

77

def connect(self) -> None: ...

78

79

def disconnect(self) -> None: ...

80

81

def send_command(self, *args) -> None: ...

82

83

def send_packed_command(self, command: bytes) -> None: ...

84

85

def read_response(self) -> Any: ...

86

87

def pack_command(self, *args) -> bytes: ...

88

89

def pack_commands(self, commands: List[Tuple]) -> bytes: ...

90

91

class SSLConnection(Connection):

92

def __init__(

93

self,

94

ssl_keyfile: Optional[str] = None,

95

ssl_certfile: Optional[str] = None,

96

ssl_cert_reqs: str = "required",

97

ssl_ca_certs: Optional[str] = None,

98

ssl_ca_data: Optional[str] = None,

99

ssl_check_hostname: bool = False,

100

ssl_password: Optional[str] = None,

101

ssl_disable_dev_restrictions: bool = False,

102

**kwargs

103

): ...

104

105

class UnixDomainSocketConnection(Connection):

106

def __init__(

107

self,

108

path: str = "",

109

db: int = 0,

110

username: Optional[str] = None,

111

password: Optional[str] = None,

112

socket_timeout: Optional[float] = None,

113

encoding: str = "utf-8",

114

encoding_errors: str = "strict",

115

decode_responses: bool = False,

116

retry_on_timeout: bool = False,

117

retry_on_error: Optional[List[Type[Exception]]] = None,

118

parser_class: Type = None,

119

socket_read_size: int = 65536,

120

health_check_interval: int = 0,

121

client_name: Optional[str] = None,

122

**kwargs

123

): ...

124

```

125

126

### Sentinel Connection Classes

127

128

Specialized connection classes for Redis Sentinel high availability configurations.

129

130

```python { .api }

131

class SentinelConnectionPool(ConnectionPool):

132

def __init__(

133

self,

134

service_name: str,

135

sentinel_manager: SentinelManager,

136

**kwargs

137

): ...

138

139

class SentinelManagedConnection(Connection):

140

def __init__(

141

self,

142

**kwargs

143

): ...

144

145

class SentinelManagedSSLConnection(SSLConnection):

146

def __init__(

147

self,

148

**kwargs

149

): ...

150

```

151

152

### Utility Functions

153

154

Helper functions for creating connections and managing connection URLs.

155

156

```python { .api }

157

def from_url(

158

url: str,

159

**kwargs

160

) -> Redis: ...

161

```

162

163

## Usage Examples

164

165

### Basic Connection Pool Usage

166

167

```python

168

import redis

169

from redis import ConnectionPool, Connection

170

171

# Create a connection pool

172

pool = ConnectionPool(

173

host='localhost',

174

port=6379,

175

db=0,

176

max_connections=20,

177

retry_on_timeout=True

178

)

179

180

# Create Redis client with pool

181

r = redis.Redis(connection_pool=pool)

182

183

# Multiple clients can share the same pool

184

r1 = redis.Redis(connection_pool=pool)

185

r2 = redis.Redis(connection_pool=pool)

186

```

187

188

### SSL Connection Configuration

189

190

```python

191

from redis import Redis, ConnectionPool, SSLConnection

192

193

# SSL connection pool

194

ssl_pool = ConnectionPool(

195

connection_class=SSLConnection,

196

host='redis-ssl.example.com',

197

port=6380,

198

ssl_cert_reqs='required',

199

ssl_ca_certs='/path/to/ca-certificates.crt',

200

ssl_certfile='/path/to/client.crt',

201

ssl_keyfile='/path/to/client.key',

202

ssl_check_hostname=True

203

)

204

205

# Create Redis client with SSL

206

redis_ssl = Redis(connection_pool=ssl_pool)

207

208

# Alternatively, create SSL client directly

209

redis_ssl = Redis(

210

host='redis-ssl.example.com',

211

port=6380,

212

ssl=True,

213

ssl_ca_certs='/path/to/ca-certificates.crt',

214

ssl_certfile='/path/to/client.crt',

215

ssl_keyfile='/path/to/client.key'

216

)

217

```

218

219

### Unix Domain Socket Connection

220

221

```python

222

from redis import Redis, UnixDomainSocketConnection

223

224

# Unix socket connection

225

r = Redis(

226

unix_domain_socket_path='/var/run/redis/redis.sock',

227

db=0

228

)

229

230

# With connection pool

231

unix_pool = ConnectionPool(

232

connection_class=UnixDomainSocketConnection,

233

path='/var/run/redis/redis.sock',

234

db=0

235

)

236

237

r = Redis(connection_pool=unix_pool)

238

```

239

240

### Blocking Connection Pool

241

242

```python

243

from redis import Redis, BlockingConnectionPool

244

245

# Blocking pool with connection limit

246

blocking_pool = BlockingConnectionPool(

247

host='localhost',

248

port=6379,

249

max_connections=10,

250

timeout=20, # Wait up to 20 seconds for available connection

251

db=0

252

)

253

254

r = Redis(connection_pool=blocking_pool)

255

256

# This will block if all connections are in use

257

try:

258

r.set('key', 'value')

259

except redis.ConnectionError as e:

260

print(f"Could not get connection: {e}")

261

```

262

263

### Connection Pool from URL

264

265

```python

266

from redis import ConnectionPool

267

268

# Create pool from URL

269

pool = ConnectionPool.from_url('redis://localhost:6379/0')

270

271

# SSL from URL

272

ssl_pool = ConnectionPool.from_url(

273

'rediss://username:password@redis.example.com:6380/0'

274

)

275

276

# Unix socket from URL

277

unix_pool = ConnectionPool.from_url('unix:///var/run/redis/redis.sock?db=0')

278

```

279

280

### Connection Health Monitoring

281

282

```python

283

# Enable connection health checks

284

pool = ConnectionPool(

285

host='localhost',

286

port=6379,

287

health_check_interval=30, # Check every 30 seconds

288

max_connections=20

289

)

290

291

r = Redis(connection_pool=pool)

292

293

# Manual connection health check

294

connection = pool.get_connection('ping')

295

try:

296

connection.send_command('PING')

297

response = connection.read_response()

298

print(f"Connection healthy: {response}")

299

finally:

300

pool.release(connection)

301

```

302

303

### Advanced Connection Configuration

304

305

```python

306

# Custom connection with keepalive

307

pool = ConnectionPool(

308

host='localhost',

309

port=6379,

310

socket_keepalive=True,

311

socket_keepalive_options={

312

1: 1, # TCP_KEEPIDLE

313

2: 3, # TCP_KEEPINTVL

314

3: 5 # TCP_KEEPCNT

315

},

316

socket_timeout=5.0,

317

socket_connect_timeout=10.0,

318

retry_on_timeout=True,

319

retry_on_error=[redis.ConnectionError, redis.TimeoutError]

320

)

321

322

r = Redis(connection_pool=pool)

323

```

324

325

### Connection Pool Management

326

327

```python

328

import redis

329

330

# Create pool with monitoring

331

pool = redis.ConnectionPool(

332

host='localhost',

333

port=6379,

334

max_connections=50

335

)

336

337

r = redis.Redis(connection_pool=pool)

338

339

# Check pool status

340

print(f"Created connections: {pool.created_connections}")

341

print(f"Available connections: {len(pool._available_connections)}")

342

print(f"In-use connections: {len(pool._in_use_connections)}")

343

344

# Reset all connections (closes existing connections)

345

pool.reset()

346

347

# Disconnect all connections

348

pool.disconnect()

349

```

350

351

### Error Handling

352

353

```python

354

from redis.exceptions import ConnectionError, TimeoutError

355

356

try:

357

r = Redis(

358

host='unreachable-host',

359

port=6379,

360

socket_connect_timeout=5,

361

retry_on_timeout=True

362

)

363

r.ping()

364

except ConnectionError as e:

365

print(f"Connection failed: {e}")

366

except TimeoutError as e:

367

print(f"Connection timed out: {e}")

368

```