0
# Client Connection Management
1
2
Core ZooKeeper client wrapper providing robust connection management, retry integration, and session handling for reliable distributed coordination in Apache Curator.
3
4
## Capabilities
5
6
### CuratorZookeeperClient
7
8
Main client class that wraps ZooKeeper client functionality with enhanced connection management, retry integration, and session monitoring.
9
10
```java { .api }
11
/**
12
* Main ZooKeeper client wrapper providing connection management and retry functionality
13
*/
14
public class CuratorZookeeperClient implements Closeable {
15
/**
16
* Create client with connection string and retry policy
17
* @param connectString ZooKeeper connection string (host:port)
18
* @param sessionTimeoutMs Session timeout in milliseconds
19
* @param connectionTimeoutMs Connection timeout in milliseconds
20
* @param watcher Optional watcher for connection events
21
* @param retryPolicy Retry policy for failed operations
22
*/
23
public CuratorZookeeperClient(String connectString, int sessionTimeoutMs,
24
int connectionTimeoutMs, Watcher watcher,
25
RetryPolicy retryPolicy);
26
27
/**
28
* Create client with ensemble provider for dynamic connection strings
29
* @param ensembleProvider Provider for ZooKeeper connection strings
30
* @param sessionTimeoutMs Session timeout in milliseconds
31
* @param connectionTimeoutMs Connection timeout in milliseconds
32
* @param watcher Optional watcher for connection events
33
* @param retryPolicy Retry policy for failed operations
34
*/
35
public CuratorZookeeperClient(EnsembleProvider ensembleProvider, int sessionTimeoutMs,
36
int connectionTimeoutMs, Watcher watcher,
37
RetryPolicy retryPolicy);
38
39
/**
40
* Create client with custom ZooKeeper factory and read-only support
41
* @param zookeeperFactory Factory for creating ZooKeeper instances
42
* @param ensembleProvider Provider for ZooKeeper connection strings
43
* @param sessionTimeoutMs Session timeout in milliseconds
44
* @param connectionTimeoutMs Connection timeout in milliseconds
45
* @param watcher Optional watcher for connection events
46
* @param retryPolicy Retry policy for failed operations
47
* @param canBeReadOnly Whether client can connect in read-only mode
48
*/
49
public CuratorZookeeperClient(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider,
50
int sessionTimeoutMs, int connectionTimeoutMs, Watcher watcher,
51
RetryPolicy retryPolicy, boolean canBeReadOnly);
52
53
/**
54
* Create client with custom connection handling policy
55
* @param zookeeperFactory Factory for creating ZooKeeper instances
56
* @param ensembleProvider Provider for ZooKeeper connection strings
57
* @param sessionTimeoutMs Session timeout in milliseconds
58
* @param connectionTimeoutMs Connection timeout in milliseconds
59
* @param watcher Optional watcher for connection events
60
* @param retryPolicy Retry policy for failed operations
61
* @param canBeReadOnly Whether client can connect in read-only mode
62
* @param connectionHandlingPolicy Policy for connection handling behavior
63
*/
64
public CuratorZookeeperClient(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider,
65
int sessionTimeoutMs, int connectionTimeoutMs, Watcher watcher,
66
RetryPolicy retryPolicy, boolean canBeReadOnly,
67
ConnectionHandlingPolicy connectionHandlingPolicy);
68
69
/**
70
* Create client with all configuration parameters
71
* @param zookeeperFactory Factory for creating ZooKeeper instances
72
* @param ensembleProvider Provider for ZooKeeper connection strings
73
* @param sessionTimeoutMs Session timeout in milliseconds
74
* @param connectionTimeoutMs Connection timeout in milliseconds
75
* @param waitForShutdownTimeoutMs Timeout for shutdown operations
76
* @param watcher Optional watcher for connection events
77
* @param retryPolicy Retry policy for failed operations
78
* @param canBeReadOnly Whether client can connect in read-only mode
79
* @param connectionHandlingPolicy Policy for connection handling behavior
80
*/
81
public CuratorZookeeperClient(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider,
82
int sessionTimeoutMs, int connectionTimeoutMs, int waitForShutdownTimeoutMs,
83
Watcher watcher, RetryPolicy retryPolicy, boolean canBeReadOnly,
84
ConnectionHandlingPolicy connectionHandlingPolicy);
85
86
/**
87
* Start the client connection to ZooKeeper
88
* @throws Exception if connection cannot be established
89
*/
90
public void start() throws Exception;
91
92
/**
93
* Close the client and release resources
94
* @throws IOException if close operation fails
95
*/
96
public void close() throws IOException;
97
98
/**
99
* Close the client with custom shutdown timeout
100
* @param waitForShutdownTimeoutMs Timeout for shutdown operations in milliseconds
101
*/
102
public void close(int waitForShutdownTimeoutMs);
103
104
/**
105
* Check if client is currently connected to ZooKeeper
106
* @return true if connected, false otherwise
107
*/
108
public boolean isConnected();
109
110
/**
111
* Block current thread until connected or timeout occurs
112
* @return true if connected, false if timed out
113
* @throws InterruptedException if interrupted while waiting
114
*/
115
public boolean blockUntilConnectedOrTimedOut() throws InterruptedException;
116
117
/**
118
* Get the underlying ZooKeeper client instance
119
* @return ZooKeeper client for direct operations
120
* @throws Exception if client is not available
121
*/
122
public ZooKeeper getZooKeeper() throws Exception;
123
124
/**
125
* Create a new retry loop for ZooKeeper operations
126
* @return RetryLoop instance for operation retry handling
127
*/
128
public RetryLoop newRetryLoop();
129
130
/**
131
* Create a session fail retry loop for session failure scenarios
132
* @param mode Retry mode (RETRY or FAIL)
133
* @return SessionFailRetryLoop instance
134
*/
135
public SessionFailRetryLoop newSessionFailRetryLoop(SessionFailRetryLoop.Mode mode);
136
}
137
```
138
139
**Usage Examples:**
140
141
```java
142
import org.apache.curator.CuratorZookeeperClient;
143
import org.apache.curator.RetryPolicy;
144
import org.apache.curator.retry.ExponentialBackoffRetry;
145
146
// Basic client setup
147
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
148
CuratorZookeeperClient client = new CuratorZookeeperClient(
149
"localhost:2181,localhost:2182,localhost:2183",
150
5000, // session timeout
151
5000, // connection timeout
152
null, // watcher
153
retryPolicy
154
);
155
156
// Start and use client
157
try {
158
client.start();
159
160
// Wait for connection
161
if (client.blockUntilConnectedOrTimedOut()) {
162
System.out.println("Connected to ZooKeeper");
163
164
// Access ZooKeeper instance for operations
165
ZooKeeper zk = client.getZooKeeper();
166
// ... perform operations ...
167
}
168
} finally {
169
client.close();
170
}
171
```
172
173
### Retry Loop Framework
174
175
Framework for performing ZooKeeper operations with automatic retry handling based on configured retry policies.
176
177
```java { .api }
178
/**
179
* Abstract base class for retry loop implementations
180
*/
181
public abstract class RetryLoop {
182
/**
183
* Execute a callable with retry logic
184
* @param client CuratorZookeeperClient instance
185
* @param proc Callable to execute with retry
186
* @return Result of successful callable execution
187
* @throws Exception if all retries are exhausted
188
*/
189
public static <T> T callWithRetry(CuratorZookeeperClient client, Callable<T> proc) throws Exception;
190
191
/**
192
* Check if ZooKeeper return code indicates retry should be attempted
193
* @param rc ZooKeeper operation return code
194
* @return true if operation should be retried
195
*/
196
public static boolean shouldRetry(int rc);
197
198
/**
199
* Check if exception indicates operation should be retried
200
* @param exception Exception from ZooKeeper operation
201
* @return true if operation should be retried for this exception
202
*/
203
public static boolean isRetryException(Throwable exception);
204
205
/**
206
* Get default retry sleeper implementation
207
* @return Default RetrySleeper instance
208
*/
209
public static RetrySleeper getDefaultRetrySleeper();
210
}
211
```
212
213
**Usage Examples:**
214
215
```java
216
import org.apache.curator.RetryLoop;
217
218
// Using static retry method
219
String result = RetryLoop.callWithRetry(client, () -> {
220
// ZooKeeper operation that may fail
221
return client.getZooKeeper().getData("/some/path", false, null);
222
});
223
224
// Manual retry loop
225
RetryLoop retryLoop = client.newRetryLoop();
226
while (retryLoop.shouldContinue()) {
227
try {
228
// ZooKeeper operations
229
client.getZooKeeper().create("/test", "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
230
retryLoop.markComplete();
231
} catch (Exception e) {
232
retryLoop.takeException(e);
233
}
234
}
235
```
236
237
### Session Failure Handling
238
239
Specialized retry loop for handling ZooKeeper session failures with configurable behavior modes.
240
241
```java { .api }
242
/**
243
* Retry loop specialized for handling session failures
244
*/
245
public class SessionFailRetryLoop {
246
/**
247
* Mode enumeration for session failure handling
248
*/
249
public enum Mode {
250
/** Retry operations after session failure */
251
RETRY,
252
/** Fail immediately on session failure */
253
FAIL
254
}
255
256
/**
257
* Exception thrown when session failure occurs in FAIL mode
258
*/
259
public static class SessionFailedException extends Exception {
260
// Exception for session failure scenarios
261
}
262
263
/**
264
* Execute callable with session failure retry logic
265
* @param client CuratorZookeeperClient instance
266
* @param mode Session failure handling mode
267
* @param proc Callable to execute
268
* @return Result of successful execution
269
* @throws Exception if operation fails or session fails in FAIL mode
270
*/
271
public static <T> T callWithRetry(CuratorZookeeperClient client, Mode mode, Callable<T> proc) throws Exception;
272
}
273
```
274
275
**Usage Examples:**
276
277
```java
278
import org.apache.curator.SessionFailRetryLoop;
279
280
// Retry on session failure
281
String data = SessionFailRetryLoop.callWithRetry(client, SessionFailRetryLoop.Mode.RETRY, () -> {
282
return new String(client.getZooKeeper().getData("/important/data", false, null));
283
});
284
285
// Fail immediately on session failure
286
try {
287
SessionFailRetryLoop.callWithRetry(client, SessionFailRetryLoop.Mode.FAIL, () -> {
288
client.getZooKeeper().setData("/critical/path", newData, -1);
289
return null;
290
});
291
} catch (SessionFailRetryLoop.SessionFailedException e) {
292
// Handle session failure
293
System.err.println("Session failed, cannot continue");
294
}
295
```
296
297
### Connection State Monitoring
298
299
Enumeration for tracking ZooKeeper connection states and handling connection lifecycle events.
300
301
```java { .api }
302
/**
303
* Enumeration of possible ZooKeeper connection states
304
*/
305
public enum ConnectionState {
306
/** Successfully connected to ZooKeeper */
307
CONNECTED,
308
/** Connection temporarily suspended */
309
SUSPENDED,
310
/** Reconnected after suspension */
311
RECONNECTED,
312
/** Connection permanently lost */
313
LOST,
314
/** Connected in read-only mode */
315
READ_ONLY
316
}
317
```