一、数据库搭建
-- 创建Keyspace
CREATE KEYSPACE school WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 1};-- 创建表
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是下面多线程导入数据引入 -->
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.26</version>
</dependency>
三、配置文件
spring:application:name: Spring-Cassandracassandra:keyspace-name: schoolcontact-points:- 192.168.204.131:9042port: 9042username: ***password: ******local-datacenter: datacenter1request:timeout: 60s
检查Cassandra的local-datacenter,可执行下面命令:
[root@localhost apache-cassandra]# bin/nodetool status
四、创建一个实体类:
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 {@PrimaryKeyprivate 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;
}
五、创建一个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 +"运行");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位整数的最大值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 +"结束批量插入");});}System.out.println("线程结束");
// ThreadUtil.waitForDie();return "success";
}
注意:Cassandra 本身不适合用来做数据分析统计,比如 count,是需要去遍历数据库的,分布式数据库,那么就要通通遍历一次。小数据还可以,数据量大会报查询超时错误。
六、编写service查询数据
service接口省略
1、JPA方式查询
service实现
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:
如果你的查询条件里,有一个是根据索引查询,那其它非索引非主键字段,可以通过加一个ALLOW FILTERING来过滤实现;
虽然查询非索引非主键字段,但是只要加了ALLOW FILTERING条件,它会先根据索引查出来的值,再对结果进行过滤;
(如果不加ALLOW FILTERING,而又有非索引列,这样是不允许的; 加上ALLOW FILTERING,相当于在结果后再进行过滤。)
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);
}