Common Methods for Connecting to a DDS Instance
This section describes how to connect to a DDS instance using the following four methods:
- Mongo Shell
- Python Mongo
- Java Mongo
- Using Spring MongoTemplate to Perform MongoDB Operations
Mongo Shell
- Prerequisites
- To connect an ECS to a DDS instance, run the following command to connect to the IP address and port of the instance server to test the network connectivity.
If the message It looks like you are trying to access MongoDB over HTTP on the native driver port is displayed, the ECS and DDS instance can communicate with each other.
- Download the mongo shell package from the MongoDB official website. Decompress the package, obtain the mongosh file, and upload it to the ECS.
- If SSL is enabled, download the root certificate and upload it to the ECS.
- To connect an ECS to a DDS instance, run the following command to connect to the IP address and port of the instance server to test the network connectivity.
- Connection commands
- SSL is enabled.
Method 1: ./mongosh ip:port --authenticationDatabase admin -u username -p password --ssl --sslCAFile $path to certificate authority file --sslAllowInvalidHostnames
Method 2: ./mongosh "mongodb://<username >:<password>@ip:port/test?authSource=admin" --ssl --sslCAFile $path to certificate authority file --sslAllowInvalidHostnames
- SSL is disabled.
Method 1: ./mongosh ip:port --authenticationDatabase admin -u username -p password
Method 2: ./mongosh "mongodb://<username >:<password>@ip:port/test?authSource=admin"
Table 1 Parameter description Parameter
Description
ip
If you access an instance from an ECS, ip is the private IP address of the instance.
If you access an instance from a device over a public network, ip is the EIP bound to the instance,
port
Database port displayed on the Basic Information page. Default value: 8635
username
Current username
password
Password for the current username. In the connection method 2, when connecting to a DDS instance, escape the at sign (@), percent sign (%), and exclamation mark (!) and replace them with hexadecimal URL codes (ASCII codes) %40, %25, and %21, respectively.
path to certificate authority file
Path of the SSL certificate
- SSL is enabled.
- Precautions
- If SSL is enabled, the connection command must contain --ssl and --sslCAFile.
- --authenticationDatabase must be set to admin. If you log in to the database as user rwuser, switch to admin for authentication.
For details, see Connecting to an Instance in Getting Started with Document Database Service.
Python Mongo
- Prerequisites
- To connect an ECS to a DDS instance, run the following command to connect to the IP address and port of the instance server to test the network connectivity.
If the message It looks like you are trying to access MongoDB over HTTP on the native driver port is displayed, the network connectivity is normal.
- Install Python and third-party installation package pymongo on the ECS. Pymongo 2.8 is recommended.
- If SSL is enabled, download the root certificate and upload it to the ECS.
- To connect an ECS to a DDS instance, run the following command to connect to the IP address and port of the instance server to test the network connectivity.
- Input the connection code.
- SSL is enabled.
import ssl import os from pymongo import MongoClient # There will be security risks if the username and password used for authentication are directly written into code. Store the username and password in ciphertext in the configuration file or environment variables. # In this example, the username and password are stored in the environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV as needed. rwuser = os.getenv('EXAMPLE_USERNAME_ENV') password = os.getenv('EXAMPLE_PASSWORD_ENV') conn_urls="mongodb://%s:%s@ip:port/{mydb}?authSource=admin" connection = MongoClient(conn_urls % (rwuser, password),connectTimeoutMS=5000,ssl=True, ssl_cert_reqs=ssl.CERT_REQUIRED,ssl_match_hostname=False,ssl_ca_certs=${path to certificate authority file}) dbs = connection.database_names() print "connect database success! database names is %s" % dbs
- SSL is disabled.
import ssl import os from pymongo import MongoClient # There will be security risks if the username and password used for authentication are directly written into code. Store the username and password in ciphertext in the configuration file or environment variables. # In this example, the username and password are stored in the environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV as needed. rwuser = os.getenv('EXAMPLE_USERNAME_ENV') password = os.getenv('EXAMPLE_PASSWORD_ENV') conn_urls="mongodb://%s:%s@ip:port/{mydb}?authSource=admin" connection = MongoClient(conn_urls % (rwuser, password),connectTimeoutMS=5000) dbs = connection.database_names() print "connect database success! database names is %s" % dbs
- SSL is enabled.
- Precautions
- {mydb} is the name of the database to be connected.
- The authentication database in the URL must be admin. Set authSource to admin.
Java Mongo
- How to Use
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
- Computer basics
- Java
- 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/.
- Connecting to the Instance with 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 the SSL connection guide, see the MongoDB Java Driver official document at https://www.mongodb.com/docs/drivers/java/sync/v5.0/fundamentals/connection/tls/.
- 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.
If you connect to a cluster instance using Java, the format of code is as follows:mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&ssl=true
Table 2 Parameter description Parameter
Description
<username>
Current username.
<password>
Password for the current username.
<instance_ip>
If you access an instance from an ECS, instance_ip is the private IP address shown on the Basic Information page of the DB instance.
If you access an instance through an EIP, instance_ip is the EIP that has been bound to the instance.
If there are multiple IP addresses, 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 database. The value is admin.
ssl
Connection mode. true indicates that SSL will be used.
Use the keytool to configure the CA certificate. For details about the parameters, see Table 3.keytool -importcert -trustcacerts -file <path to certificate authority file> -keystore <path to trust store> -storepass <password>
Table 3 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>");
The following shows an 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"); } } }
- Connecting to the Instance Without an SSL Certificate
You do not need to download the SSL certificate because certificate verification on the server is not required.
If you connect to a cluster instance using Java, the format of code is as follows:mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin
Table 4 Parameter description Parameter
Description
<username>
Current username.
<password>
Password for the current username.
<instance_ip>
If you access an instance from an ECS, instance_ip is the private IP address shown on the Basic Information page of the DB instance.
If you access an instance through an EIP, instance_ip is the EIP that has been bound to the instance.
If there are multiple IP addresses, 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 database. The value is admin.
The following shows an 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"); 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"); } } }
Using Spring MongoTemplate to Perform MongoDB Operations
- How to Use
The following describes how to use Spring MongoTemplate to perform operations on MongoDB. For details, visit the MongoDB official website.
- Prerequisites
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <exclusions> <exclusion> <artifactId>spring-boot-starter-logging</artifactId> <groupId>org.springframework.boot</groupId> </exclusion> </exclusions> </dependency>
- Configuration Guide
spring: data: mongodb: #MongoDB configuration, which is for reference only // There will be security risks if the username and password used for authentication are directly written into code. Store the username and password in ciphertext in the configuration file or environment variables. // In this example, the username and password are stored in the environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV as needed. String userName = System.getenv("EXAMPLE_USERNAME_ENV"); String rwuserPassword = System.getenv("EXAMPLE_PASSWORD_ENV"); uri: mongodb://" + userName + ":" + rwuserPassword + "@192.***.***.***:8635,192.***.***.***:8635/${mongodb.database} database: ${mongodb.database}
- Development Guide
/** * MongoDB execution */ @Autowired private MongoTemplate template; /** * Log configuration */ @Autowired private LoggingProperties properties; @Override public void write(BaseLog businessLog, LoggingOption option) { if (template != null) { LoggingConfig config = properties.getBusinessConfig(businessLog.getCategory()); String collection = config.getMeta().get("collection"); if (StringUtils.isNotEmpty(collection)) { Object data = mapping(businessLog, config); template.save(data, collection); if (log.isDebugEnabled()) { log.debug("save audit log to mongodb successfully!, message: {}", StringEscapeUtils.escapeJava(TransformUtil.toJsonByJackson(businessLog))); } } else { log.warn("mongo log write log failed, mongoconfig is null"); } } else { log.warn("mongo log write log failed, mongoTemplate is null"); } }
- Precautions
- In SSL mode, you need to manually generate the trustStore file.
- Change the authentication database to admin, and then switch to the service database after authentication.
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