MongoDB试图连接到localhost,为什么?

时间:2016-03-07 16:49:54

标签: java mongodb

我目前正在开发一个连接到远程MongoDB数据库的Java应用程序。

我已经实现了使用mongo指南的身份验证方法:

MongoCredential credential = MongoCredential.createScramSha1Credential(username, credentialDatabase, password.toCharArray());
MongoClient client = new MongoClient(new ServerAddress(hostname, port), Arrays.asList(credential));
mongoDatabase = client.getDatabase(database);

应用程序正确连接到数据库,但有一件事我无法理解。它连接到远程服务器,但我不知道为什么它尝试连接到localhost:27017。

2016-03-07 16:13:29.662  INFO 12507 --- [*.*.*:25015] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:29}] to *.*.*.*:25015

2016-03-07 16:13:29.687  INFO 12507 --- [*.*.*:25015] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=*.*.*.*:25015, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 3]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=24485426}


2016-03-07 16:13:30.062  INFO 12507 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}


2016-03-07 16:13:30.220  INFO 12507 --- [localhost:27017] org.mongodb.driver.cluster               : Exception in monitor thread while connecting to server localhost:27017

com.mongodb.MongoSocketOpenException: Exception opening socket

那么,我怎么能告诉它我不想连接到localhost?

由于

3 个答案:

答案 0 :(得分:5)

您可以通过在spring boot Application.java上添加以下注释来排除Mongo自动连接/(localhost:27017)。

@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class})
public class Application {
    // ...
}

答案 1 :(得分:1)

我不确定这是否会有所帮助。

如果您正在使用SpringBoot 1.4并且在上下文中没有MongoClient的bean,则自动配置将使用默认配置创建MongoClient。

@Configuration
---->@ConditionalOnClass(MongoClient.class)<----
@EnableConfigurationProperties(MongoProperties.class)
@ConditionalOnMissingBean(type = "org.springframework.data.mongodb.MongoDbFactory")
public class MongoAutoConfiguration {
...
    @Bean
    ---->@ConditionalOnMissingBean<----
    public MongoClient mongo() throws UnknownHostException {
        this.mongo = this.properties.createMongoClient(this.options, this.environment);
        return this.mongo;
    }
...

所以你有3个选择:

  1. 排除mongo的自动配置。
  2. 在上下文中将MongoClient公开为bean。
  3. 使用SpringBoot / Mongo的默认配置方式和自动配置中继为您创建MongoClient: spring.data.mongodb.host= spring.data.mongodb.port= spring.data.mongodb.database= spring.data.mongodb.username= spring.data.mongodb.password=

答案 2 :(得分:0)

这是Spring Boot的“自动配置”功能。您可以通过扩展@SpringBootApplication注释来禁用它,如下所示:

@SpringBootApplication(exclude={MongoAutoConfiguration.class})