如何通过Springboot连接到MongoDB?

时间:2017-09-18 13:24:26

标签: spring mongodb spring-mvc spring-boot application.properties

我有一个简单的Springboot应用程序启动并运行,并且知道我的完整MongoDB URI /连接字符串。数据库也已启动并运行。

为什么我会收到以下错误,如何让我的Springboot应用程序运行?

application.properties

#mongodb
spring.data.mongodb.host=asdf
spring.data.mongodb.port=27017
spring.data.mongodb.database=asdf
spring.data.mongodb.username=admin

#logging
logging.level.org.springframework.data=debug
logging.level.=error

的build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = '1.1.2-4'

    repositories {
        mavenCentral()
    }
    dependencies {
        // Needed for the 'kotlin' plugin
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // Needed for the 'org.springframework.boot' plugin
        classpath "org.springframework.boot:spring-boot-gradle-plugin:1.5.2.RELEASE"
        // Needed for the 'kotlin-spring' plugin
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"

    }
}

// Allows us to compile Kotlin files
apply plugin: 'kotlin'
// Does some extra work to set up Spring Boot.
// Specifically this gives us the "bootRun" task we will be using
apply plugin: 'org.springframework.boot'
// Allows for improved interop between Kotlin and Spring
apply plugin: 'kotlin-spring'

repositories {
    mavenCentral()
}

dependencies {
    // MongoDB
    compile 'org.springframework.data:spring-data-mongodb:1.2.3.RELEASE'

    // Kotlin Dependencies
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"

    // Spring Dependencies
    compile("org.springframework.boot:spring-boot-starter-web") {
        exclude module: "spring-boot-starter-tomcat"
    }
    compile "org.springframework.boot:spring-boot-starter-jetty"
    compile "org.springframework.boot:spring-boot-starter-actuator"

    // Jackson Dependencies
    compile "com.fasterxml.jackson.core:jackson-annotations"
    compile "com.fasterxml.jackson.core:jackson-core"
    compile "com.fasterxml.jackson.core:jackson-databind"
    runtime "com.fasterxml.jackson.datatype:jackson-datatype-jdk8"
    runtime "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
    runtime "com.fasterxml.jackson.module:jackson-module-kotlin"
}

task wrapper(type: Wrapper) {
    gradleVersion = "3.5"
}

堆栈跟踪:

$ ./gradlew bootRun
Starting a Gradle Daemon, 1 busy and 2 incompatible Daemons could not be reused, use --status for details
:compileKotlin UP-TO-DATE
:compileJava NO-SOURCE
:copyMainKotlinClasses UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:findMainClass
Using a single directory for all classes from a source set. This behaviour has been deprecated and is scheduled to be removed in Gradle 5.0
:bootRun

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

2017-09-18 15:30:31.765  INFO 5904 --- [           main] hello.ApplicationKt                      : Starting ApplicationKt on Martin with PID 5904 (started by Martin in D:\Software Projects\Web Projects\spring-boot-kotlin-demo)
2017-09-18 15:30:31.767  INFO 5904 --- [           main] hello.ApplicationKt                      : No active profile set, falling back to default profiles: default
2017-09-18 15:30:31.808  INFO 5904 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3c72f59f: startup date [Mon Sep 18 15:30:31 CEST 2017]; root of context hierarchy
2017-09-18 15:30:32.826  INFO 5904 --- [           main] org.eclipse.jetty.util.log               : Logging initialized @1697ms to org.eclipse.jetty.util.log.Slf4jLog
2017-09-18 15:30:33.074  INFO 5904 --- [           main] e.j.JettyEmbeddedServletContainerFactory : Server initialized with port: 8080
2017-09-18 15:30:33.075  INFO 5904 --- [           main] org.eclipse.jetty.server.Server          : jetty-9.4.2.v20170220
2017-09-18 15:30:33.300  INFO 5904 --- [           main] org.eclipse.jetty.server.session         : DefaultSessionIdManager workerName=node0
2017-09-18 15:30:33.300  INFO 5904 --- [           main] org.eclipse.jetty.server.session         : No SessionScavenger set, using defaults
2017-09-18 15:30:33.302  INFO 5904 --- [           main] org.eclipse.jetty.server.session         : Scavenging every 600000ms
2017-09-18 15:30:33.306  INFO 5904 --- [           main] o.e.jetty.ContextHandler.application     : Initializing Spring embedded WebApplicationContext
2017-09-18 15:30:33.307  INFO 5904 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1501 ms
2017-09-18 15:30:33.484  INFO 5904 --- [           main] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-09-18 15:30:33.486  INFO 5904 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'metricsFilter' to: [/*]
2017-09-18 15:30:33.486  INFO 5904 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-18 15:30:33.486  INFO 5904 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-18 15:30:33.486  INFO 5904 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-18 15:30:33.486  INFO 5904 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-18 15:30:33.486  INFO 5904 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'webRequestLoggingFilter' to: [/*]
2017-09-18 15:30:33.486  INFO 5904 --- [           main] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'applicationContextIdFilter' to: [/*]
2017-09-18 15:30:33.652  INFO 5904 --- [           main] o.e.jetty.server.handler.ContextHandler  : Started o.s.b.c.e.j.JettyEmbeddedWebAppContext@562457e1{/,[file:///C:/Users/Martin/AppData/Local/Temp/jetty-docbase.789597977539512961.8080/],AVAILABLE}
2017-09-18 15:30:33.652  INFO 5904 --- [           main] org.eclipse.jetty.server.Server          : Started @2524ms
2017-09-18 15:30:33.911  INFO 5904 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3c72f59f: startup date [Mon Sep 18 15:30:31 CEST 2017]; root of context hierarchy
2017-09-18 15:30:33.961  INFO 5904 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-09-18 15:30:33.961  INFO 5904 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-09-18 15:30:33.990  INFO 5904 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-18 15:30:33.990  INFO 5904 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-18 15:30:34.028  INFO 5904 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-18 15:30:34.382  INFO 5904 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2017-09-18 15:30:34.853  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/info || /info.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-09-18 15:30:34.854  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/env/{name:.*}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EnvironmentMvcEndpoint.value(java.lang.String)
2017-09-18 15:30:34.854  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/env || /env.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-09-18 15:30:34.855  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/health || /health.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.HealthMvcEndpoint.invoke(javax.servlet.http.HttpServletRequest,java.security.Principal)
2017-09-18 15:30:34.855  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/trace || /trace.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-09-18 15:30:34.856  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/heapdump || /heapdump.json],methods=[GET],produces=[application/octet-stream]}" onto public void org.springframework.boot.actuate.endpoint.mvc.HeapdumpMvcEndpoint.invoke(boolean,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.io.IOException,javax.servlet.ServletException
2017-09-18 15:30:34.859  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/loggers/{name:.*}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.LoggersMvcEndpoint.get(java.lang.String)
2017-09-18 15:30:34.859  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/loggers/{name:.*}],methods=[POST],consumes=[application/vnd.spring-boot.actuator.v1+json || application/json],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.LoggersMvcEndpoint.set(java.lang.String,java.util.Map<java.lang.String, java.lang.String>)
2017-09-18 15:30:34.859  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/loggers || /loggers.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-09-18 15:30:34.863  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/mappings || /mappings.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-09-18 15:30:34.864  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/metrics/{name:.*}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)
2017-09-18 15:30:34.864  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/metrics || /metrics.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-09-18 15:30:34.865  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/dump || /dump.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-09-18 15:30:34.865  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/beans || /beans.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-09-18 15:30:34.866  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/configprops || /configprops.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-09-18 15:30:34.867  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/auditevents || /auditevents.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.boot.actuate.endpoint.mvc.AuditEventsMvcEndpoint.findByPrincipalAndAfterAndType(java.lang.String,java.util.Date,java.lang.String)
2017-09-18 15:30:34.867  INFO 5904 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/autoconfig || /autoconfig.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-09-18 15:30:34.990  INFO 5904 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-09-18 15:30:35.000  INFO 5904 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2017-09-18 15:30:35.082  INFO 5904 --- [           main] o.e.jetty.ContextHandler.application     : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-09-18 15:30:35.082  INFO 5904 --- [           main] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2017-09-18 15:30:35.094  INFO 5904 --- [           main] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 12 ms
2017-09-18 15:30:35.106  INFO 5904 --- [           main] o.e.jetty.server.AbstractConnector       : Started ServerConnector@7f6874f2{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2017-09-18 15:30:35.106  INFO 5904 --- [           main] .s.b.c.e.j.JettyEmbeddedServletContainer : Jetty started on port(s) 8080 (http/1.1)
2017-09-18 15:30:35.111  INFO 5904 --- [           main] hello.ApplicationKt                      : Started ApplicationKt in 3.62 seconds (JVM running for 3.982)
2017-09-18 15:30:35.479  INFO 5904 --- [localhost:27017] org.mongodb.driver.cluster               : Exception in monitor thread while connecting to server localhost:27017

com.mongodb.MongoSocketOpenException: Exception opening socket
        at com.mongodb.connection.SocketStream.open(SocketStream.java:63) ~[mongo-java-driver-3.4.2.jar:na]
        at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) ~[mongo-java-driver-3.4.2.jar:na]
        at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:113) ~[mongo-java-driver-3.4.2.jar:na]
        at java.lang.Thread.run(Thread.java:745) [na:1.8.0_20]
Caused by: java.net.ConnectException: Connection refused: connect
        at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[na:1.8.0_20]
        at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) ~[na:1.8.0_20]
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345) ~[na:1.8.0_20]
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_20]
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_20]
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) ~[na:1.8.0_20]
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_20]
        at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_20]
        at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:57) ~[mongo-java-driver-3.4.2.jar:na]
        at com.mongodb.connection.SocketStream.open(SocketStream.java:58) ~[mongo-java-driver-3.4.2.jar:na]
        ... 3 common frames omitted

申请类:

package hello

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.context.annotation.Configuration

@EnableAutoConfiguration
@Configuration
class Application

fun main(args: Array<String>) {
    SpringApplication.run(Application::class.java, *args)
}

0 个答案:

没有答案