Java
If you are connecting to an instance using Java, an SSL certificate is optional, but downloading an SSL certificate and encrypting the connection will improve the security of your instance. SSL is disabled by default for newly created instances, but you can enable SSL by referring to Enabling or Disabling SSL. SSL encrypts connections to databases but it increases the connection response time and CPU usage. For this reason, enabling SSL is not recommended.
Prerequisites
Familiarize yourself with:
- Computer basics
- Java code
Obtaining and Using Java
- Download the Jar driver from: https://repo1.maven.org/maven2/org/mongodb/mongo-java-driver/3.0.4/
- To view the usage guide, visit https://mongodb.github.io/mongo-java-driver/4.2/driver/getting-started/installation/.
Using an SSL Certificate
- Download the SSL certificate and verify the certificate before connecting to databases.
- On the Instances page, click the target DB instance name. In the DB Information area on the Basic Information page, click in the SSL field to download the root certificate or certificate bundle.
- For details about how to set up an SSL connection, see the MongoDB Java Driver official document at https://www.mongodb.com/docs/drivers/java/sync/current/fundamentals/connection/tls/#std-label-tls-ssl.
- Java Runtime Environment (JRE) earlier than Java 8 enables TLS 1.2 only in updated versions. If TLS 1.2 is not enabled for your JRE, upgrade it to a later version to use TLS 1.2 for connection.
mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&ssl=true
Parameter |
Description |
---|---|
<username> |
Current username. |
<password> |
Password for the current username |
<instance_ip> |
If you attempt to access the instance from an ECS, set instance_ip to the private IP address displayed on the Basic Information page of the instance to which you intend to connect. |
If you intend to access the instance through an EIP, set instance_ip to the EIP that has been bound to the instance. |
|
If multiple host addresses are required, list the addresses in the format of <instance_ip1>:<instance_port1>,<instance_ip2>:<instance_port2>....... Example: mongodb://username:*****@127.***.***.1:8635,127.***.***.2:8635/?authSource=admin |
|
<instance_port> |
Database port displayed on the Basic Information page. Default value: 8635 |
<database_name> |
Name of the database to be connected. |
authSource |
Authentication user database. The value is admin. |
ssl |
Connection mode. true indicates that the SSL connection mode is used. |
keytool -importcert -trustcacerts -file <path to certificate authority file> -keystore <path to trust store> -storepass <password>
Parameter |
Description |
---|---|
<path to certificate authority file> |
Path for storing the SSL certificate. |
<path to trust store> |
Path for storing the truststore. Set this parameter as required, for example, ./trust/certs.keystore. |
<password> |
Custom password. |
- System.setProperty("javax.net.ssl.trustStore","<path to trust store>");
- System.setProperty("javax.net.ssl.trustStorePassword","<password>");
public class Connector { public static void main(String[] args) { try { System.setProperty("javax.net.ssl.trustStore", "./trust/certs.keystore"); System.setProperty("javax.net.ssl.trustStorePassword", "123456"); ConnectionString connString = new ConnectionString("mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&ssl=true"); MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(connString) .applyToSslSettings(builder -> builder.enabled(true)) .applyToSslSettings(builder -> builder.invalidHostNameAllowed(true)) .build(); MongoClient mongoClient = MongoClients.create(settings); MongoDatabase database = mongoClient.getDatabase("admin"); //Ping the database. If the operation fails, an exception occurs. BsonDocument command = new BsonDocument("ping", new BsonInt64(1)); Document commandResult = database.runCommand(command); System.out.println("Connect to database successfully"); } catch (Exception e) { e.printStackTrace(); System.out.println("Test failed"); } } }
Connection Without the SSL Certificate
You do not need to download the SSL certificate because certificate verification on the server is not required.
mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin
Parameter |
Description |
---|---|
<username> |
Current username. |
<password> |
Password for the current username |
<instance_ip> |
If you attempt to access the instance from an ECS, set instance_ip to the private IP address displayed on the Basic Information page of the instance to which you intend to connect. |
If you intend to access the instance through an EIP, set instance_ip to the EIP that has been bound to the instance. |
|
If multiple host addresses are required, list the addresses in the format of <instance_ip1>:<instance_port1>,<instance_ip2>:<instance_port2>....... Example: mongodb://username:*****@127.***.***.1:8635,127.***.***.2:8635/?authSource=admin |
|
<instance_port> |
Database port displayed on the Basic Information page. Default value: 8635 |
<database_name> |
Name of the database to be connected. |
authSource |
Authentication user database. The value is admin. |
public class Connector { public static void main(String[] args) { try { ConnectionString connString = new ConnectionString("mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin"); MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(connString) .retryWrites(true) .build(); MongoClient mongoClient = MongoClients.create(settings); MongoDatabase database = mongoClient.getDatabase("admin"); //Ping the database. If the operation fails, an exception occurs. BsonDocument command = new BsonDocument("ping", new BsonInt64(1)); Document commandResult = database.runCommand(command); System.out.println("Connect to database successfully"); } catch (Exception e) { e.printStackTrace(); System.out.println("Test failed"); } } }
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot