Skip to content

Spring Boot Starter QuickStart

Cedrick Lunven edited this page Sep 23, 2022 · 9 revisions

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

📋 Table of content

  1. Prerequisites
  2. Create your project with Initializr
  3. Setup your project
  4. Configuration
  5. Working with Spring Data Cassandra
  6. Working with Spring Actuator
  7. Working with Spring Security

1. Prerequisites

📦 Java Development Kit (JDK) 8

java --version

📦 Apache Maven

mvn -version

📦 An astra Instance

  • In the Quickstart-Astra, the procedure to create an instance has been described. Please follow the instructions
  • Note your databaseId, databaseRegion and the keyspace you used.

📦 An Astra Token

  • In the Quickstart-Astra, the procedure to create a token has been described. Please follow the instructions
  • Note your token (it should look like AstraCS:...)

2. Create your project with Spring Initializr

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 and Spring Data for Cassandra

3. Setup your project

✅ Step 3a. Import the application in your favorite IDE.

Do not try to start the application immediately, it would fail. We did not tell how to connect to Cassandra yet.

  • Rename class SdkQuickstartSpringApplication to QuickStartSpring

✅ Step 3b. Fix your application

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"; 
  }
}

✅ Step 3c. Start the application

mvn clean install spring-boot:run

👁️ Expected output

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 on GET 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.

4. Configuration

✅ Step 4a. Add the starter dependency

  • Add the latest version Maven Central of astra-spring-boot-starter in the project.
<dependency>
  <groupId>com.datastax.astra</groupId>
  <artifactId>astra-spring-boot-starter</artifactId>
  <version>0.3.4</version>
</dependency>

✅ Step 4b. Configure the starter in application.yaml

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 to application.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>

✅ Step 4c. Change the controller

  • Edit the method hello() to display something telling the AstraClient 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.

5. Spring Data Cassandra

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 a CqlTemplate 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)

✅ Step 5a. Spring Data Cassandra Connectivity

This one is straight forward. Remove the exclude in @SpringBootApplication

@SpringBootApplication

You can restart the application, spring data is connected to Astra.

✅ Step 5b. Working with CassandraRepository<BEAN,KEY>

  • Create a bean Todos in the same package com.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 package com.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
[
 {
  "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.

✅ Step 5c. Working with CqlTemplate and CassandraTemplate

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);
}

6. Spring Actuator integration

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 :

✅ Step 6a. Enabled Metrics Support

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}.

✅ Step 6b. Prometheus Integration

  • 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

Clone this wiki locally