[JAVA] Cassandra x Spring Boot struggle record

Summary of this article

--Since I have never touched Cassandra, it is a record when I tried to build ~ Spring Boot application to reference / update --The environment is a local PC (Mac)

reference

Cassandra: http://cassandra.apache.org/doc/latest/ SpringDataCassandra: https://spring.io/projects/spring-data-cassandra property Setting item: https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#data-properties

Building Cassandra

Installation

#Cassandra body
brew install cassandra
# CQL(Cassandra Query Language)
brew install cql

Start-up

cassandra -f

Connection error: ('Unable to connect to any servers', {'127.0.0.1': error(61, "Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")})

It doesn't move. .. .. In my case, it seems that JAVA_HOME shouldn't point to the Java 11 directory. .. .. After redefining it, it will start up safely!

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home/
cassandra -f

Start with Homebrew anyway!

vi /usr/local/etc/cassandra/cassandra-env.sh
#"Export JAVA" at the end_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home/Added

brew services start cassandra

Connect!

cqlsh

cqlsh localhost 9042 With this

Let's play Cassandra alone for a moment

cqlsh

Resume from here The explanation of detailed options is omitted here. .. ..

Add KeySpace

Concept corresponding to Database in MySQL and Oracle

-- #Before adding keyspace
DESCRIBE keyspaces
-- system_traces  system_schema  system_auth  system  system_distributed

-- #Added "sample" keyspace
CREATE KEYSPACE sample WITH REPLICATION = {'class':'SimpleStrategy','replication_factor':1};

-- #Before adding keyspace
DESCRIBE keyspaces
-- system_schema  system_auth  system  sample  system_distributed  system_traces

By the way, the deletion is

DROP KEYSPACE sample;

Move Database

USE sample

Creating a table

Here, we simply assume data with Key and Value.

--Create
CREATE TABLE t_sample (key text PRIMARY KEY, value text);

--Check the list
DESCRIBE tables;

--Check table definition
DESCRIBE table t_sample;

By the way, the deletion is

DROP TABLE t_sample;

Data manipulation

Using the t_sample table created earlier

--Reference (empty)
select * from t_sample;

--Reference (equivalent to above)
select key, value from t_sample;

--Registration
INSERT INTO t_sample (key, value) VALUES ('key1', 'value1');

--Registration (duplicate)
--The query is successful and behaves like an update
INSERT INTO t_sample (key, value) VALUES ('key1', 'value2');

--update
UPDATE t_sample SET value = 'value3' WHERE key = 'key1';

--Delete
DELETE FROM t_sample WHERE key = 'key1';

It's my first experience to be updated instead of being played if I violate the primary

Build Spring application

project creation

build.gradle


plugins {
    id 'org.springframework.boot' version '2.2.4.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-cassandra'
    //webflux is for operation check
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    compileOnly('org.projectlombok:lombok')
    annotationProcessor('org.projectlombok:lombok')
}

application.yml


spring:
  data:
    cassandra:
      keyspace-name: sample

Create model class for table

Sample.java


import lombok.Value;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;

@Data
@Table("t_sample")
public class Sample {
    @PrimaryKey
    private String key;
    private String value;
}

Try to register / reference / delete

Application.java


@Slf4j
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        //SpringApplication.run(Application.class);

        Cluster cluster = Cluster.builder()
                .addContactPoints("localhost")
                .withoutJMXReporting()  //Error if not attached
                .build();
        Session session = cluster.connect("sample");

        var template = new CassandraTemplate(session);
        var data = new Sample("key1", "value1");

        template.insert(data);
        //Search all
        var selected = template.select("SELECT * from t_sample", Sample.class);
        log.info("selected: {}", selected);
        //update
        data = new Sample("key1", "value2");
        template.update(data);
        //Conditional search
        selected = template.select(Query.query(Criteria.where("key").is("key1")), Sample.class);
        log.info("selected: {}", selected);
        //Delete (PK specified)
        template.deleteById("key1", Sample.class);
        //Get the number
        var count = template.count(Sample.class);
        log.info("count: {}", count);

        //Connection closed
        session.close();
        cluster.close();
    }
}

The following error occurred unless .withoutJMXReporting () was described.

Exception in thread "main" java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter

Try to make it look like a web application

First of all, investigate how much "spring-boot-starter-data-cassandra" will register beans

Cluster

--ʻOrg.springframework.boot.autoconfigure.cassandra.CassandraAutoConfigurationis registered as a bean --It seems good to set properties underspring.data.cassandra --spring.data.cassandra.keyspace-name = sample`

Session

――Is it Session or Session Factory? --ʻOrg.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfigurationis registered as a bean --This also seems to reflect the settings underspring.data.cassandra`

CassandraTemplate

