Esta página ainda não está disponível no idioma selecionado. Estamos trabalhando para adicionar mais opções de idiomas. Agradecemos sua compreensão.

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-01-23 GMT+08:00

Using an SSL Certificate

NOTE:

Download the SSL certificate and verify the certificate before connecting to databases.

In the DB Instance 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.

    • Connect to a single node:
      mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&ssl=true
    • Connect to a replica set.
      mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&replicaSet=replica&ssl=true
    • Connect to a cluster:
      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 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 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");
                  // 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 code:

    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

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. The Java code format is as follows:

    • Connect to a single node:
      mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin
    • Connect to a replica set.
      mongodb://<username>:<password>@<instance_ip>:<instance_port>/<database_name>?authSource=admin&replicaSet=replica
    • Connect to a cluster:
      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 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 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 
            // 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");
    	ConnectionString connString = new ConnectionString("mongodb://" + userName + ":" + rwuserPassword + "@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"); 
            } 
    }
    } 

Usamos cookies para aprimorar nosso site e sua experiência. Ao continuar a navegar em nosso site, você aceita nossa política de cookies. Saiba mais

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback