原标题:Spring认证中国教育管理中心-Apache Cassandra 的 Spring 数据教程二(Spring中国教育管理中心)
9.3.2.XML 配置
本节介绍如何使用 XML 配置 Spring Data Cassandra。
外部化连接属性
要外部化连接属性,您应该首先创建一个属性文件,其中包含连接到 Cassandra 所需的信息。contactpoints和keyspace是必填字段。
以下示例显示了我们的属性文件,名为cassandra.properties:
cassandra.contactpoints=10.1.55.80:9042,10.1.55.81:9042
cassandra.keyspace=showcase
在接下来的两个示例中,我们使用 Spring 将这些属性加载到 Spring 上下文中。
使用基于 XML 的元数据注册会话实例
虽然您可以使用 Spring 的传统<beans/>XML 命名空间向
com.datastax.oss.driver.api.core.CqlSession容器注册一个实例 ,但 XML 可能非常冗长,因为它是通用的。XML 名称空间是配置常用对象(例如CqlSession实例)的更好替代方法。该cassandra命名空间让你创建一个CqlSession实例。
以下示例显示了如何配置cassandra命名空间:
示例 58. 使用cassandra命名空间配置 Cassandra 的 XML 模式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cassandra="http://www.springframework.org/schema/data/cassandra"
xsi:schemaLocation="
http://www.springframework.org/schema/data/cassandra
https://www.springframework.org/schema/data/cassandra/spring-cassandra.xsd
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Default bean name is 'cassandraSession' -->
<cassandra:session contact-points="localhost" port="9042">
<cassandra:keyspace action="CREATE_DROP" name="mykeyspace" />
</cassandra:session>
<cassandra:session-factory>
<cassandra:script
location="classpath:/org/springframework/data/cassandra/config/schema.cql"/>
</cassandra:session-factory>
</beans>
更高级的 Cassandra 配置的 XML 配置元素如下所示。这些元素都使用默认的 bean 名称来保持配置代码的整洁和可读。
虽然前面的示例显示了配置 Spring 以连接到 Cassandra 是多么容易,但还有许多其他选项。基本上,DataStax Java 驱动程序可用的任何选项也可在 Spring Data for Apache Cassandra 配置中使用。这包括但不限于身份验证、负载平衡策略、重试策略和池选项。所有 Spring Data for Apache Cassandra 方法名称和 XML 元素都与驱动程序上的配置选项完全(或尽可能接近)命名,以便映射任何现有的驱动程序配置应该是直接的。以下示例展示了如何使用 XML 配置 Spring Data 组件
示例 59. 使用 XML 配置 Spring Data 组件
<!-- Loads the properties into the Spring Context and uses them to fill
in placeholders in the bean definitions -->
<context:property-placeholder location=