Spring mongo查询设置自定义超时

时间:2017-01-20 15:18:54

标签: java spring mongodb spring-data mongo-java-driver

我想降低spring-mongo java应用程序中的超时设置(如果数据库不可访问,查询应在300 ms后失败)。

我试过这个配置:

@Configuration
public class MongoConfiguration {

private String mongoUri = "mongodb://127.0.0.1:27017/myDb?connectTimeoutMS=300&socketTimeoutMS=300&waitQueueTimeoutMS=300&wtimeoutMS=300";

@Bean
public MongoDbFactory mongoDbFactory() throws Exception {
    Builder options = new MongoClientOptions.Builder().socketTimeout(300).connectTimeout(300).maxWaitTime(300);
    return new SimpleMongoDbFactory(new MongoClientURI(mongoUri, options));
}

@Bean
public MongoTemplate mongoTemplate() throws Exception {
    MongoDbFactory mongoDbFactory = mongoDbFactory();
    MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory);
    return mongoTemplate;
}

}

但是mongoUri选项和构建器会更改超时:查询仅在30 000ms后失败。

我不确定我应该覆盖哪个参数,也不确定正确的方法。

感谢您的帮助

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>1.9.5.RELEASE</version>
    </dependency>

1 个答案:

答案 0 :(得分:6)

我在这里找到答案:https://scalegrid.io/blog/understanding-mongodb-client-timeout-options/

@Bean
public MongoDbFactory mongoDbFactory() throws Exception {
    MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder();
    optionsBuilder.connectTimeout(300);
    optionsBuilder.socketTimeout(300);
    optionsBuilder.serverSelectionTimeout(300);
    return new SimpleMongoDbFactory(new MongoClientURI(mongoUri, optionsBuilder));
}