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 client installation package whose version is the same as the instance version from the MongoDB official website. Decompress the package, obtain the mongo 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.
./mongo ip:port --authenticationDatabase admin -u username -p password --ssl --sslCAFile $path to certificate authority file --sslAllowInvalidHostnames
- SSL is disabled.
./mongo ip:port --authenticationDatabase admin -u username -p password
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 of the current username
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
- 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 MongoDB JAR package compatible with the instance version by referring to the MongoDB Compatibility table.
- JDK is installed on 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.
- Input the connection code.
Use keytool to generate a trustStore.
// 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 password = System.getenv("EXAMPLE_PASSWORD_ENV");
keytool -import -file /var/chroot/mongodb/CA/ca.crt -keystore /home/Mike/jdk1.8.0_112/jre/lib/security/mongostore -storetype pkcs12 -storepass ${password}
- /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.
- SSL is enabled.
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"); // 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 password = System.getenv("EXAMPLE_PASSWORD_ENV"); System.setProperty("javax.net.ssl.trustStorePassword", password); ServerAddress serverAddress = new ServerAddress("ip", port); List addrs = new ArrayList(); addrs.add(serverAddress); // 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"); 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
- SSL is disabled.
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 { ServerAddress serverAddress = new ServerAddress("ip", port); List addrs = new ArrayList(); addrs.add(serverAddress); // 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"); MongoCredential credential = MongoCredential.createScramSha1Credential("rwuser", "admin", rwuserPassword.toCharArray()); List credentials = new ArrayList(); credentials.add(credential); MongoClient mongoClient = new MongoClient(addrs,credentials); 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() ); } } }
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