Build a Spring Java Microservice With Apache Cassandra
Build a Spring Java Microservice With Apache Cassandra
YouTube
Twitch
Discord
YouTube
Runtime: dtsx.io/workshop Quizz: menti.com
Disclaimer
5
Hands-on exercise material
- Get your Astra instance here:
- http://dtsx.io/workshop
- Github repo:
- https://github.com/DataStax-Academy/Spring-boot-todo-app
- Driver documentation:
- https://docs.datastax.com/en/developer/java-driver/4.9/
6
menti.com
87 51 69
Intro to Cassandra for Developers
➔ Demo !
➔ Introduction to Astra
➔ Introduction to Spring and Spring Boot
➔ Plan the Spring Application
➔ Working with Datastax drivers
➔ Build and test the basic CRUD app
What do you do when
you need to learn a new
language ?
9
10
Demo
11
Intro to Cassandra for Developers
➔ Demo
➔ Introduction to Astra
➔ Introduction to Spring and Spring Boot
➔ Plan the Spring Application
➔ Working with Datastax drivers
➔ Build and test the basic CRUD app
Introduction to Astra
==
Fully managed Cassandra
Without the ops!
13
DataStax Astra
15
Get the secure bundle with curl
16
Intro to Cassandra for Developers
➔ Demo !
➔ Introduction to Astra
➔ Introduction to Spring and Spring Boot
➔ Plan the Spring Application
➔ Working with Datastax drivers
➔ Build and test the basic CRUD app
Inversion of control : Know only the interface
18
spring.io
19
The Spring Framework provides a comprehensive programming and configuration model
for modern Java-based enterprise applications - on any kind of deployment platform.
spring.io
Core technologies Dependency injection, events, resources, i18n, validation, data binding, AOP.
20
21
Spring Boot Presentation Layer
(Rest API, Controller)
- Create stand-alone Spring applications Inversion of Control
- externalized configuration
Databases
22
Vocabulary
23
Intro to Cassandra for Developers
➔ Demo
➔ Introduction to Astra
➔ Introduction to Spring and Spring Boot
➔ Plan the Spring Application
➔ Working with Datastax drivers
➔ Build and test the basic CRUD app
What is a microservice?
Microservices - also known as the microservice architecture - is an architectural
style that structures an application as a collection of services that are
- Highly maintainable and testable
- Loosely coupled
- Independently deployable
- Organized around business capabilities
- Owned by a small team
The microservice architecture enables the rapid, frequent and reliable delivery of
large, complex applications. It also enables an organization to evolve its
technology stack. source: https://microservices.io/
25
Microservices, All things distributed
Monolith Multi-Tiers SOA Modern Applications
Service
API Gateway Service Mesh
Discovery
ESB
Services Backend SOA Service Service Service Service Microservices
Service Service Service
Service Service Service Service
26
Microservices in a nutshell Martin Fowler
Principles:
✔ Organized around Business Capabilities
✔ Products not Projects
✔ Smart endpoints and dumb pipes
✔ Decentralized Governance
✔ Decentralized Data Management
✔ Infrastructure Automation
✔ Design for failure
✔ Evolutionary Design
ADVANTAGES DISADVANTAGES
-
• Reduce Cost (Scaling, Design) • Complexity (Security, Transaction, Orchestration)
27
Apache Cassandra MicroServices
• REALTIME REQUESTS & SCALABILITY AT CORE
• DISTRIBUTED ARCHITECTURES
– From ACID to BASE (Basic Availability, Soft-State, Eventual Consistency)
– Implementations: CQRS, Event Sourcing
– Colocate service and Data
• DECOUPLING BY DESIGN
– 1 KEYSPACE = DOMAIN
– 1 QUERY = 1 TABLE
28
28
What service are we building? A ToDo Service
29
The REST Api
30
The full ToDo app architecture
Swagger
Spring-Web
TodoListRepository
todobackend-cassandra
31
The main data entity? Tasks
Tasks
● Task UUID
● title
● completed flag
● order
32
Designing the Cassandra datamodel
Entities & Relationships
Queries
33
The final task model
34
The ToDoRepository
public interface TodoListRepository {
...
35
What are the queries? CRUD for ToDos
List all tasks
Mark a task as
completed/uncomplete
Delete a task
Delete all
36
The ToDoListRepository
public interface TodoListRepository {
...
/**
* Find a task from its unique identifier.
*/
Optional<Todo> findById(UUID uid);
/**
* Create a new {@link Todo} providing only a title.
*/
void upsert(Todo title);
/**
* Delete a task identifier
*/
void delete(UUID uid);
...
37
Intro to Cassandra for Developers
➔ Demo
➔ Introduction to Astra
➔ Introduction to Spring and Spring Boot
➔ Plan the Spring Application
➔ Working with Datastax drivers
➔ Build and test the basic CRUD app
Connecting the REST Api to Astra
39
Contact points with Astra
SecureConnectBundle
40
Datastax Drivers One of set drivers to connect them all - January 2020
41
Working with the driver: Open a session
// Explicit Settings
.withCloudSecureConnectBundle(Paths.get("/tmp/secure-connect-bundle.zip"))
.withKeyspace("todoapp")
.withAuthCredentials("KVUser", "KVPassword")
.build();
42
File based driver configuration application.conf
datastax-java-driver {
basic {...
Based on Typesafe Config session-keyspace = killrvideo
43
Open a session with app.conf
44
Important about the CqlSession
45
Hands-on Exercise 1:
Test the connection to Astra
mvn test
-Dtest=com.datastax.examples.ConnectivityToAstraExplicitTest#should_connect_to_Astra_static
mvn test
-Dtest=com.datastax.examples.ConnectivityToAstraWithConfTest#should_connect_to_Astra_withConfig
46
Working with the driver: Execute queries
Statement
47
Working with the driver: Simple Statements
Statement statement = …
cqlSession.execute(statement);
48
Working with the driver:
Prepare and bind a statement
- Compiled once on each node automatically as needed
- Prepare each statement only once per application
- Use one of the many bind variations to create a BoundStatement
cqlSession.execute(bound);
49
Working with the driver: ResultSets
- ResultSet is the object returned for executing query. It contains ROWS (data) and
EXECUTION INFO.
- ResultSet is iterable and as such you can navigate from row to row.
- Results are always paged for you (avoiding memory and response time issues)
ResultSet rs = cqlSession.execute(myStatement);
// Plumbery
ExecutionInfo info = rs.getExecutionInfo();
int executionTime = info.getQueryTrace().getDurationMicros();
// Data: NOT ALL DATA RETRIEVED IMMEDIATELY (only when needed .next())
Iterator<Row> iterRow = rs.iterator();
int itemsFirstCall = rs.getAvailableWithoutFetching();
50
Parsing ResultSets
// We know there are not so many results we can get all (fetch all pages)
List<Row> allRows = resultSet.all();
// Browse iterable
for(Row myRow : resultSet.iterator()) {
// .. Parsing rows
}
// Use Lambda
rs.forEach(row -> { row.getColumnDefinitions(); });
51
Parsing Rows
// Sample row
Row row = resultSet.one();
52
Hands-on Exercise 2:
Set up schema and test inserts
53
Intro to Cassandra for Developers
➔ Demo
➔ Introduction to Astra
➔ Introduction to Spring and Spring Boot
➔ Plan the Spring Application
➔ Working with Datastax drivers
➔ Build and test the basic CRUD app
Building the REST API with Spring Boot
@Repository("todobackend.repo.cassandra-driver")
public interface TodoRepository { public class TodoListRepositoryCassandraDriverImpl
//schema definition implements TodoListRepository {
//query definitions
} @Autowired
public CqlSession cqlSession;
@Configuration
@RestController
public class CassandraDriverConfig {
@RequestMapping("/api/v1/todos")
@Bean
public class TodoListRestController {
public CqlSession cqlSession() {
@Autowired
return CqlSession.builder().build();
@Qualifier("todobackend.repo.cassandra-dri
}
ver")
}
private TodoListRepository todoRepository;
...
}
55
Hands-on Exercise 3:
Configure and run the application
mvn spring-boot:run
56
Hands-on Exercise 4:
Test CRUD with Swagger
57
menti.com
87 51 69
Bonus Exercise:
Test with Todo MVC, client GUI and API specs
59
Learn more?
Micro-service REST Micro-service GraphQL
https://bit.ly/31RL62I https://bit.ly/2MVicup
https://bit.ly/2pofk0b https://bit.ly/2JwsFdM
60
61