Updated on 2023-04-11 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 DB instances. 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. Therefore, you are advised not to enable SSL.

Prerequisites

Familiarize yourself with:

  • Computer basics
  • Java code

Using an SSL Certificate

Connect to a single node instance using Java. The format of the Java link is as follows:
mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&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&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 a single node using Java. The Java link format is as follows:
mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin
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.

Example script in Java:
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");
        }
    }
}