public class Cluster extends Object
Cluster
is the main entry point when connecting to a Couchbase cluster.
Most likely you want to start out by using the connect(String, String, String)
entry point. For more
advanced options you want to use the connect(String, ClusterOptions)
method. The entry point that allows
overriding the seed nodes (connect(Set, ClusterOptions)
is only needed if you run a couchbase cluster
at non-standard ports.
See the individual connect methods for more information, but here is a snippet to get you off the ground quickly. It assumes you have Couchbase running locally and the "travel-sample" sample bucket loaded:
//Connect and open a bucket Cluster cluster = Cluster.connect("127.0.0.1","Administrator","password"); Bucket bucket = cluster.bucket("travel-sample"); Collection collection = bucket.defaultCollection(); // Perform a N1QL query QueryResult queryResult = cluster.query("select * from `travel-sample` limit 5"); System.out.println(queryResult.rowsAsObject()); // Perform a KV request and load a document GetResult getResult = collection.get("airline_10"); System.out.println(getResult);
When the application shuts down (or the SDK is not needed anymore), you are required to call disconnect()
.
If you omit this step, the application will terminate (all spawned threads are daemon threads) but any operations
or work in-flight will not be able to complete and lead to undesired side-effects. Note that disconnect will also
shutdown all associated buckets
.
Cluster-level operations like query(String)
will not work unless at leas one bucket is opened against a
pre 6.5 cluster. If you are using 6.5 or later, you can run cluster-level queries without opening a bucket. All
of these operations are lazy, so the SDK will bootstrap in the background and service queries as quickly as possible.
This also means that the first operations might be a bit slower until all sockets are opened in the background and
the configuration is loaded. If you want to wait explicitly, you can utilize the waitUntilReady(Duration)
method before performing your first query.
The SDK will only work against Couchbase Server 5.0 and later, because RBAC (role-based access control) is a first class concept since 3.0 and therefore required.
Modifier and Type | Method and Description |
---|---|
AnalyticsIndexManager |
analyticsIndexes()
The analytics index manager allows to modify and create indexes for the analytics service.
|
AnalyticsResult |
analyticsQuery(String statement)
Performs an analytics query with default
AnalyticsOptions . |
AnalyticsResult |
analyticsQuery(String statement,
AnalyticsOptions options)
Performs an analytics query with custom
AnalyticsOptions . |
AsyncCluster |
async()
Provides access to the related
AsyncCluster . |
Bucket |
bucket(String bucketName)
Opens a
Bucket with the given name. |
BucketManager |
buckets()
The bucket manager allows to perform administrative tasks on buckets and their resources.
|
static Cluster |
connect(Set<SeedNode> seedNodes,
ClusterOptions options)
Connect to a Couchbase cluster with a list of seed nodes and custom options.
|
static Cluster |
connect(String connectionString,
ClusterOptions options)
Connect to a Couchbase cluster with custom options.
|
static Cluster |
connect(String connectionString,
String username,
String password)
Connect to a Couchbase cluster with a username and a password as credentials.
|
Core |
core()
Provides access to the underlying
Core . |
DiagnosticsResult |
diagnostics()
Runs a diagnostic report on the current state of the cluster from the SDKs point of view.
|
DiagnosticsResult |
diagnostics(DiagnosticsOptions options)
Runs a diagnostic report with custom options on the current state of the cluster from the SDKs point of view.
|
void |
disconnect()
Performs a non-reversible disconnect of this
Cluster . |
void |
disconnect(Duration timeout)
Performs a non-reversible disconnect of this
Cluster . |
ClusterEnvironment |
environment()
Provides access to the used
ClusterEnvironment . |
PingResult |
ping()
Performs application-level ping requests against services in the couchbase cluster.
|
PingResult |
ping(PingOptions options)
Performs application-level ping requests with custom options against services in the couchbase cluster.
|
QueryResult |
query(String statement)
Performs a query against the query (N1QL) services.
|
QueryResult |
query(String statement,
QueryOptions options)
Performs a query against the query (N1QL) services with custom options.
|
QueryIndexManager |
queryIndexes()
The query index manager allows to modify and create indexes for the query service.
|
ReactiveCluster |
reactive()
Provides access to the related
ReactiveCluster . |
SearchIndexManager |
searchIndexes()
The search index manager allows to modify and create indexes for the search service.
|
SearchResult |
searchQuery(String indexName,
SearchQuery query)
Performs a Full Text Search (FTS) query with default
SearchOptions . |
SearchResult |
searchQuery(String indexName,
SearchQuery query,
SearchOptions options)
Performs a Full Text Search (FTS) query with custom
SearchOptions . |
UserManager |
users()
The user manager allows to manage users and groups.
|
void |
waitUntilReady(Duration timeout)
Waits until the desired
ClusterState is reached. |
void |
waitUntilReady(Duration timeout,
WaitUntilReadyOptions options)
Waits until the desired
ClusterState is reached. |
public static Cluster connect(String connectionString, String username, String password)
This is the simplest (and recommended) method to connect to the cluster if you do not need to provide any custom options.
The first argument (the connection string in its simplest form) is used to supply the hostnames of the cluster. In development it is OK to only pass in one hostname (or IP address), but in production we recommend passing in at least 3 nodes of the cluster (comma separated). The reason is that if one or more of the nodes are not reachable the client will still be able to bootstrap (and your application will become more resilient as a result).
Here is how you specify one node to use for bootstrapping:
Cluster cluster = Cluster.connect("127.0.0.1", "user", "password"); // ok during developmentThis is what we recommend in production:
Cluster cluster = Cluster.connect("host1,host2,host3", "user", "password"); // recommended in productionIt is important to understand that the SDK will only use the bootstrap ("seed nodes") host list to establish an initial contact with the cluster. Once the configuration is loaded this list is discarded and the client will connect to all nodes based on this configuration.
This method will return immediately and the SDK will try to establish all the necessary resources and connections
in the background. This means that depending on how fast it can be bootstrapped, the first couple cluster-level
operations like query(String)
will take a bit longer. If you want to wait explicitly until those resources
are available, you can use the waitUntilReady(Duration)
method before running any of them:
Cluster cluster = Cluster.connect("host1,host2,host3", "user", "password"); cluster.waitUntilReady(Duration.ofSeconds(5)); QueryResult result = cluster.query("select * from bucket limit 1");
connectionString
- connection string used to locate the Couchbase cluster.username
- the name of the user with appropriate permissions on the cluster.password
- the password of the user with appropriate permissions on the cluster.Cluster
.public static Cluster connect(String connectionString, ClusterOptions options)
You likely want to use this over the simpler connect(String, String, String)
if:
ClusterEnvironment
Authenticator
A custom environment can be passed in like this:
// on bootstrap: ClusterEnvironment environment = ClusterEnvironment.builder().build(); Cluster cluster = Cluster.connect( "127.0.0.1", clusterOptions("user", "password").environment(environment) ); // on shutdown: cluster.disconnect(); environment.shutdown();It is VERY important to shut down the environment when being passed in separately (as shown in the code sample above) and AFTER the cluster is disconnected. This will ensure an orderly shutdown and makes sure that no resources are left lingering.
If you want to pass in a custom Authenticator
, it is likely because you are setting up certificate-based
authentication instead of using a username and a password directly. Remember to also enable TLS.
ClusterEnvironment environment = ClusterEnvironment .builder() .securityConfig(SecurityConfig.enableTls(true)) .build(); Authenticator authenticator = CertificateAuthenticator.fromKey(...); Cluster cluster = Cluster.connect( "127.0.0.1", clusterOptions(authenticator).environment(environment) );This method will return immediately and the SDK will try to establish all the necessary resources and connections in the background. This means that depending on how fast it can be bootstrapped, the first couple cluster-level operations like
query(String)
will take a bit longer. If you want to wait explicitly until those resources
are available, you can use the waitUntilReady(Duration)
method before running any of them:
Cluster cluster = Cluster.connect("host1,host2,host3", "user", "password"); cluster.waitUntilReady(Duration.ofSeconds(5)); QueryResult result = cluster.query("select * from bucket limit 1");
connectionString
- connection string used to locate the Couchbase cluster.options
- custom options when creating the cluster.Cluster
.public static Cluster connect(Set<SeedNode> seedNodes, ClusterOptions options)
Note that you likely only want to use this method if you need to pass in custom ports for specific seed nodes
during bootstrap. Otherwise we recommend relying on the simpler connect(String, String, String)
method
instead.
The following example shows how to bootstrap against a node with custom KV and management ports:
SetseedNodes = new HashSet<>(Collections.singletonList( SeedNode.create("127.0.0.1", Optional.of(12000), Optional.of(9000)) )); Cluster cluster Cluster.connect(seedNodes, clusterOptions("user", "password"));
seedNodes
- the seed nodes used to connect to the cluster.options
- custom options when creating the cluster.Cluster
.public AsyncCluster async()
AsyncCluster
.
Note that the AsyncCluster
is considered advanced API and should only be used to get the last drop
of performance or if you are building higher-level abstractions on top. If in doubt, we recommend using the
reactive()
API instead.
public ReactiveCluster reactive()
ReactiveCluster
.@Stability.Volatile public Core core()
Core
.
This is advanced and volatile API - it might change any time without notice. Use with care!
public UserManager users()
public BucketManager buckets()
public AnalyticsIndexManager analyticsIndexes()
public QueryIndexManager queryIndexes()
public SearchIndexManager searchIndexes()
public ClusterEnvironment environment()
ClusterEnvironment
.public QueryResult query(String statement)
statement
- the N1QL query statement.QueryResult
once the response arrives successfully.TimeoutException
- if the operation times out before getting a result.CouchbaseException
- for all other error reasons (acts as a base type and catch-all).public QueryResult query(String statement, QueryOptions options)
statement
- the N1QL query statement as a raw string.options
- the custom options for this query.QueryResult
once the response arrives successfully.TimeoutException
- if the operation times out before getting a result.CouchbaseException
- for all other error reasons (acts as a base type and catch-all).public AnalyticsResult analyticsQuery(String statement)
AnalyticsOptions
.statement
- the query statement as a raw string.AnalyticsResult
once the response arrives successfully.TimeoutException
- if the operation times out before getting a result.CouchbaseException
- for all other error reasons (acts as a base type and catch-all).public AnalyticsResult analyticsQuery(String statement, AnalyticsOptions options)
AnalyticsOptions
.statement
- the query statement as a raw string.options
- the custom options for this query.AnalyticsResult
once the response arrives successfully.TimeoutException
- if the operation times out before getting a result.CouchbaseException
- for all other error reasons (acts as a base type and catch-all).public SearchResult searchQuery(String indexName, SearchQuery query)
SearchOptions
.query
- the query, in the form of a SearchQuery
SearchRequest
once the response arrives successfully.TimeoutException
- if the operation times out before getting a result.CouchbaseException
- for all other error reasons (acts as a base type and catch-all).public SearchResult searchQuery(String indexName, SearchQuery query, SearchOptions options)
SearchOptions
.query
- the query, in the form of a SearchQuery
options
- the custom options for this query.SearchRequest
once the response arrives successfully.TimeoutException
- if the operation times out before getting a result.CouchbaseException
- for all other error reasons (acts as a base type and catch-all).public Bucket bucket(String bucketName)
Bucket
with the given name.bucketName
- the name of the bucket to open.Bucket
once opened.public void disconnect()
Cluster
.
If this method is used, the default disconnect timeout on the environment is used. Please use the companion
overload (disconnect(Duration)
if you want to provide a custom duration.
If a custom ClusterEnvironment
has been passed in during connect, it is VERY important to
shut it down after calling this method. This will prevent any in-flight tasks to be stopped prematurely.
public void disconnect(Duration timeout)
Cluster
.
If a custom ClusterEnvironment
has been passed in during connect, it is VERY important to
shut it down after calling this method. This will prevent any in-flight tasks to be stopped prematurely.
timeout
- allows to override the default disconnect duration.public DiagnosticsResult diagnostics()
Please note that it does not perform any I/O to do this, it will only use the current known state of the cluster to assemble the report (so, if for example no N1QL query has been run the socket pool might be empty and as result not show up in the report).
DiagnosticsResult
once complete.public DiagnosticsResult diagnostics(DiagnosticsOptions options)
Please note that it does not perform any I/O to do this, it will only use the current known state of the cluster to assemble the report (so, if for example no N1QL query has been run the socket pool might be empty and as result not show up in the report).
options
- options that allow to customize the report.DiagnosticsResult
once complete.public PingResult ping()
Note that this operation performs active I/O against services and endpoints to assess their health. If you do
not wish to perform I/O, consider using the diagnostics()
instead. You can also combine the functionality
of both APIs as needed, which is waitUntilReady(Duration)
is doing in its implementation as well.
PingResult
once complete.public PingResult ping(PingOptions options)
Note that this operation performs active I/O against services and endpoints to assess their health. If you do
not wish to perform I/O, consider using the diagnostics(DiagnosticsOptions)
instead. You can also combine
the functionality of both APIs as needed, which is waitUntilReady(Duration)
is doing in its
implementation as well.
PingResult
once complete.public void waitUntilReady(Duration timeout)
ClusterState
is reached.
This method will wait until either the cluster state is "online", or the timeout is reached. Since the SDK is bootstrapping lazily, this method allows to eagerly check during bootstrap if all of the services are online and usable before moving on.
timeout
- the maximum time to wait until readiness.public void waitUntilReady(Duration timeout, WaitUntilReadyOptions options)
ClusterState
is reached.
This method will wait until either the cluster state is "online" by default, or the timeout is reached. Since the
SDK is bootstrapping lazily, this method allows to eagerly check during bootstrap if all of the services are online
and usable before moving on. You can tune the properties through WaitUntilReadyOptions
.
timeout
- the maximum time to wait until readiness.options
- the options to customize the readiness waiting.Copyright © 2021 Couchbase, Inc.. All rights reserved.