Updated on 2024-01-18 GMT+08:00

Connecting to a Database

Prerequisites

  1. To connect an ECS to an instance, the ECS must be able to communicate with the DDS instance. You can 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. If SSL is enabled, download the root certificate and upload it to the ECS.

Connection Code

  • Enabling SSL
    //Construct an authentication credential.
    // 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.
    username = System.getenv("EXAMPLE_USERNAME_ENV")
    password = System.getenv("EXAMPLE_PASSWORD_ENV")
    credential := options.Credential{
      AuthMechanism: "SCRAM-SHA-1",
      AuthSource:    "admin",
      Username:      username,
      Password:      password, 
    }
    //HA URI. Note that SetDirect is set to false.
    highProxyUri := "mongodb://host1:8635,host2:8635/?ssl=true"
    clientOpts := options.Client().ApplyURI(highProxyUri)
    clientOpts = clientOpts.SetTLSConfig(&tls.Config {
    InsecureSkipVerify: true,
    }).SetDirect(false).SetAuth(credential)
    //URI of the direct connection. Note that SetDirect is set to true.
    //directUri := "mongodb://host:8635/?ssl=true"
    //clientOpts := options.Client().ApplyURI(highProxyUri)
    //clientOpts = clientOpts.SetTLSConfig(&tls.Config {
    // InsecureSkipVerify: true,
    //}).SetDirect(true).SetAuth(credential)
    // Connecting to an instance
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    client, err := mongo.Connect(ctx, clientOpts)
    if err != nil {
       fmt.Println("Failed to connect to the mongo instance:", err)
       return
    }
    //Ping the primary node.
    ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()err = client.Ping(ctx, readpref.Primary())
    if err != nil {fmt.Println ("Failed to ping the primary node: ",err)
       return
    }
    //Select the database and collection.
    collection := client.Database("test").Collection("numbers")
    //Insert a record.
    ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    oneRes, err := collection.InsertOne(ctx, bson.D{{"name", "e"}, {"value", 2.718}})
    if err != nil{fmt.Println("Failed to insert a record: ",err)
       return
    }else {
       fmt.Println(oneRes)
    }
    // Batch insert
    ctx, cancel = context.WithTimeout(context.Background(), 100*time.Second)
    defer cancel()
    docs := make([]interface{}, 100)
    for i := 0; i < 100; i++{
       docs[i] = bson.D{{"name", "name"+strconv.Itoa(i)}, {"value", i}}
    }
    manyRes, err := collection.InsertMany(ctx, docs)
    if err != nil {
       fmt.Println("Batch insertion failed: ",err)
       return
    }else {
       fmt.Println(manyRes)
    }
    
  • Disabling SSL
    //HA connection. The value of readPreference is primary (by default), indicating that the primary node is read-only. The value primaryPreferred indicates that the primary node is preferred. If the primary node is unavailable, the secondary node is read.
    // Secondary: read-only node. If the secondary node is unavailable, an error is reported. secondaryPreferred: The secondary node is preferred. If the secondary node is unavailable, the primary node is read.
    // 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.
    username = System.getenv("EXAMPLE_USERNAME_ENV")
    password = System.getenv("EXAMPLE_PASSWORD_ENV")
    highProxyUri := fmt.Sprintf("mongodb://%v:%v@host1:8635,host2:8635/?authSource=admin&replicaSet=replica&readPreference=secondaryPreferred",username,password)
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    clientOpts := options.Client().ApplyURI(highProxyUri)
    client, err := mongo.Connect(ctx, clientOpts)
    //Ping the primary node.
    ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()err = client.Ping(ctx, readpref.Primary())
    if err != nil {
       fmt.Println("Failed to ping the primary node: ",err)
       return
    }
    //Select the database and collection.
    collection := client.Database("test").Collection("numbers")
    //Insert a record.
    ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    res, err := collection.InsertOne(ctx, bson.D{{"name", "e"}, {"value", 2.718}})
    if err != nil{
       fmt.Println("Failed to insert a record: ",err)
       return
    }else {
       fmt.Println(res)
    }