Spring Boot无法连接到cassandra数据库

时间:2018-11-08 16:11:28

标签: java spring spring-boot cassandra

我正在使用Spring Boot快速入门,并希望建立与在同一台计算机上的ubuntu VM上运行的cassandra实例的连接, 运行spring boot应用程序时出现此错误

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.5.RELEASE)

2018-11-08 18:00:10.671  INFO 12076 --- [           main] hello.Application                        : Starting Application on DESKTOP-OG0KPA1 with PID 12076 (C:\Users\omar_\Downloads\gs-spring-boot-master\gs-spring-boot-master\complete\target\classes started by omar_ in C:\Users\omar_\Downloads\gs-spring-boot-master\gs-spring-boot-master\complete)
2018-11-08 18:00:10.680  INFO 12076 --- [           main] hello.Application                        : No active profile set, falling back to default profiles: default
2018-11-08 18:00:10.966  INFO 12076 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@60dcc9fe: startup date [Thu Nov 08 18:00:10 EET 2018]; root of context hierarchy
2018-11-08 18:00:12.701  INFO 12076 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'cassandraTemplate' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=cassandraConfig; factoryMethodName=cassandraTemplate; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [hello/CassandraConfig.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration; factoryMethodName=cassandraTemplate; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/data/cassandra/CassandraDataAutoConfiguration.class]]
2018-11-08 18:00:13.020  INFO 12076 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2018-11-08 18:00:13.112  INFO 12076 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2018-11-08 18:00:14.517  INFO 12076 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8087 (http)
2018-11-08 18:00:14.560  INFO 12076 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-11-08 18:00:14.561  INFO 12076 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.34
2018-11-08 18:00:14.570  INFO 12076 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_121\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Dell\DW WLAN Card;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Brackets\command;C:\Program Files (x86)\GtkSharp\2.12\bin;C:\Program Files (x86)\Git\cmd;C:\Program Files\nodejs\;C:\PostgreSQL\pg10\bin;C:\Program Files\PuTTY\;C:\WINDOWS\System32\OpenSSH\;D:\PostgreSQL\pg10\bin;C:\Users\omar_\Downloads\apache-maven-3.5.4-bin\apache-maven-3.5.4\bin;C:\Users\omar_\AppData\Local\atom\bin;C:\Users\omar_\AppData\Local\Microsoft\WindowsApps;C:\Users\omar_\AppData\Roaming\npm;C:\Program Files\Microsoft VS Code\bin;C:\Users\omar_\Downloads\apache-cassandra-3.11.3-bin\apache-cassandra-3.11.3\bin;C:\Python27;;.]
2018-11-08 18:00:14.775  INFO 12076 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-11-08 18:00:14.775  INFO 12076 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3830 ms
2018-11-08 18:00:15.491 ERROR 12076 --- [ost-startStop-1] o.s.b.web.embedded.tomcat.TomcatStarter  : Error starting Tomcat context. Exception: org.springframework.beans.factory.BeanCreationException. Message: Error creating bean with name 'servletEndpointRegistrar' defined in class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration$WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthEndpoint' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthEndpoint]: Factory method 'healthEndpoint' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.cassandra.CassandraHealthIndicatorAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cluster' defined in class path resource [hello/CassandraConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.cassandra.config.CassandraClusterFactoryBean]: Factory method 'cluster' threw exception; nested exception is java.lang.NumberFormatException: null
2018-11-08 18:00:15.522  INFO 12076 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2018-11-08 18:00:15.534  WARN 12076 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2018-11-08 18:00:15.560  INFO 12076 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-11-08 18:00:15.583 ERROR 12076 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:155) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1277) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1265) [spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
    at hello.Application.main(Application.java:15) [classes/:na]
Caused by: java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:542) ~[na:1.8.0_121]
    at java.lang.Integer.parseInt(Integer.java:615) ~[na:1.8.0_121]
    at hello.CassandraConfig.cluster(CassandraConfig.java:32) ~[classes/:na]
    at hello.CassandraConfig$$EnhancerBySpringCGLIB$$bf5637d0.CGLIB$cluster$0(<generated>) ~[classes/:na]
    at hello.CassandraConfig$$EnhancerBySpringCGLIB$$bf5637d0$$FastClassBySpringCGLIB$$bfd61920.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:365) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at hello.CassandraConfig$$EnhancerBySpringCGLIB$$bf5637d0.cluster(<generated>) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    ... 122 common frames omitted


