• Astra SDK Java
Astra Java SDK is a framework that wraps different apis and interfaces exposed by Astra and provides fluent API and ease of usage.
1. Pre-requisites¶
Setup your JAVA
Development environment
- Install Java Development Kit (JDK) 8+
Use java reference documentation targetting your operating system to install a Java Development Kit. You can then validate your installation with the following command.
- Install Apache Maven (3.8+)
Samples and tutorials have been designed with Apache Maven
. Use the reference documentation top install maven validate your installation with
Setup Datastax Astra DB
- Create your DataStax Astra account:
- Create an Astra Token
An astra token acts as your credentials, it holds the different permissions. The scope of a token is the whole organization (tenant) but permissions can be edited to limit usage to a single database.
To create a token, please follow this guide
The Token is in fact three separate strings: a Client ID
, a Client Secret
and the token
proper. You will need some of these strings to access the database, depending on the type of access you plan. Although the Client ID, strictly speaking, is not a secret, you should regard this whole object as a secret and make sure not to share it inadvertently (e.g. committing it to a Git repository) as it grants access to your databases.
It is handy to have your token declare as an environment variable (replace with proper value):
- Create a Database and a keyspace
With your account you can run multiple databases, a Databases is an Apache Cassandra cluster. It can live in one or multiple regions (dc). In each Database you can have multiple keyspaces. In the page we will use the database name db_demo
and the keyspace keyspace_demo
.
You can create the DB using the user interface and here is a tutorial. You can also use Astra command line interface. To install and setup the CLI run the following:
curl -Ls "https://dtsx.io/get-astra-cli" | bash
source ~/.astra/cli/astra-init.sh
astra setup --token ${ASTRA_TOKEN}
To create DB and keyspace with the CLI:
- Download the Secure Connect Bundle for current database
A Secure Connect Bundle contains the certificates and endpoints informations to open a mTLS connection. Often mentionned as scb
its scope is a database AND a region. If your database is deployed on multiple regions you will have to download the bundle for each one and initiate the connection accordingly. Instructions to download Secure Connect Bundle are here
You can download the secure connect bundle from the user interface and here is a tutorial. You can also use Astra command line interface.
2. Astra DB¶
2.1 - Project Setup¶
Project Setup
- If you create a project from scratch you can start with our template that include the
astra-sdk
dependency.:
2.2 - CQL Native Drivers¶
Sample Code
- Create a class
AstraSdkDrivers.java
with the following code.
What you need to know
🔑 About Credentials
- The pair
clientId
/clientSecret
hold your credentials. It can be replaced by the value of the token only.
- There is no need to download the cloud securebundle in advance as it will be downloaded for you in folder
~.astra/scb
by default. Stil, but you can also provide the file location with.withCqlCloudSecureConnectBundle()
:
- Notice than
enableCQL()
must be explictely provided. Thesdk
will open only the asked interfaces in order to limit the resource consumption.
⚙️ About Database identifiers
databaseId
/databaseRegion
will be required to locate the proper endpoint. You can find them for a particular database with either the cli.
$astra db list
+---------------------+--------------------------------------+---------------------+-----------+
| Name | id | Default Region | Status |
+---------------------+--------------------------------------+---------------------+-----------+
| db_demo | 3043a40f-39bf-464e-8337-dc283167b2c3 | us-east1 | ACTIVE |
+---------------------+--------------------------------------+---------------------+-----------+
$astra db describe db_demo
+------------------------+-----------------------------------------+
| Attribute | Value |
+------------------------+-----------------------------------------+
| Name | db_demo |
| id | 3043a40f-39bf-464e-8337-dc283167b2c3 |
| Status | ACTIVE |
| Default Cloud Provider | GCP |
| Default Region | us-east1 |
| Default Keyspace | keyspace_demo |
| Creation Time | 2023-04-17T09:03:14Z |
| Keyspaces | [0] demo |
| Regions | [0] us-east1 |
+------------------------+-----------------------------------------+
2.3 - Stargate Rest API¶
The REST API
(also known as api Data
) is wrapping exposing CQL language as Rest Resources. To get more information about this API check the dedicated page
Sample Code
- Create a class
AstraSdkRestApi.java
with the following code.
More information about Rest API
2.4 - Stargate Document API¶
The DOCUMENT API
exposes an Rest Resources to use Cassandra as a document-oriented database To get more information about this API check the dedicated page.
Sample Code
- Create a class
AstraSdkDocApi.java
with the following code.
Document Repository
With modern java applications you want to interact with the DB using the repository pattern where most operations have been implemented for you findAll(), findById()...
. Astra SDK provide this feature for the document API.
Sample Document Repository
- Create a class
AstraSdkDocRepository.java
with the following code.
2.5 - Stargate Grpc APi¶
The GRPC API
exposes a grpc endpoint to query some CQL. From there it is very similar from native drivers. To know more about it check the dedicated page.
Sample Code
- Create a class
AstraSdkGrpcApi.java
with the following code.
2.6 - Stargate GraphQL Api¶
The GRAPHQL API
exposes a graphQL endpoint to query CQL over graphQL. To know more about this api please check the dedicated page.
Sample Code
- Create a class
AstraSdkGraphQLApi.java
with the following code.
3. Astra Streaming¶
3.1 - Project setup¶
Project Setup
3.2 - PulsarClient¶
Pulsar Api are very simple and the need of an sdk is limited. It could be used to get the proper version of pulsar-client
, there are no extra setup steps.
PulsarClient Setup
3.3 - Pulsar Admin¶
Pulsar Api are very simple and the need of an sdk is limited. It could be used to to setup the pulsar-admin
for you.
Pulsar Admin Setup
String pulsarUrlAdmin = "https://<cluster>.api.streaming.datastax.com";
String pulsarToken = "<your_token>"
PulsarAdmin pa = new PulsarAdminProvider(pulsarUrlAdmin,pulsarToken).get();
// Get Infos
System.out.println(pa.tenants().getTenantInfo("tenant_name").toString());
// List Namespaces
pa.namespaces().getNamespaces("clun-gcp-east1").forEach(System.out::println);
// List Topics
pa.topics().getList("clun-gcp-east1/astracdc").forEach(System.out::println);
// Details on a topic
PersistentTopicInternalStats stats = pa.topics()
.getInternalStats("persistent://<tenant>/<namespace>/<topic>");
System.out.println(stats.totalSize);
4.3 - Producer¶
The Astra user interface already shows the expected code. There is very little an SDK can provide here. A sample to code to copy.
Sample Code
import org.apache.pulsar.client.api.*;
import java.io.IOException;
public class SimpleProducer {
private static final String CLUSTER = "<cluster>";
private static final String TENANT = "<yourtenant>";
private static final String NAMESPACE = "<yournamespace>";
private static final String TOPIC = "<your_topic>";
private static final String PULSAR_TOKEN = "<your_token>";
private static final String SERVICE_URL =
"pulsar+ssl://" + CLUSTER + "streaming.datastax.com:6651";
public static void main(String[] args) throws IOException {
try(PulsarClient cli = new PulsarClientProvider(pulsarUrl, pulsarToken).get()) {
try( Producer<byte[]> producer = cli
.newProducer()
.topic("persistent://" + TENANT + "/"+NAMESPACE+"/" + TOPIC)
.create()) {
// Send a message to the topic
producer.send("Hello World".getBytes());
}
};
}
}
4.4 - Consumer¶
The Astra user interface already shows the expected code. There is very little an SDK can provide here. A sample to code to copy.
Sample Consumer
import org.apache.pulsar.client.api.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class SimpleConsumer {
private static final String CLUSTER = "<cluster>";
private static final String TENANT = "<yourtenant>";
private static final String NAMESPACE = "<yournamespace>";
private static final String TOPIC = "<your_topic>";
private static final String SUBSCRIPTION = "<your_subscription>";
private static final String PULSAR_TOKEN = "<your_token>";
public static void main(String[] args) throws IOException {
try(PulsarClient cli = new PulsarClientProvider(
"pulsar+ssl://" + CLUSTER + "streaming.datastax.com:6651", pulsarToken).get()) {
try(Consumer consumer = cli
.newConsumer()
.topic("persistent://" + TENANT + "/"+NAMESPACE+"/" + TOPIC)
.subscriptionName(SUBSCRIPTION)
.subscribe()) {
boolean receivedMsg = false;
// Loop until a message is received
do {
// Block for up to 1 second for a message
Message msg = consumer.receive(1, TimeUnit.SECONDS);
if(msg != null){
System.out.printf("Message received: %s", new String(msg.getData()));
// Acknowledge the message to remove it from the message backlog
consumer.acknowledge(msg);
receivedMsg = true;
}
} while (!receivedMsg);
}
}
}
4. Spring Boot¶
4.1 - Create Project¶
Spring Boot 2x
- To Create a project from scratch start with our template:
The 3 last parameters in this command define your project groupId, artifactId and version.
Spring Boot 3x
- To Create a project from scratch start with our template:
The 3 last parameters in this command define your project groupId, artifactId and version.
4.2 - Setup Project¶
Spring Boot 2x
If you created your project with the archetypes the
pom.xml
is already correct.
Spring Boot 3x
If you created your project with the archetypes the
pom.xml
is already correct.
4.3 - Configuration¶
Configuration of application.xml
If you created the project with the archetypes the file is already populated.
- Update your
application.xml
with the following keys
astra:
api:
application-token: ${ASTRA_DB_APPLICATION_TOKEN}
database-id: ${ASTRA_DB_ID}
database-region: ${ASTRA_DB_REGION}
cross-region-failback: false
cql:
enabled: true
download-scb:
enabled: true
driver-config:
basic:
session-keyspace: ${ASTRA_DB_KEYSPACE}
As you notice there are 4 variables to be replaced to point to your Astra Database. You can create environment variables or do the substition manually.
Param | Description |
---|---|
ASTRA_DB_APPLICATION_TOKEN |
Your authentication token starting with AstraCS:.. It MUST HAVE ADMINISTRATION PRIVILEGES in order to download the secure connect bundle from devops API. |
ASTRA_DB_ID |
Your database identifier, it is a UUID available at the top of your db page in the user interface or in the CLI with astra db list |
ASTRA_DB_REGION |
Your database main region. Even if the database lives in multiple region you need to provide the main one (to reduce latency). The id of the region also provides information on the cloud provide in used. There is no need for an extra parameter. It is a value available in the details database page in the user interface or in the CLI with astra db list |
ASTRA_DB_KEYSPACE |
The keyspace where to connect your application. |
The ASTRA CLI can help you defining those environment variables with the following:
4.4 - Run Application¶
You can now start your application with:
If you created the application with archetype a firs table todos
has been created and populated. An REST APi is also available for your
5. Astra Devops Api¶
Reminders
To work with the devops Apis it is recommanded to have an Organization Administrator
role token. Most of the operation indeed required an high level of permissions.
- Create an Astra Token
To create a token, please follow this guide
Project Setup
If you added the astra-sdk
dependency your are good to go. Now if you want to work only work with the Devops API and not the stargate APis you might want to only import this subset.
<dependencies>
<dependency>
<groupId>com.datastax.astra</groupId>
<artifactId>astra-sdk-devops</artifactId>
<version>${latestSDK}</version>
</dependency>
</dependencies>
- Initializing the Devopis Api Client
// It can be accessed from the global AstraClient
AstraClient astraClient = ....;
AstraDevopsApiClient apiDevopsClient = astraClient.apiDevops();
AstraDbClient apiDevopsClientDb = astraClient.apiDevopsDatabases();
AstraStreamingClient apiDevopsClientStreaming = astraClient.apiDevopsStreaming();
// You can only setup the devops part
AstraDevopsApiClient apiDevopsDirect = new AstraDevopsApiClient(getToken());
5.1 - Astra DB¶
The SDK is extensively tested a lot of samples can be found in the database unit tests
Sample Code
String token = "<your_token>";
AstraDbClient devopsDbsClient = new AstraDbClient(token);
// Create DB
devopsDbsClient.create(DatabaseCreationRequest
.builder()
.name("my_db")
.keyspace("my_keyspace")
.cloudRegion("my_region")
//.withVector() to enable vector preview
.build());
Stream<Database> dbList = devopsDbsClient.findByName("my_db");
// Working with 1 db
DatabaseClient dbCli = devopsDbsClient.databaseByName("my_db"));
// Keyspaces
dbCli.keyspaces().exist(SDK_TEST_KEYSPACE2)
dbCli.keyspaces().create(SDK_TEST_KEYSPACE2)
dbCli.keyspaces().delete("invalid")
// Scb
dbCli.downloadDefaultSecureConnectBundle(randomFile);
dbCli.downloadSecureConnectBundle(SDK_TEST_DB_REGION, randomFile);
dbCli.downloadAllSecureConnectBundles("/invalid"));
// Multi-Regions
dbCli.datacenters().create("serverless", CloudProviderType.AWS, "eu-central-1");
dbCli.datacenters().delete("eu-central-1");
// Classic Ops
dbCli.park()
dbCli.unpark()
dbCli.resize(2)
dbCli.resetPassword("token", "cedrick1")
// Access-list
dbCli.accessLists().addAddress(a1, a2);
5.2 - Astra Streaming¶
The SDK is extensively tested a lot of samples can be found in the streaming unit tests
Sample Code
5.3 - Organization¶
The SDK is extensively tested a lot of samples can be found in the control unit tests
6. Extra Resources¶
6.1 - Source Code and Issues¶
-
The source code is open and available at https://github.com/datastax/astra-sdk-java. If you like the solution please give consider to give us a star on github.
-
To open an issue please use the Github Repository Issues
6.2 - JavaDoc¶
The javadocs are available here: