Spring Boot не может подключиться к базе данных CassandraJAVA

Программисты JAVA общаются здесь
Anonymous
Spring Boot не может подключиться к базе данных Cassandra

Сообщение Anonymous »

Я использую быстрый запуск Spring Boot и хочу установить соединение с экземпляром cassandra, который работает на виртуальной машине Ubuntu на том же компьютере.
Я получаю эту ошибку при запуске приложения 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() ~[classes/:na]
at hello.CassandraConfig$$EnhancerBySpringCGLIB$$bf5637d0$$FastClassBySpringCGLIB$$bfd61920.invoke() ~[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() ~[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:

Код: Выделить всё

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0

org.springframework
gs-spring-boot
0.1.0


org.springframework.boot
spring-boot-starter-parent
2.0.5.RELEASE




org.springframework.boot
spring-boot-starter-web



org.springframework.boot
spring-boot-starter-actuator


















org.springframework.boot
spring-boot-starter-data-cassandra



com.fasterxml.jackson.core
jackson-databind



com.datastax.cassandra
cassandra-driver-core
3.6.0



com.datastax.cassandra
cassandra-driver-mapping
3.6.0


commons-io
commons-io
2.4



org.apache.commons
commons-lang3
3.7









































1.8
3.6.0
2.1.9.2
2.1.9.2
2.0-0
19.0
18.0





org.springframework.boot
spring-boot-maven-plugin


maven-failsafe-plugin



integration-test
verify










spring-snapshots
Spring Snapshots
https://repo.spring.io/snapshot

true



spring-milestones
Spring Milestones
https://repo.spring.io/milestone

false






spring-snapshots
Spring Snapshots
https://repo.spring.io/snapshot

true



spring-milestones
Spring Milestones
https://repo.spring.io/milestone

false





Я настроил файл cassandra.properties, устанавливающий хост, порт и имя пространства ключей, также существует Java-класс конфигурации cassandra, который устанавливает параметры соединения для подключения к кластеру
вот файл:

Код: Выделить всё

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();
//    }
}
что еще мне не хватает?

EDIT: оказалось, что мне пришлось изменить rpc_address в файле cassandra.yml на хосте виртуальной машины с localhost на IP-адрес виртуальной машины, поэтому он доступен для внешних подключений

Вернуться в «JAVA»