Class Cluster.Builder
- java.lang.Object
-
- com.datastax.driver.core.Cluster.Builder
-
- All Implemented Interfaces:
Cluster.Initializer
- Enclosing class:
- Cluster
public static class Cluster.Builder extends Object implements Cluster.Initializer
Helper class to buildClusterinstances.
-
-
Constructor Summary
Constructors Constructor Description Builder()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description Cluster.BuilderaddContactPoint(EndPoint contactPoint)Adds a contact point using the given connection information.Cluster.BuilderaddContactPoint(String address)Adds a contact point - or many if the given address resolves to multipleInetAddresss (A records).Cluster.BuilderaddContactPoints(String... addresses)Adds contact points.Cluster.BuilderaddContactPoints(InetAddress... addresses)Adds contact points.Cluster.BuilderaddContactPoints(Collection<InetAddress> addresses)Adds contact points.Cluster.BuilderaddContactPointsWithPorts(InetSocketAddress... addresses)Adds contact points.Cluster.BuilderaddContactPointsWithPorts(Collection<InetSocketAddress> addresses)Adds contact points.Cluster.BuilderallowBetaProtocolVersion()Create cluster connection using latest development protocol version, which is currently in beta.Clusterbuild()Builds the cluster with the configured set of initial contact points and policies.StringgetClusterName()An optional name for the created cluster.ConfigurationgetConfiguration()The configuration that will be used for the new cluster.List<EndPoint>getContactPoints()Returns the initial Cassandra hosts to connect to.Collection<Host.StateListener>getInitialListeners()Optional listeners to register against the newly created cluster.Cluster.BuilderwithAddressTranslator(AddressTranslator translator)Configures the address translator to use for the new cluster.Cluster.BuilderwithApplicationInfo(ApplicationInfo applicationInfo)Sets application information provider, every connection on startup sends this information to the server.Cluster.BuilderwithAuthProvider(AuthProvider authProvider)Use the specified AuthProvider when connecting to Cassandra hosts.Cluster.BuilderwithClusterName(String name)An optional name for the create cluster.Cluster.BuilderwithCodecRegistry(CodecRegistry codecRegistry)Configures theCodecRegistryinstance to use for the new cluster.Cluster.BuilderwithCompression(ProtocolOptions.Compression compression)Sets the compression to use for the transport.Cluster.BuilderwithCredentials(String username, String password)Uses the provided credentials when connecting to Cassandra hosts.Cluster.BuilderwithDriverConfigReporting(boolean enabled)Enables or disables driver configuration reporting, i.e. whether the control connection sends aDRIVER_CONFIGJSON blob describing the effective driver configuration in its startup options.Cluster.BuilderwithEndPointFactory(EndPointFactory endPointFactory)Configures the endpoint factory to use for the new cluster.Cluster.BuilderwithInitialListeners(Collection<Host.StateListener> listeners)Register the provided listeners in the newly created cluster.Cluster.BuilderwithLoadBalancingPolicy(LoadBalancingPolicy policy)Configures the load balancing policy to use for the new cluster.Cluster.BuilderwithLocalPortRange(int low, int high)Sets local port range for use by advanced shard awareness.Cluster.BuilderwithMaxSchemaAgreementWaitSeconds(int maxSchemaAgreementWaitSeconds)Sets the maximum time to wait for schema agreement before returning from a DDL query.Cluster.BuilderwithNettyOptions(NettyOptions nettyOptions)Set theNettyOptionsto use for the newly created Cluster.Cluster.BuilderwithNoCompact()Enables theNO_COMPACTstartup option.Cluster.BuilderwithoutAdvancedShardAwareness()Disables advanced shard awareness.Cluster.BuilderwithoutJMXReporting()Disables JMX reporting of the metrics.Cluster.BuilderwithoutMetrics()Disables metrics collection for the created cluster (metrics are enabled by default otherwise).Cluster.BuilderwithoutPagingInSchemaQueries()Disables paging in schema queries.Cluster.BuilderwithPoolingOptions(PoolingOptions options)Sets the PoolingOptions to use for the newly created Cluster.Cluster.BuilderwithPort(int port)The port to use to connect to the Cassandra host.Cluster.BuilderwithProtocolVersion(ProtocolVersion version)The native protocol version to use.Cluster.BuilderwithQueryOptions(QueryOptions options)Sets the QueryOptions to use for the newly created Cluster.Cluster.BuilderwithReconnectionPolicy(ReconnectionPolicy policy)Configures the reconnection policy to use for the new cluster.Cluster.BuilderwithRetryPolicy(RetryPolicy policy)Configures the retry policy to use for the new cluster.Cluster.BuilderwithSocketOptions(SocketOptions options)Sets the SocketOptions to use for the newly created Cluster.Cluster.BuilderwithSpeculativeExecutionPolicy(SpeculativeExecutionPolicy policy)Configures the speculative execution policy to use for the new cluster.Cluster.BuilderwithSSL()Enables the use of SSL for the createdCluster.Cluster.BuilderwithSSL(SSLOptions sslOptions)Enable the use of SSL for the createdClusterusing the provided options.Cluster.BuilderwithThreadingOptions(ThreadingOptions options)Sets the threading options to use for the newly created Cluster.Cluster.BuilderwithTimestampGenerator(TimestampGenerator timestampGenerator)Configures the generator that will produce the client-side timestamp sent with each query.
-
-
-
Method Detail
-
getClusterName
public String getClusterName()
Description copied from interface:Cluster.InitializerAn optional name for the created cluster.Such name is optional (a default name will be created otherwise) and is currently only use for JMX reporting of metrics. See
Cluster.getClusterName()for more information.- Specified by:
getClusterNamein interfaceCluster.Initializer- Returns:
- the name for the created cluster or
nullto use an automatically generated name.
-
getContactPoints
public List<EndPoint> getContactPoints()
Description copied from interface:Cluster.InitializerReturns the initial Cassandra hosts to connect to.- Specified by:
getContactPointsin interfaceCluster.Initializer- Returns:
- the initial Cassandra contact points. See
addContactPoint(java.lang.String)for more details on contact points.
-
withClusterName
public Cluster.Builder withClusterName(String name)
An optional name for the create cluster.Note: this is not related to the Cassandra cluster name (though you are free to provide the same name). See
Cluster.getClusterName()for details.If you use this method and create more than one Cluster instance in the same JVM (which should be avoided unless you need to connect to multiple Cassandra clusters), you should make sure each Cluster instance get a unique name or you may have a problem with JMX reporting.
- Parameters:
name- the cluster name to use for the created Cluster instance.- Returns:
- this Builder.
-
withPort
public Cluster.Builder withPort(int port)
The port to use to connect to the Cassandra host.If not set through this method, the default port (9042) will be used instead.
- Parameters:
port- the port to set.- Returns:
- this Builder.
-
allowBetaProtocolVersion
public Cluster.Builder allowBetaProtocolVersion()
Create cluster connection using latest development protocol version, which is currently in beta. Calling this method will result into setting USE_BETA flag in all outgoing messages, which allows server to negotiate the supported protocol version even if it is currently in beta.This feature is only available starting with version
V5.Use with caution, refer to the server and protocol documentation for the details on latest protocol version.
- Returns:
- this Builder.
-
withMaxSchemaAgreementWaitSeconds
public Cluster.Builder withMaxSchemaAgreementWaitSeconds(int maxSchemaAgreementWaitSeconds)
Sets the maximum time to wait for schema agreement before returning from a DDL query.If not set through this method, the default value (10 seconds) will be used.
- Parameters:
maxSchemaAgreementWaitSeconds- the new value to set.- Returns:
- this Builder.
- Throws:
IllegalStateException- if the provided value is zero or less.
-
withProtocolVersion
public Cluster.Builder withProtocolVersion(ProtocolVersion version)
The native protocol version to use.The driver supports versions 1 to 5 of the native protocol. Higher versions of the protocol have more features and should be preferred, but this also depends on the Cassandra version:
Native protocol version to Cassandra version correspondence Protocol version Minimum Cassandra version 1 1.2 2 2.0 3 2.1 4 2.2 5 3.10 By default, the driver will "auto-detect" which protocol version it can use when connecting to the first node. More precisely, it will try first with
ProtocolVersion.DEFAULT, and if not supported fallback to the highest version supported by the first node it connects to. Please note that once the version is "auto-detected", it won't change: if the first node the driver connects to is a Cassandra 1.2 node and auto-detection is used (the default), then the native protocol version 1 will be use for the lifetime of the Cluster instance.By using
allowBetaProtocolVersion(), it is possible to force driver to connect to Cassandra node that supports the latest protocol beta version. Leaving this flag out will let client to connect with latest released version.This method allows to force the use of a particular protocol version. Forcing version 1 is always fine since all Cassandra version (at least all those supporting the native protocol in the first place) so far support it. However, please note that a number of features of the driver won't be available if that version of the protocol is in use, including result set paging,
BatchStatement, executing a non-prepared query with binary values (Session.execute(String, Object...)), ... (those methods will throw an UnsupportedFeatureException). Using the protocol version 1 should thus only be considered when using Cassandra 1.2, until nodes have been upgraded to Cassandra 2.0.If version 2 of the protocol is used, then Cassandra 1.2 nodes will be ignored (the driver won't connect to them).
The default behavior (auto-detection) is fine in almost all case, but you may want to force a particular version if you have a Cassandra cluster with mixed 1.2/2.0 nodes (i.e. during a Cassandra upgrade).
- Parameters:
version- the native protocol version to use.nullis also supported to trigger auto-detection (see above) but this is the default (so you don't have to call this method for that behavior).- Returns:
- this Builder.
-
addContactPoint
public Cluster.Builder addContactPoint(String address)
Adds a contact point - or many if the given address resolves to multipleInetAddresss (A records).Contact points are addresses of Cassandra nodes that the driver uses to discover the cluster topology. Only one contact point is required (the driver will retrieve the address of the other nodes automatically), but it is usually a good idea to provide more than one contact point, because if that single contact point is unavailable, the driver cannot initialize itself correctly.
Note that by default (that is, unless you use the
withLoadBalancingPolicy(com.datastax.driver.core.policies.LoadBalancingPolicy)) method of this builder), the first successfully contacted host will be used to define the local data-center for the client. If follows that if you are running Cassandra in a multiple data-center setting, it is a good idea to only provide contact points that are in the same datacenter than the client, or to provide manually the load balancing policy that suits your need.If the host name points to a DNS record with multiple a-records, all InetAddresses returned will be used. Make sure that all resulting
InetAddresss returned point to the same cluster and datacenter.- Parameters:
address- the address of the node(s) to connect to.- Returns:
- this Builder.
- Throws:
IllegalArgumentException- if the givenaddresscould not be resolved.SecurityException- if a security manager is present and permission to resolve the host name is denied.
-
addContactPoint
public Cluster.Builder addContactPoint(EndPoint contactPoint)
Adds a contact point using the given connection information.You only need this method if you use a custom connection mechanism and have configured a custom
EndPointFactory; otherwise, you can safely ignore it and use the higher level, host-and-port-based variants such asaddContactPoint(String).
-
addContactPoints
public Cluster.Builder addContactPoints(String... addresses)
Adds contact points.See
addContactPoint(java.lang.String)for more details on contact points.Note that all contact points must be resolvable; if any of them cannot be resolved, this method will fail.
- Parameters:
addresses- addresses of the nodes to add as contact points.- Returns:
- this Builder.
- Throws:
IllegalArgumentException- if any of the givenaddressescould not be resolved.SecurityException- if a security manager is present and permission to resolve the host name is denied.- See Also:
addContactPoint(java.lang.String)
-
addContactPoints
public Cluster.Builder addContactPoints(InetAddress... addresses)
Adds contact points.See
addContactPoint(java.lang.String)for more details on contact points.Note that all contact points must be resolvable; if any of them cannot be resolved, this method will fail.
- Parameters:
addresses- addresses of the nodes to add as contact points.- Returns:
- this Builder.
- Throws:
IllegalArgumentException- if any of the givenaddressescould not be resolved.SecurityException- if a security manager is present and permission to resolve the host name is denied.- See Also:
addContactPoint(java.lang.String)
-
addContactPoints
public Cluster.Builder addContactPoints(Collection<InetAddress> addresses)
Adds contact points.See
addContactPoint(java.lang.String)for more details on contact points.- Parameters:
addresses- addresses of the nodes to add as contact points.- Returns:
- this Builder
- See Also:
addContactPoint(java.lang.String)
-
addContactPointsWithPorts
public Cluster.Builder addContactPointsWithPorts(InetSocketAddress... addresses)
Adds contact points.See
addContactPoint(java.lang.String)for more details on contact points. Contrarily to otheraddContactPointsmethods, this method allows to provide a different port for each contact point. Since Cassandra nodes must always all listen on the same port, this is rarely what you want and most users should prefer otheraddContactPointsmethods to this one. However, this can be useful if the Cassandra nodes are behind a router and are not accessed directly. Note that if you are in this situation (Cassandra nodes are behind a router, not directly accessible), you almost surely want to provide a specificAddressTranslator(throughwithAddressTranslator(com.datastax.driver.core.policies.AddressTranslator)) to translate actual Cassandra node addresses to the addresses the driver should use, otherwise the driver will not be able to auto-detect new nodes (and will generally not function optimally).- Parameters:
addresses- addresses of the nodes to add as contact points.- Returns:
- this Builder
- See Also:
addContactPoint(java.lang.String)
-
addContactPointsWithPorts
public Cluster.Builder addContactPointsWithPorts(Collection<InetSocketAddress> addresses)
Adds contact points.See
addContactPoint(java.lang.String)for more details on contact points. Contrarily to otheraddContactPointsmethods, this method allows to provide a different port for each contact point. Since Cassandra nodes must always all listen on the same port, this is rarely what you want and most users should prefer otheraddContactPointsmethods to this one. However, this can be useful if the Cassandra nodes are behind a router and are not accessed directly. Note that if you are in this situation (Cassandra nodes are behind a router, not directly accessible), you almost surely want to provide a specificAddressTranslator(throughwithAddressTranslator(com.datastax.driver.core.policies.AddressTranslator)) to translate actual Cassandra node addresses to the addresses the driver should use, otherwise the driver will not be able to auto-detect new nodes (and will generally not function optimally).- Parameters:
addresses- addresses of the nodes to add as contact points.- Returns:
- this Builder
- See Also:
addContactPoint(java.lang.String)
-
withLoadBalancingPolicy
public Cluster.Builder withLoadBalancingPolicy(LoadBalancingPolicy policy)
Configures the load balancing policy to use for the new cluster.If no load balancing policy is set through this method,
Policies.defaultLoadBalancingPolicy()will be used instead.- Parameters:
policy- the load balancing policy to use.- Returns:
- this Builder.
-
withReconnectionPolicy
public Cluster.Builder withReconnectionPolicy(ReconnectionPolicy policy)
Configures the reconnection policy to use for the new cluster.If no reconnection policy is set through this method,
Policies.DEFAULT_RECONNECTION_POLICYwill be used instead.- Parameters:
policy- the reconnection policy to use.- Returns:
- this Builder.
-
withRetryPolicy
public Cluster.Builder withRetryPolicy(RetryPolicy policy)
Configures the retry policy to use for the new cluster.If no retry policy is set through this method,
Policies.DEFAULT_RETRY_POLICYwill be used instead.- Parameters:
policy- the retry policy to use.- Returns:
- this Builder.
-
withAddressTranslator
public Cluster.Builder withAddressTranslator(AddressTranslator translator)
Configures the address translator to use for the new cluster.See
AddressTranslatorfor more detail on address translation, but the default translator,IdentityTranslator, should be correct in most cases. If unsure, stick to the default.- Parameters:
translator- the translator to use.- Returns:
- this Builder.
-
withTimestampGenerator
public Cluster.Builder withTimestampGenerator(TimestampGenerator timestampGenerator)
Configures the generator that will produce the client-side timestamp sent with each query.This feature is only available with version
V3or above of the native protocol. With earlier versions, timestamps are always generated server-side, and setting a generator through this method will have no effect.If no generator is set through this method, the driver will default to client-side timestamps by using
AtomicMonotonicTimestampGenerator.- Parameters:
timestampGenerator- the generator to use.- Returns:
- this Builder.
-
withSpeculativeExecutionPolicy
public Cluster.Builder withSpeculativeExecutionPolicy(SpeculativeExecutionPolicy policy)
Configures the speculative execution policy to use for the new cluster.If no policy is set through this method,
Policies.defaultSpeculativeExecutionPolicy()will be used instead.- Parameters:
policy- the policy to use.- Returns:
- this Builder.
-
withEndPointFactory
public Cluster.Builder withEndPointFactory(EndPointFactory endPointFactory)
Configures the endpoint factory to use for the new cluster.This is a low-level component for advanced scenarios where connecting to a node requires more than its socket address. If you're simply using host+port, the default factory is sufficient.
-
withCodecRegistry
public Cluster.Builder withCodecRegistry(CodecRegistry codecRegistry)
Configures theCodecRegistryinstance to use for the new cluster.If no codec registry is set through this method,
CodecRegistry.DEFAULT_INSTANCEwill be used instead.Note that if two or more
Clusterinstances are configured to use the default codec registry, they are going to share the same instance. In this case, care should be taken when registering new codecs on it as any codec registered by one cluster would be immediately available to others sharing the same default instance.- Parameters:
codecRegistry- the codec registry to use.- Returns:
- this Builder.
-
withCredentials
public Cluster.Builder withCredentials(String username, String password)
Uses the provided credentials when connecting to Cassandra hosts.This should be used if the Cassandra cluster has been configured to use the
PasswordAuthenticator. If the the defaultAllowAllAuthenticatoris used instead, using this method has no effect.- Parameters:
username- the username to use to login to Cassandra hosts.password- the password corresponding tousername.- Returns:
- this Builder.
-
withAuthProvider
public Cluster.Builder withAuthProvider(AuthProvider authProvider)
Use the specified AuthProvider when connecting to Cassandra hosts.Use this method when a custom authentication scheme is in place. You shouldn't call both this method and
withCredentialson the sameBuilderinstance as one will supersede the other- Parameters:
authProvider- theAuthProviderto use to login to Cassandra hosts.- Returns:
- this Builder
-
withCompression
public Cluster.Builder withCompression(ProtocolOptions.Compression compression)
Sets the compression to use for the transport.- Parameters:
compression- the compression to set.- Returns:
- this Builder.
- See Also:
ProtocolOptions.Compression
-
withoutMetrics
public Cluster.Builder withoutMetrics()
Disables metrics collection for the created cluster (metrics are enabled by default otherwise).- Returns:
- this builder.
-
withSSL
public Cluster.Builder withSSL()
Enables the use of SSL for the createdCluster.Calling this method will use the JDK-based implementation with the default options (see
RemoteEndpointAwareJdkSSLOptions.Builder). This is thus a shortcut forwithSSL(JdkSSLOptions.builder().build()).Note that if SSL is enabled, the driver will not connect to any Cassandra nodes that doesn't have SSL enabled and it is strongly advised to enable SSL on every Cassandra node if you plan on using SSL in the driver.
- Returns:
- this builder.
-
withSSL
public Cluster.Builder withSSL(SSLOptions sslOptions)
Enable the use of SSL for the createdClusterusing the provided options.- Parameters:
sslOptions- the SSL options to use.- Returns:
- this builder.
-
withInitialListeners
public Cluster.Builder withInitialListeners(Collection<Host.StateListener> listeners)
Register the provided listeners in the newly created cluster.Note: repeated calls to this method will override the previous ones.
- Parameters:
listeners- the listeners to register.- Returns:
- this builder.
-
withoutJMXReporting
public Cluster.Builder withoutJMXReporting()
Disables JMX reporting of the metrics.JMX reporting is enabled by default (see
Metrics) but can be disabled using this option. If metrics are disabled, this is a no-op.- Returns:
- this builder.
-
withPoolingOptions
public Cluster.Builder withPoolingOptions(PoolingOptions options)
Sets the PoolingOptions to use for the newly created Cluster.If no pooling options are set through this method, default pooling options will be used.
- Parameters:
options- the pooling options to use.- Returns:
- this builder.
-
withSocketOptions
public Cluster.Builder withSocketOptions(SocketOptions options)
Sets the SocketOptions to use for the newly created Cluster.If no socket options are set through this method, default socket options will be used.
- Parameters:
options- the socket options to use.- Returns:
- this builder.
-
withQueryOptions
public Cluster.Builder withQueryOptions(QueryOptions options)
Sets the QueryOptions to use for the newly created Cluster.If no query options are set through this method, default query options will be used.
- Parameters:
options- the query options to use.- Returns:
- this builder.
-
withThreadingOptions
public Cluster.Builder withThreadingOptions(ThreadingOptions options)
Sets the threading options to use for the newly created Cluster.If no options are set through this method, a new instance of
ThreadingOptionswill be used.- Parameters:
options- the options.- Returns:
- this builder.
-
withNettyOptions
public Cluster.Builder withNettyOptions(NettyOptions nettyOptions)
Set theNettyOptionsto use for the newly created Cluster.If no Netty options are set through this method,
NettyOptions.DEFAULT_INSTANCEwill be used as a default value, which means that no customization will be applied.- Parameters:
nettyOptions- theNettyOptionsto use.- Returns:
- this builder.
-
withNoCompact
public Cluster.Builder withNoCompact()
Enables theNO_COMPACTstartup option.When this option is supplied,
SELECT,UPDATE,DELETEandBATCHstatements onCOMPACT STORAGEtables function in "compatibility" mode which allows seeing these tables as if they were "regular" CQL tables.This option only effects interactions with tables using
COMPACT STORAGEand is only supported by C* 4.0+ and DSE 6.0+.- Returns:
- this builder.
- See Also:
- CASSANDRA-10857
-
withoutAdvancedShardAwareness
public Cluster.Builder withoutAdvancedShardAwareness()
Disables advanced shard awareness. By default, this driver chooses local port while making a connection to node, to signal which shard it wants to connect to. This allows driver to estabilish connection pool faster, especially when there are multiple clients connecting concurrently. If this causes any issues, you can disable it using this method. The most common issues are the NAT between client and node (which messes up client port numbers) and shard aware port (default: 19042) blocked by firewall.- Returns:
- this builder.
-
withoutPagingInSchemaQueries
public Cluster.Builder withoutPagingInSchemaQueries()
Disables paging in schema queries. By default, Queries that fetch schema from the cluster are paged. This option causes the least impact on the cluster latencies when a new client connects. Turning off paging may result in faster driver initialisation at the expense of higher cluster latencies.- Returns:
- this builder.
-
withLocalPortRange
public Cluster.Builder withLocalPortRange(int low, int high)
Sets local port range for use by advanced shard awareness. Driver will use ports from this range as local ports when connecting to cluster. IfwithoutAdvancedShardAwareness()was called, then setting this range does not affect anything.- Parameters:
low- Lower bound of range, inclusive.high- Upper bound of range, inclusive.- Returns:
- this builder.
-
withApplicationInfo
public Cluster.Builder withApplicationInfo(ApplicationInfo applicationInfo)
Sets application information provider, every connection on startup sends this information to the server.- Parameters:
applicationInfo- an application information provider.
-
withDriverConfigReporting
@Beta public Cluster.Builder withDriverConfigReporting(boolean enabled)
Enables or disables driver configuration reporting, i.e. whether the control connection sends aDRIVER_CONFIGJSON blob describing the effective driver configuration in its startup options. Enabled by default.The server stores it in
system.clients.client_options— a per-node table, so only the node holding the control connection storesDRIVER_CONFIG; consumers must query and aggregate across all nodes.This does not govern the
SESSION_IDstartup option, which every connection always sends (so the server can group every connection opened from thisCluster, across all of itsSessions), regardless of this setting.- Parameters:
enabled- whether driver configuration reporting is enabled.
-
getConfiguration
public Configuration getConfiguration()
The configuration that will be used for the new cluster.You should not modify this object directly because changes made to the returned object may not be used by the cluster build. Instead, you should use the other methods of this
Builder.- Specified by:
getConfigurationin interfaceCluster.Initializer- Returns:
- the configuration to use for the new cluster.
-
getInitialListeners
public Collection<Host.StateListener> getInitialListeners()
Description copied from interface:Cluster.InitializerOptional listeners to register against the newly created cluster.Note that contrary to listeners registered post Cluster creation, the listeners returned by this method will see
Host.StateListener.onAdd(com.datastax.driver.core.Host)events for the initial contact points.- Specified by:
getInitialListenersin interfaceCluster.Initializer- Returns:
- a possibly empty collection of
Host.StateListenerto register against the newly created cluster.
-
build
public Cluster build()
Builds the cluster with the configured set of initial contact points and policies.This is a convenience method for
Cluster.buildFrom(this).- Returns:
- the newly built Cluster instance.
-
-