2019-04-02 22:17:48.046 INFO 6 --- [cluster-ClusterId{value='5ca36f0bcaed170006d3bed6', description='null'}-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:62) ~[mongo-java-driver-3.6.4.jar!/:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongo-java-driver-3.6.4.jar!/:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114) ~[mongo-java-driver-3.6.4.jar!/:na]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_151]
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_151]
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_151]
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_151]
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_151]
at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_151]
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:59) ~[mongo-java-driver-3.6.4.jar!/:na]
at com.mongodb.connection.SocketStream.open(SocketStream.java:57) ~[mongo-java-driver-3.6.4.jar!/:na]
... 3 common frames omitted
springboot中添加了mongodb的依赖包后,启动报错,原因是配置文件中未配置mongodb的地址:spring.data.mongodb.uri。
解决,移除mongodb依赖包或者启动类中添加:
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
//@EnableAutoConfiguration @ComponentScan
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplication.class, args);
}
}
Spring Boot has a feature called "auto configuration". In this case, as soon as the Mongo driver is detected on the classpath, the MongoAutoConfiguration is activated with default values, which point to localhost:27017. If you don't want that behaviour, you can now either configure the properties for MongoDB (see http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-mongodb for valid property keys) or disable the MongoAutoConfiguration。
Spring Boot有一个称为“自动配置”的特性。在本例中,一旦在类路径上检测到Mongo驱动程序,就会使用默认值激活MongoAutoConfiguration,默认值指向localhost:27017。如果不想要这种行为,现在可以为MongoDB配置属性,或者禁用MongoAutoConfiguration。
注意:启动类这样@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})配置时,代码中不可再自动注入MongoTemplate,因为MongoTemplate是在MongoAutoConfiguration中@Bean注入spring的:
@Autowired
MongoTemplate mongoTemplate;