Apache Cassandra是一个分布式数据库管理系统,是为了处理多个数据中心和云端的大量数据而建立的。本指南将指导你使用模块Spring Data Cassandra和Spring Boot与Cassandra数据库(如Astra DB)合作的过程。
目录
- 1.先决条件
- 2.创建一个Spring Boot应用程序
- 3.设置Cassandra数据库
- 4.卡桑德拉配置
- 5.连接到Cassandra
- 6.用CassandraRepository访问数据
- 7.启用过滤功能
- 8.结论
1.先决条件
在开始之前,确保我们在系统中安装了以下东西。
- 我们最喜欢的IDE
- Maven 3.2+
- JDK 11或更高版本
2.创建一个Spring Boot应用程序
- 转到start.spring.io。
- 选择Maven项目和Java。
- 选择你的项目名称。
- 点击依赖性,选择Spring Data for Apache Cassandra。
之后,配置应该如下所示。
现在,生成项目并将其下载到我们的电脑上。此外,我们需要解压缩档案,用我们最喜欢的IDE打开它。例如,我们将使用IntelliJ IDEA。
如果我们检查pom.xml文件,我们将看到以下Cassandra的依赖关系。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>
3.设置卡桑德拉数据库
在开始编码之前,我们将需要一个Cassandra数据库来连接。在这个例子中,我们将使用DataStax Astra Cassandra-as-a-Service的免费层。按照以下链接中的说明,创建数据库和名为spring_cassandra的钥匙空间。
之后,我们需要在pom.xml文件中添加astra-spring-boot-starter依赖项。它有助于将应用程序与ASTRA数据库连接起来。
<dependency>
<groupId>com.datastax.astra</groupId>
<artifactId>astra-spring-boot-starter</artifactId>
<version>0.3.1</version>
</dependency>
4.Cassandra配置
接下来,我们应该在application.properties文件中配置数据库连接属性。每个提供商都提供其特定的属性,所以这些属性可能会根据Cassandra服务提供商的不同而不同。
# Credentials to Astra DB
astra.client-id= <client-id>
astra.client-secret= <client-secret>
astra.application-token= <application-token>
# Select an Astra instance
astra.cloud-region= <region>
astra.database-id= <database-id>
astra.keyspace= spring_cassandra
#timeout configs
spring.data.cassandra.request.timeout=60s
spring.data.cassandra.connection.connect-timeout=60s
spring.data.cassandra.connection.init-query-timeout=60s
下面给出了一个等效的Java配置。我们可以用 AbstractCassandraConfiguration进行扩展,并覆盖特定的Bean以进行特定的配置。
import com.datastax.astra.boot.autoconfigure.AstraClientProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
@Configuration
@EnableCassandraRepositories(basePackages = {"com.howtodoinjava.cassandrademo"})
public class CassandraConfig extends AstraClientProperties {
@Override
public String getClientId() {
return "<Your_Client_Id>";
}
@Override
public String getApplicationToken() {
return "<Your_Application_Token>";
}
@Override
public String getClientSecret() {
return "<Your_Client_Secret>";
}
@Override
public String getCloudRegion() {
return "<Your_cloudRegion>;
}
@Override
public String getDatabaseId() {
return "<Your_database_id>";
}
@Override
public String getKeyspace() {
return "spring_cassandra";
}
}
spring.data.cassandra.schema-action 属性定义了启动时要采取的模式行动。它可以有以下值。
none(建议用于生产) - 不采取任何模式行动。create- 根据需要创建每个表。create-if-not-exists- 必要时创建每个表。recreate- 根据需要创建每一个表,如果表存在的话,先把它丢掉。recreate-drop-unused- 删除关键空间中的所有表,然后根据需要创建每个表。
我们正在使用create-if-not-exists ,为这个演示创建所需的模式。
该 @EnableCassandraRepositories是一个特殊的Cassandra注解,它将扫描包(在我们的例子中是我们在 "basePackages"中指定的包)中的Cassandra存储库,如下一节中指定的存储库。
此外,我们可以指定连接到Cassandra数据库的超时设置。
5.连接到Cassandra
5.1.实体
我们已经创建了Book类,它作为一个实体用于持久化。注释@Table ,将这个实体映射到一个Cassandra表。我们正在使用UUID作为主键。
@Table
public class Book {
@PrimaryKey
private UUID id;
private String title;
private String author;
// getters, setters, constructor, toString method
}
5.2.CassandraRepository配置
接下来,我们要创建一个@Repository,提供在数据库中执行基本CRUD操作的最常用方法。注意,Spring Data Cassandra内部使用CassandraTemplate 来执行SELECT查询。我添加了额外的查询findBookByTitle,注解为 @AllowFiltering.
import org.springframework.data.cassandra.repository.AllowFiltering;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
public interface BookRepository extends CassandraRepository<Book, Long> {
@AllowFiltering
Book findBookByTitle(String title);
}
6.用CassandraRepository访问数据
现在是测试连接的时候了。我们正在使用CommandLineRunner,它在应用程序启动后执行给定的代码。我们将在数据库中插入一些书籍。然后我们将选择一本书并更新它。之后,我们将删除一本,并从数据库中选择所有的书。
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.util.Arrays;
@SpringBootApplication
public class AccessingDataCassandraApplication {
public static void main(String[] args) {
SpringApplication.run(AccessingDataCassandraApplication.class, args);
}
@Bean
public CommandLineRunner clr(BookRepository bookRepository) {
return args -> {
// save books in the database
bookRepository.saveAll(Arrays.asList(
new Book(1L,"War and Peace", "Tolstoy"),
new Book(2L,"Harry Potter", "Rowling, J.K."),
new Book(3L,"Anna Karenina", "Tolstoy")
));
// select only on book
Book harryPotter = bookRepository.findBookByTitle("Harry Potter");
// modify the selected book
harryPotter.setTitle("Harry Potter and the Philosopher's Stone");
bookRepository.save(harryPotter);
//delete the book with id 1
bookRepository.deleteById(1L);
//get all the books
bookRepository.findAll().forEach(System.out::println);
};
}
}
控制台中的输出是。
7.启用过滤功能
如果你要搜索非等价物,Cassandra必须做一个全表扫描。因此,Cassandra没有执行上述操作,而是以警告的方式使请求失败。在这里,我们需要在接口方法上注解并标记为 @AllowFiltering来ping Spring Data Cassandra,使其发送过滤查询并允许数据库执行。
为了更好地理解*@AllowFiltering*注解的作用,让我们试着在没有它的情况下运行代码。如果你这样做,你会得到以下错误。
带有这样的信息。不能执行这个查询,因为它可能涉及到数据过滤,因此可能有不可预测的性能。如果你想在性能不可预测的情况下执行这个查询,请使用ALLOW FILTERING。
通过这条信息,Cassandra告诉我们,我们想执行一个可能有性能问题的、结果不可预测的查询。
不建议使用ALLOW FILTERING,除非你确信该表中只包含非常小的数据集。在大数据上使用它可能会有性能问题。
8.8.结论
现在开始在你的个人项目中玩Cassandra一点都不难。Cassandra是非常有用的,是一个非常好的学习技能,对你作为一个开发者的职业生涯是非常完美的。
祝你学习愉快!!
这个帖子有帮助吗?
如果你喜欢这篇文章,请告诉我们。这是我们改进的唯一方法。
有
没有