Class Cluster
- java.lang.Object
-
- com.datastax.driver.core.Cluster
-
- All Implemented Interfaces:
Closeable,AutoCloseable
- Direct Known Subclasses:
DelegatingCluster
public class Cluster extends Object implements Closeable
Information and known state of a Cassandra cluster.This is the main entry point of the driver. A simple example of access to a Cassandra cluster would be:
Cluster cluster = Cluster.builder().addContactPoint("192.168.0.1").build(); Session session = cluster.connect("db1"); for (Row row : session.execute("SELECT * FROM table1")) // do something ...A cluster object maintains a permanent connection to one of the cluster nodes which it uses solely to maintain information on the state and current topology of the cluster. Using the connection, the driver will discover all the nodes currently in the cluster as well as new nodes joining the cluster subsequently.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classCluster.BuilderHelper class to buildClusterinstances.static interfaceCluster.InitializerInitializer forClusterinstances.
-
Constructor Summary
Constructors Modifier Constructor Description protectedCluster(Cluster.Initializer initializer)Constructs a new Cluster instance.protectedCluster(String name, List<EndPoint> contactPoints, Configuration configuration)Constructs a new Cluster instance.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description static Cluster.Builderbuilder()Creates a newCluster.Builderinstance.static ClusterbuildFrom(Cluster.Initializer initializer)Build a new cluster based on the provided initializer.voidclose()Initiates a shutdown of this cluster instance and blocks until that shutdown completes.CloseFuturecloseAsync()Initiates a shutdown of this cluster instance.Sessionconnect()Creates a new session on this cluster and initialize it.Sessionconnect(String keyspace)Creates a new session on this cluster, initialize it and sets the keyspace to the provided one.ListenableFuture<Session>connectAsync()Creates a new session on this cluster and initializes it asynchronously.ListenableFuture<Session>connectAsync(String keyspace)Creates a new session on this cluster, and initializes it to the given keyspace asynchronously.StringgetClusterName()The name of this cluster object.ConfigurationgetConfiguration()The cluster configuration.static StringgetDriverVersion()Returns the current version of the driver.MetadatagetMetadata()Returns read-only metadata on the connected cluster.MetricsgetMetrics()The cluster metrics.Clusterinit()Initialize this Cluster instance.booleanisClosed()Whether this Cluster instance has been closed.static voidlogDriverVersion()Logs the driver version to the console.SessionnewSession()Creates a new session on this cluster but does not initialize it.Clusterregister(Host.StateListener listener)Registers the provided listener to be notified on hosts up/down/added/removed events.Clusterregister(LatencyTracker tracker)Registers the provided tracker to be updated with hosts read latencies.Clusterregister(SchemaChangeListener listener)Registers the provided listener to be updated with schema change events.Clusterunregister(Host.StateListener listener)Unregisters the provided listener from being notified on hosts events.Clusterunregister(LatencyTracker tracker)Unregisters the provided latency tracking from being updated with host read latencies.Clusterunregister(SchemaChangeListener listener)Unregisters the provided schema change listener from being updated with schema change events.
-
-
-
Constructor Detail
-
Cluster
protected Cluster(String name, List<EndPoint> contactPoints, Configuration configuration)
Constructs a new Cluster instance.This constructor is mainly exposed so Cluster can be sub-classed as a means to make testing/mocking easier or to "intercept" its method call. Most users shouldn't extend this class however and should prefer either using the
builder()or callingbuildFrom(com.datastax.driver.core.Cluster.Initializer)with a custom Initializer.- Parameters:
name- the name to use for the cluster (this is not the Cassandra cluster name, seegetClusterName()).contactPoints- the list of contact points to use for the new cluster.configuration- the configuration for the new cluster.
-
Cluster
protected Cluster(Cluster.Initializer initializer)
Constructs a new Cluster instance.This constructor is mainly exposed so Cluster can be sub-classed as a means to make testing/mocking easier or to "intercept" its method call. Most users shouldn't extend this class however and should prefer using the
builder().- Parameters:
initializer- the initializer to use.- See Also:
buildFrom(com.datastax.driver.core.Cluster.Initializer)
-
-
Method Detail
-
init
public Cluster init()
Initialize this Cluster instance.This method creates an initial connection to one of the contact points used to construct the
Clusterinstance. That connection is then used to populate the clusterMetadata.Calling this method is optional in the sense that any call to one of the
connectmethods of this object will automatically trigger a call to this method beforehand. It is thus only useful to call this method if for some reason you want to populate the metadata (or test that at least one contact point can be reached) without creating a firstSession.Please note that this method only creates one control connection for gathering cluster metadata. In particular, it doesn't create any connection pools. Those are created when a new
Sessionis created throughconnect.This method has no effect if the cluster is already initialized.
- Returns:
- this
Clusterobject. - Throws:
NoHostAvailableException- if no host amongst the contact points can be reached.AuthenticationException- if an authentication error occurs while contacting the initial contact points.IllegalStateException- if the Cluster was closed prior to calling this method. This can occur either directly (throughclose()orcloseAsync()), or as a result of an error while initializing the Cluster.
-
buildFrom
public static Cluster buildFrom(Cluster.Initializer initializer)
Build a new cluster based on the provided initializer.Note that for building a cluster pragmatically, Cluster.Builder provides a slightly less verbose shortcut with
Cluster.Builder.build().Also note that that all the contact points provided by
initializermust share the same port.- Parameters:
initializer- the Cluster.Initializer to use- Returns:
- the newly created Cluster instance
- Throws:
IllegalArgumentException- if the list of contact points provided byinitializeris empty or if not all those contact points have the same port.
-
builder
public static Cluster.Builder builder()
Creates a newCluster.Builderinstance.This is a convenience method for
new Cluster.Builder().- Returns:
- the new cluster builder.
-
getDriverVersion
public static String getDriverVersion()
Returns the current version of the driver.This is intended for products that wrap or extend the driver, as a way to check compatibility if end-users override the driver version in their application.
- Returns:
- the version.
-
logDriverVersion
public static void logDriverVersion()
Logs the driver version to the console.This method logs the version using the logger
com.datastax.driver.coreand levelINFO.
-
newSession
public Session newSession()
Creates a new session on this cluster but does not initialize it.Because this method does not perform any initialization, it cannot fail. The initialization of the session (the connection of the Session to the Cassandra nodes) will occur if either the
Session.init()method is called explicitly, or whenever the returned session object is used.Once a session returned by this method gets initialized (see above), it will be set to no keyspace. If you want to set such session to a keyspace, you will have to explicitly execute a 'USE mykeyspace' query.
Note that if you do not particularly need to defer initialization, it is simpler to use one of the
connect()method of this class.- Returns:
- a new, non-initialized session on this cluster.
-
connect
public Session connect()
Creates a new session on this cluster and initialize it.Note that this method will initialize the newly created session, trying to connect to the Cassandra nodes before returning. If you only want to create a Session object without initializing it right away, see
newSession().- Returns:
- a new session on this cluster sets to no keyspace.
- Throws:
NoHostAvailableException- if the Cluster has not been initialized yet (init()has not be called and this is the first connect call) and no host amongst the contact points can be reached.AuthenticationException- if an authentication error occurs while contacting the initial contact points.IllegalStateException- if the Cluster was closed prior to calling this method. This can occur either directly (throughclose()orcloseAsync()), or as a result of an error while initializing the Cluster.
-
connect
public Session connect(String keyspace)
Creates a new session on this cluster, initialize it and sets the keyspace to the provided one.Note that this method will initialize the newly created session, trying to connect to the Cassandra nodes before returning. If you only want to create a Session object without initializing it right away, see
newSession().- Parameters:
keyspace- The name of the keyspace to use for the createdSession.- Returns:
- a new session on this cluster sets to keyspace
keyspaceName. - Throws:
NoHostAvailableException- if the Cluster has not been initialized yet (init()has not be called and this is the first connect call) and no host amongst the contact points can be reached, or if no host can be contacted to set thekeyspace.AuthenticationException- if an authentication error occurs while contacting the initial contact points.InvalidQueryException- if the keyspace does not exist.IllegalStateException- if the Cluster was closed prior to calling this method. This can occur either directly (throughclose()orcloseAsync()), or as a result of an error while initializing the Cluster.
-
connectAsync
public ListenableFuture<Session> connectAsync()
Creates a new session on this cluster and initializes it asynchronously.This will also initialize the
Clusterif needed; note that cluster initialization happens synchronously on the thread that called this method. Therefore it is recommended to initialize the cluster at application startup, and not rely on this method to do it.Note that if a default keyspace has been configured for use with a DBaaS cluster, this method will attempt to set the session keyspace to that keyspace, effectively behaving like
connect(String).- Returns:
- a future that will complete when the session is fully initialized.
- Throws:
NoHostAvailableException- if the Cluster has not been initialized yet (init()has not been called and this is the first connect call) and no host amongst the contact points can be reached.IllegalStateException- if the Cluster was closed prior to calling this method. This can occur either directly (throughclose()orcloseAsync()), or as a result of an error while initializing the Cluster.- See Also:
connect()
-
connectAsync
public ListenableFuture<Session> connectAsync(String keyspace)
Creates a new session on this cluster, and initializes it to the given keyspace asynchronously.This will also initialize the
Clusterif needed; note that cluster initialization happens synchronously on the thread that called this method. Therefore it is recommended to initialize the cluster at application startup, and not rely on this method to do it.- Parameters:
keyspace- The name of the keyspace to use for the createdSession.- Returns:
- a future that will complete when the session is fully initialized.
- Throws:
NoHostAvailableException- if the Cluster has not been initialized yet (init()has not been called and this is the first connect call) and no host amongst the contact points can be reached.IllegalStateException- if the Cluster was closed prior to calling this method. This can occur either directly (throughclose()orcloseAsync()), or as a result of an error while initializing the Cluster.
-
getClusterName
public String getClusterName()
The name of this cluster object.Note that this is not the Cassandra cluster name, but rather a name assigned to this Cluster object. Currently, that name is only used for one purpose: to distinguish exposed JMX metrics when multiple Cluster instances live in the same JVM (which should be rare in the first place). That name can be set at Cluster building time (through
Cluster.Builder.withClusterName(java.lang.String)for instance) but will default to a name likecluster1where each Cluster instance in the same JVM will have a different number.- Returns:
- the name for this cluster instance.
-
getMetadata
public Metadata getMetadata()
Returns read-only metadata on the connected cluster.This includes the known nodes with their status as seen by the driver, as well as the schema definitions. Since this return metadata on the connected cluster, this method may trigger the creation of a connection if none has been established yet (neither
init()norconnect()has been called yet).- Returns:
- the cluster metadata.
- Throws:
NoHostAvailableException- if the Cluster has not been initialized yet and no host amongst the contact points can be reached.AuthenticationException- if an authentication error occurs while contacting the initial contact points.IllegalStateException- if the Cluster was closed prior to calling this method. This can occur either directly (throughclose()orcloseAsync()), or as a result of an error while initializing the Cluster.
-
getConfiguration
public Configuration getConfiguration()
The cluster configuration.- Returns:
- the cluster configuration.
-
getMetrics
public Metrics getMetrics()
The cluster metrics.- Returns:
- the cluster metrics, or
nullif this cluster has not yet beeninitialized, or if metrics collection has been disabled (that is ifConfiguration.getMetricsOptions()returnsnull).
-
register
public Cluster register(Host.StateListener listener)
Registers the provided listener to be notified on hosts up/down/added/removed events.Registering the same listener multiple times is a no-op.
This method should be used to register additional listeners on an already-initialized cluster. To add listeners to a cluster object prior to its initialization, use
Cluster.Builder.withInitialListeners(Collection). Calling this method on a non-initialized cluster will result in the listener beingnotifiedtwice of cluster registration: once inside this method, and once at cluster initialization.- Parameters:
listener- the newHost.StateListenerto register.- Returns:
- this
Clusterobject;
-
unregister
public Cluster unregister(Host.StateListener listener)
Unregisters the provided listener from being notified on hosts events.This method is a no-op if
listenerhasn't previously been registered against this Cluster.- Parameters:
listener- theHost.StateListenerto unregister.- Returns:
- this
Clusterobject;
-
register
public Cluster register(LatencyTracker tracker)
Registers the provided tracker to be updated with hosts read latencies.Registering the same tracker multiple times is a no-op.
Beware that the registered tracker's
updatemethod will be called very frequently (at the end of every query to a Cassandra host) and should thus not be costly.The main use case for a
LatencyTrackeris to allow load balancing policies to implement latency awareness. For example,LatencyAwarePolicyregisters it's own internalLatencyTracker(automatically, you don't have to call this method directly).- Parameters:
tracker- the newLatencyTrackerto register.- Returns:
- this
Clusterobject;
-
unregister
public Cluster unregister(LatencyTracker tracker)
Unregisters the provided latency tracking from being updated with host read latencies.This method is a no-op if
trackerhasn't previously been registered against this Cluster.- Parameters:
tracker- theLatencyTrackerto unregister.- Returns:
- this
Clusterobject;
-
register
public Cluster register(SchemaChangeListener listener)
Registers the provided listener to be updated with schema change events.Registering the same listener multiple times is a no-op.
- Parameters:
listener- the newSchemaChangeListenerto register.- Returns:
- this
Clusterobject;
-
unregister
public Cluster unregister(SchemaChangeListener listener)
Unregisters the provided schema change listener from being updated with schema change events.This method is a no-op if
listenerhasn't previously been registered against this Cluster.- Parameters:
listener- theSchemaChangeListenerto unregister.- Returns:
- this
Clusterobject;
-
closeAsync
public CloseFuture closeAsync()
Initiates a shutdown of this cluster instance.This method is asynchronous and return a future on the completion of the shutdown process. As soon a the cluster is shutdown, no new request will be accepted, but already submitted queries are allowed to complete. This method closes all connections from all sessions and reclaims all resources used by this Cluster instance.
If for some reason you wish to expedite this process, the
CloseFuture.force()can be called on the result future.This method has no particular effect if the cluster was already closed (in which case the returned future will return immediately).
- Returns:
- a future on the completion of the shutdown process.
-
close
public void close()
Initiates a shutdown of this cluster instance and blocks until that shutdown completes.This method is a shortcut for
closeAsync().get().- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-
isClosed
public boolean isClosed()
Whether this Cluster instance has been closed.Note that this method returns true as soon as one of the close methods (
closeAsync()orclose()) has been called, it does not guarantee that the closing is done. If you want to guarantee that the closing is done, you can callclose()and wait until it returns (or call the get method oncloseAsync()with a very short timeout and check this doesn't timeout).- Returns:
trueif this Cluster instance has been closed,falseotherwise.
-
-