0
# Connection Configuration
1
2
The `ClusterBuilder` abstract class provides a flexible configuration system for customizing Cassandra cluster connections. It supports authentication, SSL, load balancing, and all advanced connection parameters available in the DataStax Cassandra driver.
3
4
## Capabilities
5
6
### ClusterBuilder Base Class
7
8
Abstract configuration class that encapsulates Cassandra cluster connection setup.
9
10
```java { .api }
11
/**
12
* Abstract class for configuring Cassandra cluster connections
13
* Implementations define connection parameters through buildCluster method
14
*/
15
public abstract class ClusterBuilder implements Serializable {
16
/**
17
* Returns configured Cassandra cluster instance
18
* Creates new cluster using buildCluster implementation
19
* @return fully configured Cluster instance ready for use
20
*/
21
public Cluster getCluster();
22
23
/**
24
* Configures Cassandra cluster connection parameters
25
* Override this method to customize connection settings
26
* @param builder DataStax Cluster.Builder instance for configuration
27
* @return configured Cluster instance
28
*/
29
protected abstract Cluster buildCluster(Cluster.Builder builder);
30
}
31
```
32
33
## Configuration Examples
34
35
### Basic Connection
36
37
Simple connection to a single Cassandra node with default settings.
38
39
```java
40
ClusterBuilder basicBuilder = new ClusterBuilder() {
41
@Override
42
protected Cluster buildCluster(Cluster.Builder builder) {
43
return builder
44
.addContactPoint("localhost")
45
.withPort(9042)
46
.build();
47
}
48
};
49
```
50
51
### Multi-Node Cluster
52
53
Connection to multiple Cassandra nodes for high availability.
54
55
```java
56
ClusterBuilder clusterBuilder = new ClusterBuilder() {
57
@Override
58
protected Cluster buildCluster(Cluster.Builder builder) {
59
return builder
60
.addContactPoint("cassandra1.example.com")
61
.addContactPoint("cassandra2.example.com")
62
.addContactPoint("cassandra3.example.com")
63
.withPort(9042)
64
.build();
65
}
66
};
67
```
68
69
### Authentication Configuration
70
71
Connection with username/password authentication.
72
73
```java
74
ClusterBuilder authBuilder = new ClusterBuilder() {
75
@Override
76
protected Cluster buildCluster(Cluster.Builder builder) {
77
return builder
78
.addContactPoint("secure-cassandra.example.com")
79
.withPort(9042)
80
.withCredentials("cassandra_user", "secure_password")
81
.build();
82
}
83
};
84
```
85
86
### SSL/TLS Configuration
87
88
Secure connection using SSL encryption.
89
90
```java
91
import com.datastax.driver.core.JdkSSLOptions;
92
import javax.net.ssl.SSLContext;
93
94
ClusterBuilder sslBuilder = new ClusterBuilder() {
95
@Override
96
protected Cluster buildCluster(Cluster.Builder builder) {
97
try {
98
// Configure SSL context (implementation depends on your SSL setup)
99
SSLContext sslContext = SSLContext.getDefault();
100
JdkSSLOptions sslOptions = JdkSSLOptions.builder()
101
.withSSLContext(sslContext)
102
.build();
103
104
return builder
105
.addContactPoint("ssl-cassandra.example.com")
106
.withPort(9142) // typical SSL port
107
.withSSL(sslOptions)
108
.withCredentials("ssl_user", "ssl_password")
109
.build();
110
} catch (Exception e) {
111
throw new RuntimeException("Failed to configure SSL", e);
112
}
113
}
114
};
115
```
116
117
### Advanced Connection Configuration
118
119
Comprehensive configuration with connection pooling, timeouts, and retry policies.
120
121
```java
122
import com.datastax.driver.core.policies.*;
123
import com.datastax.driver.core.SocketOptions;
124
import com.datastax.driver.core.PoolingOptions;
125
126
ClusterBuilder advancedBuilder = new ClusterBuilder() {
127
@Override
128
protected Cluster buildCluster(Cluster.Builder builder) {
129
// Configure connection pooling
130
PoolingOptions poolingOptions = new PoolingOptions()
131
.setConnectionsPerHost(HostDistance.LOCAL, 2, 8)
132
.setConnectionsPerHost(HostDistance.REMOTE, 1, 4)
133
.setMaxRequestsPerConnection(HostDistance.LOCAL, 32768)
134
.setMaxRequestsPerConnection(HostDistance.REMOTE, 2000);
135
136
// Configure socket options (timeouts)
137
SocketOptions socketOptions = new SocketOptions()
138
.setConnectTimeoutMillis(5000)
139
.setReadTimeoutMillis(12000)
140
.setKeepAlive(true)
141
.setTcpNoDelay(true);
142
143
// Configure retry and reconnection policies
144
RetryPolicy retryPolicy = new ExponentialReconnectionPolicy(1000, 10000);
145
ReconnectionPolicy reconnectionPolicy = new ExponentialReconnectionPolicy(1000, 10000);
146
147
// Configure load balancing policy
148
LoadBalancingPolicy loadBalancingPolicy = DCAwareRoundRobinPolicy.builder()
149
.withLocalDc("datacenter1")
150
.build();
151
152
return builder
153
.addContactPoint("cassandra1.prod.example.com")
154
.addContactPoint("cassandra2.prod.example.com")
155
.addContactPoint("cassandra3.prod.example.com")
156
.withPort(9042)
157
.withCredentials("prod_user", "prod_password")
158
.withPoolingOptions(poolingOptions)
159
.withSocketOptions(socketOptions)
160
.withRetryPolicy(retryPolicy)
161
.withReconnectionPolicy(reconnectionPolicy)
162
.withLoadBalancingPolicy(loadBalancingPolicy)
163
.withCompression(ProtocolOptions.Compression.SNAPPY)
164
.build();
165
}
166
};
167
```
168
169
### Environment-Based Configuration
170
171
Configuration that adapts based on environment variables or properties.
172
173
```java
174
ClusterBuilder environmentBuilder = new ClusterBuilder() {
175
@Override
176
protected Cluster buildCluster(Cluster.Builder builder) {
177
// Read configuration from environment or properties
178
String cassandraHosts = System.getenv("CASSANDRA_HOSTS");
179
String cassandraPort = System.getenv("CASSANDRA_PORT");
180
String cassandraUser = System.getenv("CASSANDRA_USER");
181
String cassandraPassword = System.getenv("CASSANDRA_PASSWORD");
182
String cassandraKeyspace = System.getenv("CASSANDRA_KEYSPACE");
183
184
// Split multiple hosts
185
String[] hosts = cassandraHosts != null ? cassandraHosts.split(",") : new String[]{"localhost"};
186
int port = cassandraPort != null ? Integer.parseInt(cassandraPort) : 9042;
187
188
Cluster.Builder clusterBuilder = builder.withPort(port);
189
190
// Add all contact points
191
for (String host : hosts) {
192
clusterBuilder.addContactPoint(host.trim());
193
}
194
195
// Add authentication if provided
196
if (cassandraUser != null && cassandraPassword != null) {
197
clusterBuilder.withCredentials(cassandraUser, cassandraPassword);
198
}
199
200
return clusterBuilder.build();
201
}
202
};
203
```
204
205
### Keyspace-Specific Configuration
206
207
Configuration that automatically connects to a specific keyspace.
208
209
```java
210
ClusterBuilder keyspaceBuilder = new ClusterBuilder() {
211
private final String keyspace;
212
213
public KeyspaceClusterBuilder(String keyspace) {
214
this.keyspace = keyspace;
215
}
216
217
@Override
218
protected Cluster buildCluster(Cluster.Builder builder) {
219
Cluster cluster = builder
220
.addContactPoint("cassandra.example.com")
221
.withPort(9042)
222
.withCredentials("app_user", "app_password")
223
.build();
224
225
// Verify keyspace exists
226
Session session = cluster.connect();
227
try {
228
session.execute("USE " + keyspace);
229
} catch (Exception e) {
230
throw new RuntimeException("Keyspace '" + keyspace + "' not accessible", e);
231
} finally {
232
session.close();
233
}
234
235
return cluster;
236
}
237
};
238
239
// Usage
240
ClusterBuilder analyticsBuilder = new KeyspaceClusterBuilder("analytics");
241
```
242
243
## Configuration Best Practices
244
245
### Connection Pooling
246
247
Configure appropriate connection pool sizes based on your workload:
248
- **Local connections**: 2-8 connections per host for balanced throughput
249
- **Remote connections**: 1-4 connections per host to reduce network overhead
250
- **Max requests**: 32K for local, 2K for remote connections
251
252
### Timeout Configuration
253
254
Set appropriate timeouts for your network environment:
255
- **Connect timeout**: 5-10 seconds for initial connection establishment
256
- **Read timeout**: 10-30 seconds depending on query complexity
257
- **Keep-alive**: Enable to maintain long-lived connections
258
259
### Retry and Reconnection
260
261
Configure robust retry policies for production environments:
262
- **Exponential backoff**: Start with 1 second, max 10 seconds between retries
263
- **Retry policies**: Use `DefaultRetryPolicy` or custom policies for specific scenarios
264
- **Circuit breaker**: Consider implementing circuit breaker patterns for cascading failures
265
266
### Security Configuration
267
268
Follow security best practices:
269
- **Use authentication**: Always use credentials in production environments
270
- **Enable SSL/TLS**: Encrypt connections, especially over public networks
271
- **Certificate validation**: Properly validate SSL certificates in production
272
- **Principle of least privilege**: Create dedicated users with minimal required permissions
273
274
### Monitoring and Logging
275
276
Enable connection monitoring:
277
- **Connection metrics**: Monitor connection pool utilization
278
- **Query metrics**: Track query latency and error rates
279
- **Host metrics**: Monitor per-host connection status
280
- **Error logging**: Log connection failures and retry attempts
281
282
## Common Configuration Issues
283
284
### Connection Failures
285
- **DNS resolution**: Ensure contact point hostnames resolve correctly
286
- **Network connectivity**: Verify network routes and firewall rules
287
- **Port accessibility**: Confirm Cassandra ports are open and accessible
288
289
### Authentication Issues
290
- **User permissions**: Verify user has required permissions on target keyspace
291
- **Password expiration**: Check if passwords have expired
292
- **Authentication method**: Ensure authentication method matches cluster configuration
293
294
### Performance Issues
295
- **Pool exhaustion**: Monitor connection pool utilization and adjust sizes
296
- **Timeout issues**: Increase timeouts for complex queries or slow networks
297
- **Load balancing**: Ensure proper distribution across cluster nodes