Getting started with Apache Cassandra in Spring Boot

Reading Time: 3 minutes

What is Cassandra ?

Cassandra is a NoSQL database which is a highly scalable, high-performance distributed database designed to handle large amounts of data across many commodity servers. It  provides high availability with no single point of failure. It is provided by Apache written in JAVA.

cassandra

Apache Cassandra is the only distributed NoSQL database that delivers the always-on availability, blisteringly fast read-write performance, and unlimited linear scalability needed to meet the demands of successful modern applications.

Some biggest companies using Cassandra such as Facebook, Twitter, Cisco, Rackspace, Twitter, Netflix, and more.

Features of Cassandra

Cassandra has become so popular because of its outstanding technical features.

  • Scalability:  Cassandra enables you to scale horizontally by simply adding more nodes to the cluster. For example, four nodes can handle 200,000 transactions/second, eight nodes will be able to handle 400,000 transactions/second.
  • Flexible, familiar interface: The Cassandra Query Language (CQL) is similar to SQL. That means most developers should have a fairly easy time becoming familiar with it.
  • Easy data distribution − It provides the flexibility to distribute data where you need by replicating data across multiple data centers.
  • High performance: With Cassandra, no single node is in charge of replicating data across a cluster. Instead, every node is capable of performing all read and write operations. This improves performance and adds resiliency to the database.
  • Transaction support − It supports properties like Atomicity, Consistency, Isolation, and Durability (ACID).
  • Active everywhere with zero downtime: Every Cassandra node is capable of performing read and write operations, data is quickly replicated across hybrid cloud environments and geographies. If a node fails, users will automatically routed to the nearest healthy node. They won’t even notice that a node has been knocked offline because applications behave as designed even in the event of failure. As a result, applications are always available and data is always accessible and never lost.

Let’s create a simple API

First Lets create an account on datastax to use Apache Cassandra for free. And then create the database and keyspace.

Add add the dependencies in the pom.xml, with Maven:

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-cassandra</artifactId>
      <version>2.6.4</version>
    </dependency>

Configure application.properties and add following lines.

spring.data.cassandra.keyspace-name = <YOUR KEYSPACE NAME>
spring.data.cassandra.username = <YOUR USERNAME>
spring.data.cassandra.password = <YOUR PASSWORD>
spring.data.cassandra.schema-action = recreate-drop-unused

astra.db.id = <DATABASE ID FROM DATASTAX>
astra.db.region = westus2
astra.db.keyspace = <YOUR KEYSPACE NAME>
astra.db.application.token = <GENERATED TOKEN FROM DATASTAX>

datastax.astra.secure-connect-bundle = secure-connect.zip
// You have to Download your Secure Connect Bundle from datastax and paste it to under src/main/resources folder

Creating CassandraRepository, we have define an interface named EmployeeRepository which extends CassandraRepository with the Employee as the target Cassandra table, and String as the type of its primary key. :

@Repository
public interface EmployeeRepository extends CassandraRepository<Employee, String> {
}

Let’s have a quick look at the entity – the model class we’re going to be using. for example

@Table(value = "employees")
public class Employee {
    @PrimaryKeyColumn(name = "employee_id", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
    private String id;
    @PrimaryKeyColumn(name = "department", ordinal = 1, type = PrimaryKeyType.CLUSTERED)
    private String department;
    @CassandraType(type = CassandraType.Name.TEXT)
    private String name;
    
    public Employee(String id, String department, String name) {
        this.id = id;
        this.department = department;
        this.name = name;
    }
    // getters and setters
}

Let’s create a simple controller and creates a new entry in database.

@RestController
@RequestMapping("/employees")
public class EmployeeController {
    private final EmployeeRepository repository;
    
    public EmployeeController(EmployeeRepository repository) {
        this.repository = repository;
    }
    @GetMapping
    public List<Employee> getEmployee() {
        return repository.findAll();
    }
    
    @GetMapping("/add")
    public Employee addEmployee(){
        return repository.save(new Employee("emp-15","Java","Aasif Ali"));
    }
}

We need to define some configuration for Datastax to get the secure connect bundle. such as given below.

@Configuration
@ConfigurationProperties(prefix = "datastax.astra")
public class DataStaxAstraProperties {
    private File secureConnectBundle;
    
    public File getSecureConnectBundle() {
        return secureConnectBundle;
    }
    
    public void setSecureConnectBundle(File secureConnectBundle) {
        this.secureConnectBundle = secureConnectBundle;
    }
}

Add these lines to your main class.

/**
* This is necessary to have the Spring Boot app use Astra secure bundle
* to connect to the database.
* @param astraProperties
* @return
*/
@Bean
public CqlSessionBuilderCustomizer sessionBuilderCustomizer(
			DataStaxAstraProperties astraProperties) {
		Path bundle = astraProperties.getSecureConnectBundle().toPath();
		return builder -> builder.withCloudSecureConnectBundle(bundle);
	}

Output

Written by 

Aasif Ali is a Software Consultant at Knoldus Inc. He has done Post Graduation from Quantum University Roorkee. He has the knowledge of various programming languages. He is passionate about Java development and curious to learn Java Technologies. He is always impatient and enthusiastic to learn new things. He is a quick learner, problem solver and always enjoy to help others. His hobbies are watching Sci-fi movies , Playing badminton and listening to songs.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading