Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
829 views
in Technique[技术] by (71.8m points)

java - Spring mongo queries set custom timeout

I would like to lower the timeout setting in my spring-mongo java application (the query should fail after 300 ms if the database is not accessible).

I tried this config:

@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;
}

}

But the mongoUri options nor the builder change the timeout: the query fails only after 30 000ms.

I am not sure which parameter I should override nor the way to do it properly.

Thanks for your help

    <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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found the answer here: 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));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...