Created
August 16, 2024 11:13
-
-
Save jyemin/d7beed7ee5da301422ebbcb3fb48399e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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