简体   繁体   中英

MongoDB Java Driver 4.1.1 how to configure timeout settings

I am migrating an application from using MongoDB Java driver v. 3.6.4 to v. 4.1.1

In 3.6.4 configuration is passed via MongoClientOptions

@Bean
    public MongoClientOptions mongoOptions() {
        return MongoClientOptions.builder()
                .connectTimeout(...)
                .serverSelectionTimeout(..)
                .socketTimeout(...)
                .build();
    } 

In 4.1.1 MongoClientOptions has been deprecated, and I am utilizing MongoClientSettings class http://mongodb.github.io/mongo-java-driver/4.1/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.Builder.html

   @Bean
    public MongoClientSettings mongoOptions() {
        return MongoClientSettings.builder()
                .applyToSocketSettings(builder ->
                        builder.applySettings(builder()
                                .connectTimeout(config.getConnectTimeout(), MILLISECONDS).build()))
                .applyToClusterSettings(builder ->
                        builder.serverSelectionTimeout(config.getServerSelectionTimeout(), MILLISECONDS).build())
                .build();

    }

However I can't find setting to configure connectTimeout (apart from supplying connection string via applyConnectionString method.

Yeah, took me a while to figure this out.

The connection timeout and socket timeout are now both in SocketSettings (with the latter renamed as readTimeout).

So it would look something like the following (where you can replace the 1's with your inputs):

  @Bean
  public MongoClientSettings mongoSetting() {

    return MongoClientSettings.builder()
        .applyToSocketSettings(builder -> {
          builder.connectTimeout(1, MILLISECONDS);
          builder.readTimeout(1, MILLISECONDS);
        })
        .applyToClusterSettings( builder -> builder.serverSelectionTimeout(1, MILLISECONDS))
        .applyConnectionString(new ConnectionString("<your-connection-string>"))

        .build();
  }

I found the need to set the connection string here (in addition to having it set via spring.data.mongodb.uri). Go figure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM