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

Connecting to a Database

Updated on 2024-02-07 GMT+08:00

Connecting to an Instance Using an SSL Certificate

NOTE:

Download the SSL certificate and verify the certificate before connecting to an instance.

In the DB Information area on the Basic Information page, click in the SSL field to download the root certificate or certificate bundle.

  1. Use Java to connect to the MongoDB database.

    • Connecting to a replica set
      mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&replicaSet=replica&ssl=true
      Table 1 Parameters

      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 of the instance.

      If you access an instance through an EIP, instance_ip is 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 SSL will be used.

    Example script in Java:

    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);
                  // 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 code:

    javac -cp .:mongo-java-driver-3.2.0.jar MongoDBJDBC.java
    java -cp .:mongo-java-driver-3.2.0.jar MongoDBJDBC

Connecting to an Instance Without the SSL Certificate

NOTE:

You do not need to download the SSL certificate because certificate verification on the server is not required.

  1. Use Java to connect to the MongoDB database.

    • Connecting to a replica set
      mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&replicaSet=replica
      Table 2 Parameters

      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 of the instance.

      If you access an instance through an EIP, instance_ip is 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:****@192.*.*.*:8635,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"); 
            } 
    }
    } 

Connecting to an Instance Using YML file

  1. Use YML file to connect to the MongoDB database.

    • Connecting to a replica set
      spring:
        data:
          mongodb:
            uri: mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&replicaSet=replica
      Table 3 Parameters

      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 of the instance.

      If you access an instance through an EIP, instance_ip is 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 using YML file:
      • application.yml
        spring:
          data:
            mongodb:
              uri: mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&replicaSet=replica
      • ITestService.java
        package com.springboot.cli.service;
        public interface ITestService {
            long doCount();
        }
      • TestServiceImpl.java
        package com.springboot.cli.service.impl;
        import com.springboot.cli.service.ITestService;
        import lombok.RequiredArgsConstructor;
        import org.springframework.data.mongodb.core.MongoTemplate;
        import org.springframework.stereotype.Service;
        @Service
        @RequiredArgsConstructor
        public class TestServiceImpl implements ITestService {
            private final MongoTemplate mongoTemplate;
            @Override
            public long doCount() {
                return mongoTemplate.estimatedCount("coll");
            }
        }
      • MongodbApplicationTests.java
        package com.springboot.cli;
        import com.springboot.cli.service.impl.TestServiceImpl;
        import org.junit.jupiter.api.Test;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.boot.test.context.SpringBootTest;
        import org.springframework.stereotype.Service;
        @SpringBootTest
        @Service
        class MongodbApplicationTests {
            @Autowired
            TestServiceImpl testService;
            @Test
            void doCount() {
                System.out.println("coll count is: " + testService.doCount());
            }
        }

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