嵌入式Mongo的Spring Boot:无法分配请求的地址:JVM_Bind

时间:2017-08-16 07:13:51

标签: spring mongodb spring-boot spring-boot-test

我正在尝试使用嵌入式Mongo& amp;设置Spring Boot的JUnit测试。卡夫卡: -

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE,
        classes = {AccountingApplication.class})
@DataMongoTest
public class BaseEmbeddedTest {


    @ClassRule
    public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true);

    @Autowired
    private MongoTemplate mongoTemplate;


    @Test
    public void emptyTest(){

    }

}
  

src / test / resources / application.yml: -

spring:
  data:
    mongodb:
      port: 0
  kafka:
    bootstrap-servers: ${spring.embedded.kafka.brokers}

问题

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [de.flapdoodle.embed.mongo.config.IMongodConfig]: Factory method 'embeddedMongoConfiguration' threw exception; nested exception is java.net.BindException: Cannot assign requested address: JVM_Bind
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 140 more
Caused by: java.net.BindException: Cannot assign requested address: JVM_Bind
    at java.net.DualStackPlainSocketImpl.bind0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
    at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
    at java.net.ServerSocket.bind(ServerSocket.java:375)
    at java.net.ServerSocket.<init>(ServerSocket.java:237)
    at de.flapdoodle.embed.process.runtime.Network.getFreeServerPort(Network.java:80)
    at org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration.embeddedMongoConfiguration(EmbeddedMongoAutoConfiguration.java:147)

我在这里做错了什么?

版本: -

    dependencyManagementPluginVersion = '1.0.3.RELEASE'
    springBootVersion = '1.5.6.RELEASE'
    springCloudVersion = 'Dalston.SR2'
    projectVersion = '0.0.1-SNAPSHOT'
    javaVersion = 1.8
    kotlinVersion = '1.1.4'

1 个答案:

答案 0 :(得分:1)

此注释:@DataMongoTest导致Spring Boot创建嵌入式Mongo实例。异常消息告诉我们嵌入式Mongo实例无法启动,因为已经尝试在其上运行的端口上运行了进程。

嵌入式Mongo实例由EmbeddedMongoAutoConfiguration配置,Spring Boot应用的策略 - 用于端口分配 - 如下:

if configured Mongo port > 0 then 
    use the configured port
else 
    assign a random port
end

因此,我怀疑您的测试上下文配置为spring.data.mongodb.port的非零值。我知道你发布了你的application.yml,暗示你 - 正确 - 为spring.data.mongodb.port分配一个零值,但是如果你在EmbeddedMongoAutoConfiguration构造函数中放置一个断点并查看属性参数,我认为你' ll看到该配置类使用的实际值不为零。如果传递给EmbeddedMongoAutoConfiguration的端口值实际上为零,但您仍然收到JVM_Bind错误,则表示此调用:Network.getFreeServerPort(this.getHost())未返回空闲端口,这似乎不太可能。

为了解决这个问题:只要你用spring.data.mongodb.port=0配置你的测试上下文,那么嵌入式Mongo实例将被分配一个随机端口,这个随机端口将被告知你的Spring上下文的其他方面(例如你的MongoTemplate)需要与Mongo实例交谈。