Springboot3.3 整合Cassandra 4.1.5的詳細(xì)過程
一、數(shù)據(jù)庫搭建
-- 創(chuàng)建Keyspace
CREATE KEYSPACE school WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 1};
-- 創(chuàng)建表
CREATE TABLE student(
id int PRIMARY KEY,
name text,
age int,
genders int,
address text ,
interest set<text>,
phone list<text>,
education map<text, text>
);二、引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-cassandra</artifactId> </dependency> <!-- hutool是下面多線程導(dǎo)入數(shù)據(jù)引入 --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.26</version> </dependency>
三、配置文件
spring:
application:
name: Spring-Cassandra
cassandra:
keyspace-name: school
contact-points:
- 192.168.204.131:9042
port: 9042
username: ***
password: ******
local-datacenter: datacenter1
request:
timeout: 60s檢查Cassandra的local-datacenter,可執(zhí)行下面命令:
[root@localhost apache-cassandra]# bin/nodetool status

四、創(chuàng)建一個(gè)實(shí)體類:
import lombok.Data;
import org.springframework.data.cassandra.core.mapping.Column;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Data
@Table(value="student")
public class Student implements Serializable {
@PrimaryKey
private Integer id;
@Column("name")
private String name;
@Column("age")
private Integer age;
@Column("genders")
private Integer genders;
@Column("address")
private String address;
@Column("interest")
private Set<String> interest;
@Column("phone")
private List<String> phone;
@Column("education")
private Map<String, String> education;
}五、創(chuàng)建一個(gè)Controller
private final StudentService studentService;
@GetMapping("student")
public List<Student> getStudentByName(String name) {
return studentService.getStudentByName(name);
}
@GetMapping("count")
public Long count() {
return studentService.count();
}
@GetMapping("list")
public List<Student> list(String name) {
Student student = new Student();
student.setName(name);
return studentService.list(student);
}
@GetMapping("save")
public String sava() {
for(int i = 0; i<100; i++) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
int finalI = i;
ThreadUtil.execute(() -> {
System.out.println("線程"+ finalI +"運(yùn)行");
List<Student> list = Lists.newArrayList();
for(int j=0; j<100; j++) {
UUID uuid = UUID.randomUUID();
int hash = uuid.toString().hashCode();
int maxTenDigit = (int) Math.pow(10, 10) - 1; // 10位整數(shù)的最大值
int modHash = Math.abs(hash % maxTenDigit);
Student student = new Student();
student.setId(modHash);
int random = (int) (Math.random() * 100);
student.setName("GG"+ random);
student.setAge(random);
student.setGenders(1);
student.setAddress("China");
list.add(student);
// studentService.save(student);
}
System.out.println("線程"+ finalI +"開始批量插入");
studentService.batchSave(list);
System.out.println("線程"+ finalI +"結(jié)束批量插入");
});
}
System.out.println("線程結(jié)束");
// ThreadUtil.waitForDie();
return "success";
}注意:Cassandra 本身不適合用來做數(shù)據(jù)分析統(tǒng)計(jì),比如 count,是需要去遍歷數(shù)據(jù)庫的,分布式數(shù)據(jù)庫,那么就要通通遍歷一次。小數(shù)據(jù)還可以,數(shù)據(jù)量大會(huì)報(bào)查詢超時(shí)錯(cuò)誤。
六、編寫service查詢數(shù)據(jù)
service接口省略
1、JPA方式查詢
service實(shí)現(xiàn)
private final StudentMapper studentMapper;
@Override
public List<Student> getStudentByName(String name) {
return studentMapper.getStudentByName(name);
}mapper接口
@Query(value = "select id, address, age, genders, name, interest, phone, education from student where name = ?0 ALLOW filtering") List<Student> getStudentByName(String name);
Allow filtering:
如果你的查詢條件里,有一個(gè)是根據(jù)索引查詢,那其它非索引非主鍵字段,可以通過加一個(gè)ALLOW FILTERING來過濾實(shí)現(xiàn);
雖然查詢非索引非主鍵字段,但是只要加了ALLOW FILTERING條件,它會(huì)先根據(jù)索引查出來的值,再對(duì)結(jié)果進(jìn)行過濾;
(如果不加ALLOW FILTERING,而又有非索引列,這樣是不允許的; 加上ALLOW FILTERING,相當(dāng)于在結(jié)果后再進(jìn)行過濾。)

