Updated on 2024-09-25 GMT+08:00

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

Using an SSL Certificate

  • Download the SSL certificate and verify the certificate before connecting to databases.
  • 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.
Use Java to connect to the replica set. The format of the Java code is as follows:
mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&replicaSet=replica&ssl=true
Table 1 Parameter description

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.

<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.

Use the keytool to configure the CA certificate. For details about the parameters, see Table 2.
keytool -importcert -trustcacerts -file <path to certificate authority file> -keystore <path to trust store> -storepass <password>
Table 2 Parameter description

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.

Set the JVM system properties in the program to point to the correct truststore and keystore:
  • System.setProperty("javax.net.ssl.trustStore","<path to trust store>");
  • System.setProperty("javax.net.ssl.trustStorePassword","<password>");

For details about the Java code, see the following example:

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&replicaSet=replica&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.

Connect to a replica set instance using Java. The Java link format is as follows:
mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&replicaSet=replica
Table 3 Parameter description

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.

<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.

For details about the Java code, see the following example:

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&replicaSet=replica");
            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");
        }
    }

}