Process finished with exit code 1

这是我的pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-spring-boot</artifactId>
    <version>0.1.0</version>



    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- tag::actuator[] -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- end::actuator[] -->
        <!-- tag::tests[] -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
        </dependency>


        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-opengis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-data</artifactId>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-epsg-hsql</artifactId>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-wfs-ng</artifactId>
            <version>${gt.version}</version>
        </dependency>

        <!--<dependency>-->
            <!--<groupId>org.apache.cassandra</groupId>-->
            <!--<artifactId>cassandra-all</artifactId>-->
            <!--<version>3.11.3</version>-->
        <!--</dependency>-->
        <!--<dependency>-->
            <!--<groupId>com.datastax.cassandra</groupId>-->
            <!--<artifactId>cassandra-driver-core</artifactId>-->
            <!--<version>3.6.0</version>-->
        <!--</dependency>-->
        <!--<dependency>-->
            <!--<groupId>org.springframework.data</groupId>-->
            <!--<artifactId>spring-data-cassandra</artifactId>-->
        <!--</dependency>-->

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


        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>


        <dependency>
            <groupId>com.datastax.cassandra</groupId>
            <artifactId>cassandra-driver-core</artifactId>
            <version>3.6.0</version>
        </dependency>

        <dependency>
            <groupId>com.datastax.cassandra</groupId>
            <artifactId>cassandra-driver-mapping</artifactId>
            <version>3.6.0</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>



        <!--<dependency>-->
            <!--<groupId>org.cassandraunit</groupId>-->
            <!--<artifactId>cassandra-unit-spring</artifactId>-->
            <!--<version>${cassandra-unit-spring.version}</version>-->
            <!--<scope>test</scope>-->
            <!--<exclusions>-->
                <!--<exclusion>-->
                    <!--<groupId>org.cassandraunit</groupId>-->
                    <!--<artifactId>cassandra-unit</artifactId>-->
                <!--</exclusion>-->
            <!--</exclusions>-->
        <!--</dependency>-->
        <!--<dependency>-->
            <!--<groupId>org.cassandraunit</groupId>-->
            <!--<artifactId>cassandra-unit-shaded</artifactId>-->
            <!--<version>${cassandra-unit-shaded.version}</version>-->
            <!--<scope>test</scope>-->
        <!--</dependency>-->
        <!--<dependency>-->
            <!--<groupId>org.hectorclient</groupId>-->
            <!--<artifactId>hector-core</artifactId>-->
            <!--<version>${hector-core.version}</version>-->
            <!--<exclusions>-->
                <!--<exclusion>-->
                    <!--<artifactId>commons-logging</artifactId>-->
                    <!--<groupId>commons-logging</groupId>-->
                <!--</exclusion>-->
            <!--</exclusions>-->
        <!--</dependency>-->
        <!--<dependency>-->
            <!--<groupId>com.datastax.cassandra</groupId>-->
            <!--<artifactId>cassandra-driver-core</artifactId>-->
            <!--<version>${cassandra-driver-core.version}</version>-->
            <!--<optional>true</optional>-->
        <!--</dependency>-->
        <!-- end::tests[] -->
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
        <cassandra-driver-core.version>3.6.0</cassandra-driver-core.version>
        <cassandra-unit-spring.version>2.1.9.2</cassandra-unit-spring.version>
        <cassandra-unit-shaded.version>2.1.9.2</cassandra-unit-shaded.version>
        <hector-core.version>2.0-0</hector-core.version>
        <guava.version>19.0</guava.version>
        <gt.version>18.0</gt.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>







        </plugins>
    </build>


    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>


    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>

我已经建立了一个cassandra.properties文件,该文件设置了主机,端口和密钥空间名,还有一个cassandra config java类,用于设置连接参数以连接到集群 这是文件:

package hello;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.cassandra.config.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;
import org.springframework.data.cassandra.core.mapping.BasicCassandraMappingContext;
import org.springframework.data.cassandra.core.mapping.CassandraMappingContext;


@Configuration
public class CassandraConfig extends AbstractCassandraConfiguration {
    private static final Log LOGGER = LogFactory.getLog(CassandraConfig.class);

    @Autowired
    private Environment environment;

    @Override
    protected String getKeyspaceName() {
        return environment.getProperty("spring.data.cassandra.keyspace-name");
    }

    @Override
    @Bean
    public CassandraClusterFactoryBean cluster() {
        final CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
        cluster.setContactPoints(environment.getProperty("spring.data.cassandra.contact-points"));
        cluster.setPort(Integer.parseInt(environment.getProperty("spring.data.cassandra.port")));
        LOGGER.info("Cluster created with contact points [" + environment.getProperty("spring.data.cassandra.contact-points") + "] " + "& port [" + Integer.parseInt(environment.getProperty("spring.data.cassandra.port")) + "].");
        return cluster;
    }

//
//    @Bean
//    public CassandraClusterFactoryBean cluster() {
//        CassandraClusterFactoryBean cluster =
//                new CassandraClusterFactoryBean();
//        cluster.setContactPoints("192.168.164.130");
//        cluster.setPort(9042);
//        return cluster;
//    }

    @Override
    @Bean
    public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
        return new BasicCassandraMappingContext();
    }

//    @Bean
//    public CassandraMappingContext cassandraMapping()
//            throws ClassNotFoundException {
//        return new BasicCassandraMappingContext();
//    }
}

我还想念什么?

编辑:事实证明,我不得不将vm主机中cassandra.yml文件中的rpc_address从localhost更改为vm ip地址,因此暴露给外部连接

3 个答案:

答案 0 :(得分:0)

只要您的application.yml具有以下属性,您就会添加许多Spring为您处理的样板代码:

spring:
   data:
      cassandra:
         contact-points: 
         keyspace-name: 
         username: 
         password: 
         port: 

和依赖项

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

Spring将为您配置连接,类似于RDBMS的Spring数据。

然后您可以使用Cassandra存储库查询表:

@Repository
public interface YourRepository extends CassandraRepository<Item> {
    //
}

和实体:

@Table
public class Item {
    @PrimaryKeyColumn(
      name = "id"
      type = PrimaryKeyType.CLUSTERED)
    private UUID id;
    @PrimaryKeyColumn(
      name = "key", type = PrimaryKeyType.PARTITIONED)
    private String key;
    @Column
    private String data; 
    //Getter setters
}

答案 1 :(得分:0)

您spring.data.cassandra.port丢失或为空。您可以更改为以下代码,以便如果不存在该代码,则该代码将使用默认代码

@Value("${spring.data.cassandra.port: <cassandra port/9042>}")
private int port;

答案 2 :(得分:0)

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;
import org.springframework.data.cassandra.config.java.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext;
import org.springframework.data.cassandra.mapping.CassandraMappingContext;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;


/**
 * @author dpoddar
 *
 */
@Configuration
@EnableCassandraRepositories(basePackages = "com.xxx.abc.reposiroty.cassandra")
@ComponentScan(basePackages = "com.xxx.abc")
@Profile("cassandra")
public class CassandraConfig extends AbstractCassandraConfiguration {
    private static final Log LOGGER = LogFactory.getLog(CassandraConfig.class);

    @Override
    protected String getKeyspaceName() {
        return "agenthub";
    }


    @Override
    @Bean
    public CassandraClusterFactoryBean cluster() {
        final CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
        cluster.setContactPoints("localhost");
        cluster.setPort(9042);
        //LOGGER.info("Cluster created with contact points [" + environment.getProperty("cassandra.contactpoints") + "] " + "& port [" + Integer.parseInt(environment.getProperty("cassandra.port")) + "].");
        return cluster;
    }

    @Override
    @Bean
    public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
        return new BasicCassandraMappingContext();
    }
}