2、CassandraTemplate方式查詢
private final CassandraTemplate cassandraTemplate;
@Override
public List<Student> list(Student queryInfo) {
Query query = Query
.query(where("name").is(queryInfo.getName()));
query = query.withAllowFiltering();
query = query.columns(Columns.from("id", "name", "age", "address", "genders", "interest", "phone", "education"));
System.out.println(query);
return this.cassandraTemplate.select(query, Student.class);
}
@Override
public void save(Student student) {
this.cassandraTemplate.insert(student);
}
/**
* 批量插入
*/
@Override
public void batchSave(List<Student> list) {
CassandraBatchOperations batchOps = cassandraTemplate.batchOps();
batchOps.insert(list);
batchOps.execute();
}
@Override
public Long count() {
return cassandraTemplate.count(Student.class);
}到此這篇關(guān)于Springboot3.3 整合Cassandra 4.1.5的文章就介紹到這了,更多相關(guān)Springboot整合Cassandra內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
@AutoConfigurationPackage與@ComponentScan注解區(qū)別
這篇文章主要介紹了@AutoConfigurationPackage與@ComponentScan注解區(qū)別,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
Java使用Flyway實(shí)現(xiàn)數(shù)據(jù)庫版本控制的技術(shù)指南
在現(xiàn)代應(yīng)用開發(fā)中,數(shù)據(jù)庫結(jié)構(gòu)經(jīng)常隨著業(yè)務(wù)需求不斷演變,使用手動(dòng)SQL腳本管理數(shù)據(jù)庫版本,不僅容易出現(xiàn)錯(cuò)誤,還難以跟蹤和回滾,Flyway是一個(gè)強(qiáng)大的數(shù)據(jù)庫遷移工具,能夠幫助開發(fā)者高效管理和自動(dòng)化數(shù)據(jù)庫的版本控制,本文將介紹Flyway的基本功能及其在SpringBoot項(xiàng)目中的實(shí)踐2025-02-02
如何解決線程太多導(dǎo)致java socket連接池出現(xiàn)的問題
這篇文章主要介紹了如何解決線程太多導(dǎo)致socket連接池出現(xiàn)的問題,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
SpringBoot整合JWT框架,解決Token跨域驗(yàn)證問題
Json web token (JWT), 是為了在網(wǎng)絡(luò)應(yīng)用環(huán)境間傳遞聲明而執(zhí)行的一種基于JSON的開放標(biāo)準(zhǔn)((RFC 7519).定義了一種簡潔的,自包含的方法用于通信雙方之間以JSON對(duì)象的形式安全的傳遞信息。2021-06-06
Spring中BeanFactory接口的作用小結(jié)
BeanFactory是Spring IOC核心接口,負(fù)責(zé)管理Bean的實(shí)例化、配置與生命周期,通過配置類構(gòu)建BeanDefinition,注冊(cè)并解析注解,實(shí)現(xiàn)依賴注入,確保Bean正確加載與管理,本文就來詳細(xì)介紹一下,感興趣的可以了解一下2025-09-09
SpringBoot集成Sa-Token實(shí)現(xiàn)權(quán)限認(rèn)證流程入門教程
本文詳解SpringBoot集成Sa-Token框架的入門步驟,涵蓋依賴添加、配置設(shè)置、攔截器注冊(cè)、權(quán)限角色邏輯定義、設(shè)備工具類創(chuàng)建及登錄/注銷功能改造,通過注解實(shí)現(xiàn)鑒權(quán),解決權(quán)限認(rèn)證問題,感興趣的朋友跟隨小編一起看看吧2025-09-09

