如何从Spring引导应用程序访问Cassandra?

cl25kdpy  于 2022-09-27  发布在  Spring
关注(0)|答案(2)|浏览(222)

我是使用Spring Boot应用程序的新手。我想知道如何将cassandra数据库连接到应用程序。我在pom中添加了这个依赖项。xml文件:

<dependency>
    <groupId>com.datastax.oss</groupId>
    <artifactId>java-driver-core</artifactId>
    <version>4.1.0</version>
</dependency>

这些行指向应用程序。yml文件:

spring:
  data:
    cassandra:
      keyspace-name: test-keyspace
      contact-points: localhost
      port: 9042
      schemaAction: CREATE_IF_NOT_EXISTS
      request:
        timeout: 10s
      connection:
        connect-timeout: 10s
      locaDatacenter: datacenter1

但是,当我运行应用程序时,会出现以下错误:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: 

Error creating bean with name'org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration':
Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: 

Error creating bean with name 'cassandraSession' defined in class path resource [org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.class]: 
Unsatisfied dependency expressed through method 'cassandraSession' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: 

Error creating bean with name 'cassandraSessionBuilder' defined in class path resource [org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.class]: 
Unsatisfied dependency expressed through method 'cassandraSessionBuilder' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: 

Error creating bean with name 'cassandraDriverConfigLoader' defined in class path resource [org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.class]: 
Bean instantiation via factory method failed; 
nested exception is org.springframework.beans.BeanInstantiationException: 

Failed to instantiate [com.datastax.oss.driver.api.core.config.DriverConfigLoader]: Factory method 'cassandraDriverConfigLoader' threw exception; nested exception is java.lang.NoSuchFieldError: CONNECTION_CONNECT_TIMEOUT
polkgigr

polkgigr1#

代替DataStax Java驱动程序,尝试Spring Boot对Spring Data的依赖性(这会引入DataStax驱动程序本身):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>
5f0d552i

5f0d552i2#

除了Aaron的答案之外,很有可能在部署中存在版本冲突,从而导致您发布的异常。
没有必要将Cassandra Java驱动程序指定为依赖项,因为Spring Boot会自动为您拉取所有必需的依赖项+正确的版本。
既然你是新手,我建议你从一个有效的例子开始,而不是自己做一个。Spring项目在GitHub上有一个存储库,其中Spring Data examples包含一个specific for Cassandra
此外,DataStaxDevs最近举办了一个交互式研讨会,向您展示如何使用Spring Data Cassandra和Spring Boot构建微服务应用程序。有关研讨会的详细信息和包含完整工作代码的实践教程,请访问这里--https://github.com/DataStaxDevs/workshop-spring-data-cassandra。干杯

相关问题