Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
Software Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ Document Database Service/ Best Practices/ Common Methods for Connecting to a DDS Instance

Common Methods for Connecting to a DDS Instance

Updated on 2024-05-20 GMT+08:00

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

      curl ip:port

      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.

    2. 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.
    3. If SSL is enabled, download the root certificate and upload it to the ECS.
  • 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

  • Precautions
    1. If SSL is enabled, the connection command must contain --ssl and --sslCAFile.
    2. --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
    1. 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.

      curl ip:port

      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.

    2. Install Python and third-party installation package pymongo on the ECS. Pymongo 2.8 is recommended.
    3. If SSL is enabled, download the root certificate and upload it to the ECS.
  • 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
  • Precautions
    1. {mydb} is the name of the database to be connected.
    2. The authentication database in the URL must be admin. Set authSource to admin.

Java Mongo

  • Prerequisites
    1. 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.

      curl ip:port

      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.

    2. Download the MongoDB JAR package compatible with the instance version by referring to the MongoDB Compatibility table.
    3. JDK is installed on the ECS.
    4. If SSL is enabled, download the root certificate and upload it to the ECS.
  • 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}

    NOTE:
    • /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
    1. In SSL mode, you need to manually generate the trustStore file.
    2. Change the authentication database to admin, and then switch to the service database after authentication.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback