--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)
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
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
cqlsh
Resume from here The explanation of detailed options is omitted here. .. ..
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;
USE sample
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;
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.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
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;
}
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
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 under
spring.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 under
spring.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);
}
}
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