Updated on 2022-09-20 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

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.

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.

Method

Use keytool to generate a trustStore.

keytool -import -file /var/chroot/mongodb/CA/ca.crt -keystore /home/Mike/jdk1.8.0_112/jre/lib/security/mongostore -storetype pkcs12 -storepass ****

  • /var/chroot/mongodb/CA/ca.crt is the root certificate path.
  • /home/Mike/jdk1.8.0_112/jre/lib/security/mongostore indicates the path of the generated truststore.
  • **** is the password of the trustStore.

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

import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoClientOptions;
public class MongoDBJDBC {
public static void main(String[] args){
      try {
              System.setProperty("javax.net.ssl.trustStore", "/home/Mike/jdk1.8.0_112/jre/lib/security/mongostore");
              System.setProperty("javax.net.ssl.trustStorePassword", "****");
              ServerAddress serverAddress = new ServerAddress("ip", port);
              List addrs = new ArrayList();
              addrs.add(serverAddress);
              MongoCredential credential = MongoCredential.createScramSha1Credential("rwuser", "admin", "!rwuserPassword".toCharArray());
              List credentials = new ArrayList();
              credentials.add(credential);
              MongoClientOptions opts= MongoClientOptions.builder()
              .sslEnabled(true)
              .sslInvalidHostNameAllowed(true)
              .build();
              MongoClient mongoClient = new MongoClient(addrs,credentials,opts);
              MongoDatabase mongoDatabase = mongoClient.getDatabase("testdb");
              MongoCollection collection = mongoDatabase.getCollection("testCollection");
              Document document = new Document("title", "MongoDB").
              append("description", "database").
              append("likes", 100).
              append("by", "Fly");
              List documents = new ArrayList();
              documents.add(document);
              collection.insertMany(documents);
              System.out.println("Connect to database successfully");
              } catch (Exception e) {
              System.err.println( e.getClass().getName() + ": " + e.getMessage() );
         }
      }
}
Sample codes:
javac -cp .:mongo-java-driver-3.2.0.jar MongoDBJDBC.java
java -cp .:mongo-java-driver-3.2.0.jar MongoDBJDBC

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 2 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:

import com.mongodb.ConnectionString;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoDatabase;
import com.mongodb.MongoClientSettings;
public class MyConnTest { 
    final public static void main(String[] args) { 
	try {
        // no ssl 
	ConnectionString connString = new ConnectionString("mongodb://rwuser:<password>@192.*.*.*:8635/test?authSource=admin");
	MongoClientSettings settings = MongoClientSettings.builder()
		.applyConnectionString(connString)
		.retryWrites(true)
		.build();
	MongoClient mongoClient = MongoClients.create(settings);
	MongoDatabase database = mongoClient.getDatabase("test");
     System.out.println("Connect to database successfully");  
	} catch (Exception e) { 
            e.printStackTrace(); 
            System.out.println("Test failed"); 
        } 
}
}