--Similar to Session, ʻorg.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration` is registered as a bean.

Conclusion ... Suddenly use Cassandra Template and it's OK!

CassandraController.java


@RequiredArgsConstructor
@RestController
public class CassandraController {
    private final CassandraTemplate template;

    // curl localhost:8080
    @GetMapping("")
    public List<Sample> all() {
        return template.select("SELECT * FROM t_sample", Sample.class);
    }

    // curl localhost:8080/key1
    @GetMapping("/{key}")
    public Sample getByKey(@PathVariable String key) {
        return template.selectOneById(key, Sample.class);
    }

    // curl localhost:8080/insert -d '{"key":"key1","value":"value1"}' -X PATCH -H 'Content-Type: application/json'
    @PatchMapping("/**")
    public Sample patch(@RequestBody Sample sample) {
        return template.insert(sample);
    }

    // curl localhost:8080/key1 -X DELETE
    @DeleteMapping("/{key}")
    public Boolean delete(@PathVariable String key) {
        return template.deleteById(key, Sample.class);
    }
}

Reactive support

Just use ReactiveCassandraTemplate! Don't forget to change the return type to Flux or Mono! (It is also OK as a publisher at once)

ReactiveCassandraController.java


@RequiredArgsConstructor
@RestController
@RequestMapping("/reactive")
public class ReactiveCassandraController {
    private final ReactiveCassandraTemplate template;

    // curl localhost:8080/reactive
    @GetMapping("")
    public Flux<Sample> all() {
        return template.select("SELECT * FROM t_sample", Sample.class);
    }

    // curl localhost:8080/reactive/key1
    @GetMapping("/{key}")
    public Mono<Sample> getByKey(@PathVariable String key) {
        return template.selectOneById(key, Sample.class);
    }

    // curl localhost:8080/reactive/insert -d '{"key":"key1","value":"value1"}' -X PATCH -H 'Content-Type: application/json'
    @PatchMapping("/**")
    public Mono<Sample> patch(@RequestBody Sample sample) {
        return template.insert(sample);
    }

    // curl localhost:8080/reactive/key1 -X DELETE
    @DeleteMapping("/{key}")
    public Mono<Boolean> delete(@PathVariable String key) {
        return template.deleteById(key, Sample.class);
    }

}

Recommended Posts

Cassandra x Spring Boot struggle record
SPRING BOOT learning record 01
SPRING BOOT learning record 02
Spring Boot 2.x context path settings
Use cache with EhCashe 2.x with Spring Boot
Challenge Spring Boot
Spring Boot Form
Spring Boot Memorandum
gae + spring boot
Use Servlet filter in Spring Boot [Spring Boot 1.x, 2.x compatible]
[Java] Hello World with Java 14 x Spring Boot 2.3 x JUnit 5 ~
LINE Bot x Java (Spring Boot) construction procedure
Spring Boot + Heroku Postgres
Spring boot memo writing (1)
A memorandum of addiction to Spring Boot2 x Doma2
First Spring Boot (DI)
Spring Boot2 cheat sheet
Spring Boot exception handling
Spring Boot Servlet mapping
Spring boot development-development environment-
Spring Boot learning procedure
SSO with GitHub OAuth in Spring Boot 1.5.x environment
Learning Spring Boot [Beginning]
Spring boot memo writing (2)
Spring Boot 2.2 Document Summary
[Spring Boot] DataSourceProperties $ DataSourceBeanCreationException
Spring Boot 2.3 Application Availability
Spring boot tutorials Topics
Download with Spring Boot
Spring Boot 1.x will reach EOL in the next year.
[Spring Boot] Environment construction (macOS)
Set context-param in Spring Boot
Try Spring Boot from 0 to 100.
Generate barcode with Spring Boot
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Spring Boot tutorial task schedule
Spring 5 & Spring Boot 2 Hands-on preparation procedure
Get started with Spring boot
Hello World with Spring Boot!
Spring Boot 2 multi-project in Gradle
[Spring Boot] Web application creation
spring boot port duplication problem
Run LIFF with Spring Boot
SNS login with Spring Boot
Spring Boot Hot Swapping settings
[Java] Thymeleaf Basic (Spring Boot)
Introduction to Spring Boot ① ~ DI ~
File upload with Spring Boot
Spring Boot starting with copy
Introduction to Spring Boot ② ~ AOP ~
CICS-Run Java application-(4) Spring Boot application
Spring Boot starting with Docker
Spring Boot + Springfox springfox-boot-starter 3.0.0 Use
Spring Boot DB related tips
Hello World with Spring Boot
Set cookies with Spring Boot
[Spring Boot] Easy paging recipe
Use Spring JDBC with Spring Boot
Docker × Spring Boot environment construction
Major changes in Spring Boot 1.5