-
Notifications
You must be signed in to change notification settings - Fork 10
Spring Boot Starter QuickStart
This tutorial will guide through the steps to start coding with the java Astra SDK. The code is a spring boot and spring data project in order to demonstrate how the SDK can be leveraged on existing application.
ℹ️ You can download the code here 📥 Download
- Prerequisites
- Create your project with Initializr
- Setup your project
- Configuration
- Working with Spring Data Cassandra
- Working with Spring Actuator
- Working with Spring Security
- Use the reference documentation to install a Java Development Kit
- Validate your installation with
java --version
- Use the reference documentation to install Apache Maven
- Validate your installation with
mvn -version
- In the Quickstart-Astra, the procedure to create an instance has been described. Please follow the instructions
- Note your
databaseId
,databaseRegion
and thekeyspace
you used.
- In the Quickstart-Astra, the procedure to create a token has been described. Please follow the instructions
- Note your
token
(it should look likeAstraCS:...
)
To create a spring boot project, the go to is Spring Initializr available here start.spring.io. There you define the dependencies you need and configuration values. We did the work for you, simply use this TEMPLATE LINK
I already defined the properties for you:
-
groupId=
com.datastax.tutorial
-
artifactId=
sdk-quickstart-spring
-
dependencies=
Spring Web
andSpring Data for Cassandra
Do not try to start the application immediately, it would fail. We did not tell how to connect to Cassandra yet.
- Rename class
SdkQuickstartSpringApplication
toQuickStartSpring
With dependencies introduced by Spring Data Cassandra, Spring Boot wants to create beans to connect to Cassandra but, as of now we don't have any backend. We will fix it soon but for now let's add a couple of lines in the main class. In order to remove autoconfigurations we use exclude clauses in the annotation SpringBootApplication
for class QuickStartSpring
.
- Edit the to match the code below
package com.datastax.tutorial;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration;
import org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication(exclude = {
CassandraDataAutoConfiguration.class,
CassandraAutoConfiguration.class
})
public class QuickStartSpring {
public static void main(String[] args) {
SpringApplication.run(QuickStartSpring.class, args);
}
@GetMapping("/")
public String hello() {
return "OK";
}
}
mvn clean install spring-boot:run
👁️ Expected output
- Access the default URL http://localhost:8080/
You should have a sample OK
in your webpage.
ℹ️ Informations
-
We use
exclude
to avoid Spring-Data-Cassandra to try to connect to Cassandra for now. -
We mark the main class as a rest Controller with
@RestController
. The Spring Boot Web is the dependency need to expose rest endpoint like this -
We create some
hello()
method invoke onGET
when you access the home page/
. If everything is ok the application is now running, it is time to connect it to Astra...with the Starter.
<dependency>
<groupId>com.datastax.astra</groupId>
<artifactId>astra-spring-boot-starter</artifactId>
<version>0.3.4</version>
</dependency>
The purpose of a starter is to initialize the expected beans based on values in application.yaml
(or application.properties
), eventually with custom keys. The starter introduce a set of keys prefixed with astra.*
.
-
Rename
application.properties
toapplication.yaml
. This step is not mandatory but ease the configuration with hierarchical keys. -
Populate
application.yaml
with the following content and replace the values with expected values (how to retrieve the values are explained in the Quickstart Astra
astra:
api:
application-token: <your_token>
database-id: <your_db_id>
database-region: <your_db_region>
cross-region-failback: false
grpc:
enabled: true
cql:
enabled: true
download-scb:
# if disabled zip files must be in folder (path)
enabled: true
# Looking for files scb_dbid-dbregion.zip in folder (default is ~/.astra/scb)
# path: /tmp
driver-config:
basic:
session-keyspace: <your_keyspace>
- Edit the method
hello()
to display something telling theAstraClient
is initialized
@Autowired
private AstraClient astraClient;
@GetMapping("/")
public String hello() {
return astraClient.apiDevopsOrganizations().organizationId();
}
- You can now restart the application
mvn clean install spring-boot:run
👁️ Expected output
ℹ️ Informations
-
Note that we did not provide any secret cloud bundle (zip file) to initialize the component. It as been downloaded for us under the hood.
-
In your IDE, when you edit the file
application.yaml
you should have some autocompletion to edit the values.
As describe in the Spring documentation, there are multiple ways to interact with Cassandra. In this tutorial we will show you how to use all of them
-
Repository Abstraction lets you create repository declarations in your data access layer. The goal of Spring Data’s repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.
-
CassandraTemplate
wraps aCqlTemplate
to provide query result-to-object mapping and the use of SELECT, INSERT, UPDATE, and DELETE methods instead of writing CQL statements. This approach provides better documentation and ease of use.
ℹ️ Connecting Spring Data Cassandra to Astra
Spring Data Cassandra leverages on a CqlSession
bean, all the time. To build the CqlSession
there area again multiple ways described in the documentation from custom code to AbstractCassandraConfiguration
. FORGET ABOUT IT.
Astra Spring Boot Starter creates the CqlSession
bean for you using the keys previously listed as such you do not need to use configuration keys like spring.data.cassandra
(or very very few for special behaviour)
This one is straight forward. Remove the exclude
in @SpringBootApplication
@SpringBootApplication
You can restart the application, spring data is connected to Astra.
- Create a bean
Todos
in the same packagecom.datastax.tutorial
@Table
public class Todos {
@PrimaryKey
@CassandraType(type = Name.UUID)
private UUID uid = UUID.randomUUID();
private String title;
private boolean completed = false;
public Todos() {}
public Todos(String title) { this.title = title; }
//_getters and setters have been omitted here
- Create an interface
TodosRepository
in the same packagecom.datastax.tutorial
package com.datastax.tutorial;
import org.springframework.data.cassandra.repository.CassandraRepository;
public interface TodosRepository extends CassandraRepository<Todos, String> {}
- Edit the
QuickStartSpring
to add the following:
@Autowired
private TodosRepository todoRepository;
@PostConstruct
public void insertTodos() {
todoRepository.save(new Todos("Create Spring Project"));
todoRepository.save(new Todos("Setup Astra Starter"));
todoRepository.save(new Todos("Setup Spring Starter"));
}
@GetMapping("/todos")
public List<Todos> todos() {
return todoRepository.findAll(CassandraPageRequest.first(10)).toList();
}
- Finally tells Spring Data to create for us the tables with configuration. (not for CqlSession, only for this). In
application.yaml
add the following:
spring:
data:
cassandra:
schema-action: CREATE_IF_NOT_EXISTS
- You can restart your application and access http://localhost:8080/todos
[
{
"uid": "83d7a60d-1f24-42c5-aa16-9275f36dc312",
"title": "Setup Spring Starter",
"completed": false
},
{
"uid": "95e8a502-786d-4dd2-983a-b451a12877fe",
"title": "Setup Astra Starter",
"completed": false
},
{
"uid": "44da79c3-73a6-46d0-84cb-3afa2a96d99e",
"title": "Create Spring Project",
"completed": false
}
]
ℹ️ Note: Each time you restart the application you will get 3 new tasks as the primary is an generated UUID.
CassandraTemplate
is the bean initialized by Spring-Data. It embeds the CqlTemplate
= CqlOperations
.
- Add the following to your main class
@Autowired
private CassandraTemplate cassandraTemplate;
@GetMapping("/datacenter")
public String datacenter() {
return cassandraTemplate
.getCqlOperations()
.queryForObject("SELECT data_center FROM system.local", String.class);
}
- You can restart your application and access http://localhost:8080/datacenter
The native java Cassandra driver can expose some metrics using a metrics Registry. The configuration could be found here. The SDK leverage on this configuration to provide the metrics in Spring Actuator
:
Micrometer needs to be in the classpath (provided by spring-boot-starter-actuator
)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Enabled metrics flag in application.yaml
for astra
and set up actuator in management
.
management:
server:
port: 9001
address: 127.0.0.1
endpoints:
web:
exposure:
include: "*"
astra:
application-token: <token>
database-id: <dbid>
database-region: <dbRegion>
keyspace: <keyspace>
metrics:
enabled: true
The Cassandra metrics will now be available at http://localhost:9001/actuator/metrics
and http://localhost:9001/actuator/metrics/{metricsName}.
- To have the prometheus endpoint you need to add the prometheus dependency in the
pom.xml
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
- And update
application.yaml
to expose prometheus:
management:
server:
port: 9001
address: 127.0.0.1
metrics:
export:
prometheus:
enabled: true
endpoints:
web:
exposure:
include: "*"
The Cassandra metrics will now be available at http://localhost:9001/actuator/prometheus
ℹ️ You can download the code here 📥 Download
🏠 Home | Document | Rest | Native Drivers | GraphQL | gRPC | Astra Devops |