Java MongoDB driver version 3.8 -- how to set timeout?

70 Views Asked by At

I am maintaining a JSP/Servlet application that uses the MongoDB 3.8 Java driver. At this point, I cannot change versions to a newer one.

I have occasionally experienced some timeouts when connecting from the application to the database. Based on what I read in https://mongodb.github.io/mongo-java-driver/3.8/driver/tutorials/connect-to-mongodb/ I wrote the following code:

    CodecRegistry pojoCodecRegistry = fromRegistries(com.mongodb.MongoClient.getDefaultCodecRegistry(),
                fromProviders(PojoCodecProvider.builder().automatic(true).build()));
    MongoCredential credential
      = MongoCredential.createCredential(theuser, database, thepassword.toCharArray());
    MongoClientSettings settings = MongoClientSettings.builder()
      .credential(credential)
      .codecRegistry(pojoCodecRegistry)
      .applyToClusterSettings(builder
        -> builder.hosts(Arrays.asList(new ServerAddress(addr, 27017))))
      .build();
    MongoClient client = MongoClients.create(settings);

This works, but with the eventual timeout (usually when reloading a JSP page).

I figured out I could create a SocketSettings instance with:

SocketSettings socketOptions = SocketSettings.builder().connectTimeout(60,TimeUnit.SECONDS).build();

But I cannot figure out how to apply these settings to the creation of the instance of MongoClient. Any hints?

thanks

0

There are 0 best solutions below