2016-03-07 79 views
3

我目前正在开发一个连接到远程MongoDB数据库的Java应用程序。MongoDB试图连接到本地主机,为什么?

我已经实现了身份验证方法休耕蒙戈指南:

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

该应用程序正确地连接到数据库,但我不能understand.It以及连接到远程服务器的事情,但我不知道为什么它尝试连接到本地主机: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 

所以,我怎么能告诉它我不希望连接到本地主机?

感谢

+0

你可以张贴'hostname'字符串? –

+0

这应该回答你的问题。 https://docs.mongodb.org/manual/reference/program/mongod/#bin.mongod – user2263572

+0

主机名字符串是我的服务器的IP地址 – adenaud

回答

4

您可以排除蒙戈自动连接/(本地主机:27017)加入下面的注释上春天开机Application.java

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

不知道为什么这是downvoted;这正是帮助我的信息。 –

+0

当我排除本地主机时,它要求我把本地主机放回...... – santafebound

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. 排除了蒙戈自动配置。
  2. 在上下文中将MongoClient作为bean公开。
  3. 为SpringBoot /蒙戈配置和自动配置继电器的使用默认的方式创造MongoClient你: spring.data.mongodb.host= spring.data.mongodb.port= spring.data.mongodb.database= spring.data.mongodb.username= spring.data.mongodb.password=
相关问题