Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jyemin/d7beed7ee5da301422ebbcb3fb48399e to your computer and use it in GitHub Desktop.
Save jyemin/d7beed7ee5da301422ebbcb3fb48399e to your computer and use it in GitHub Desktop.
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import javax.net.ssl.SSLContext;
import java.security.NoSuchAlgorithmException;
import java.util.function.Consumer;
public class ProgrammaticMongoClientSettingsConfiguration {
public static void main(String[] args) {
var connectionString = new ConnectionString("mongodb://localhost/?tls=true");
var client = createClient(connectionString, settingsBuilder ->
// This can be any programmatic customization
settingsBuilder.applyToSslSettings(builder -> builder.context(createCustomContext())));
// ...
client.close();
}
private static MongoClient createClient(ConnectionString connectionString,
Consumer<MongoClientSettings.Builder> settingsCustomizer) {
var settingsBuilder = MongoClientSettings.builder();
settingsBuilder.applyConnectionString(connectionString);
// customize!
settingsCustomizer.accept(settingsBuilder);
var settings = settingsBuilder.build();
return MongoClients.create(settings);
}
private static SSLContext createCustomContext() {
try {
// Imagine something more complicated here
return SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment