import com.mongodb.ConnectionString; import com.mongodb.MongoClientSettings; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; public class MongoClientUtil { private static final Logger logger = LoggerFactory.getLogger(MongoClientUtil.class); private MongoClientUtil() {} private static MongoClient mongoClient; public static MongoClient getInstance() { return mongoClient; } static { try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[]{new MyX509TrustManager()}, new java.security.SecureRandom()); MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString("mongodb://,,/admin?authSource=admin&readPreference=primary&ssl=true&tlsAllowInvalidCertificates=true&tlsAllowInvalidHostnames=true")) .applyToClusterSettings(builder -> builder.serverSelectionTimeout(5, TimeUnit.SECONDS)) .applyToSocketSettings(builder -> builder.connectTimeout(5, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS)) .applyToSslSettings(builder -> builder.invalidHostNameAllowed(true).enabled(true).context(sslcontext)) .build(); mongoClient = MongoClients.create(settings); } catch (Exception e) { logger.error(e.getMessage(), e); } } private static class MyX509TrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate certificates[], String authType) throws CertificateException { logger.info("check client"); } @Override public void checkServerTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException { logger.info("check server"); } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }
在windows compass中有用的tlsAllowInvalidCertificates,这个client并不支持,所以一定要定义一个sslcontext信任所有服务器证书
标签:mongo,builder,ssl,static,import,true,public From: https://www.cnblogs.com/silyvin/p/17844465.html