全部產品
Search
文件中心

:通過程式碼串連DynamoDB協議相容版執行個體

更新時間:May 07, 2025

本文檔通過AWS CLI、Python、Java多個維度,介紹如何串連到DynamoDB協議相容版執行個體。

前提條件

已建立DynamoDB協議相容版執行個體(協議類型選擇DynamoDB協議),建立方法請參見建立分區叢集執行個體

準備工作

擷取DynamoDB協議相容版執行個體的串連地址。

  1. 登入MongoDB管理主控台

  2. 在頁面左上方,選擇執行個體所在的資源群組和地區。

  3. 在左側導覽列,單擊分區叢集執行個體列表

  4. 找到目標執行個體,單擊執行個體ID。

  5. 在左側導覽列,單擊資料庫連接

  6. 私網串連 - 專用網路地區,查看執行個體的串連地址。串連地址

如果應用部署在ECS執行個體,您需要確保ApsaraDB for MongoDB執行個體和ECS伺服器滿足以下條件,以保證網路的連通性。

AWS CLI串連樣本

以Ubuntu 16.04.6 LTS系統為例介紹通過AWS CLI(AWS Command Line Interface)串連DynamoDB協議相容版執行個體的方法。關於AWS CLI的詳細資料,請參見AWS Command Line Interface是什麼

  1. 安裝AWS CLI用戶端。

    1. 執行如下命令,擷取最新版的AWS CLI並將其重新命名為awscliv2.zip

      curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
    2. 執行如下命令,解壓awscliv2.zip檔案。

      unzip awscliv2.zip
      說明

      如果您尚未安裝unzip,請先通過sudo apt install unzip命令安裝,然後再執行上面的解壓命令。

    3. 執行如下命令,安裝AWS CLI。

      sudo ./aws/install

    當命令列視窗中出現You can now run: /usr/local/bin/aws --version提示,則表示您已成功安裝AWS CLI。此時您可以執行/usr/local/bin/aws --version命令查看當前AWS CLI的版本號碼。

  2. 執行/usr/local/bin/aws configure配置AWS CLI,分別輸入下列幾項參數(每輸入一項參數按斷行符號):

    參數

    說明

    樣本

    AWS Access Key ID

    輸入您AWS帳號的Access Key ID,如沒有可以輸入任一字元。

    XXXXXXXXXX

    AWS Secret Access Key

    輸入您AWS帳號的Secret Access Key,如沒有可以輸入任一字元。

    XXXXXXXXXX

    Default region name

    輸入您AWS的DynamoDB資料庫所在的地區,如沒有可以根據樣本輸入。

    us-west-2

    Default output format

    預設的輸出格式,此處可以留空。

    json

    說明

    更多AWS CLI配置說明的相關資訊,請參見AWS CLI基本配置

  3. 執行如下命令,串連目標DynamoDB協議相容版執行個體並建立一張表。

    aws dynamodb --endpoint-url <DynamoDB協議相容版執行個體的串連串地址> \ 
        create-table --table-name <需要建立的表名> \
        --attribute-definitions AttributeName=<屬性名稱>,AttributeType=<屬性的資料類型> \
        --key-schema AttributeName=<指定主鍵的屬性名稱>,KeyType=<主鍵的角色> \
        --provisioned-throughput ReadCapacityUnits=<預設讀輸送量>,WriteCapacityUnits=<預設寫輸送量>

    參數

    說明

    --endpoint-url

    需要串連的目標DynamoDB協議相容版執行個體地址。需要以HTTP://開頭。

    create-table

    建立表的命令。

    說明

    更多資訊,請參見create-table

    --table-name

    指定需要建立表的名稱。

    --attribute-definitions

    描述表或索引整體架構的屬性數組。該選項還需指定如下兩個子選項:

    • AttributeName:屬性的名稱。

    • AttributeType:屬性的資料類型。

      說明

      更多資訊,請參見create-table

    --key-schema

    指定表或索引的主鍵屬性。該選項還需指定如下兩個子選項:

    • AttributeName:指定通過--attribute-definitions建立的某個屬性名稱為主鍵。

    • KeyType:指定主鍵的角色。

      說明

      更多資訊,請參見create-table

    --provisioned-throughput

    指定表或索引的預設輸送量。該選項還需指定如下兩個子選項:

    • ReadCapacityUnits:指定預設讀輸送量。

    • WriteCapacityUnits:指定預設寫輸送量。

    說明

    更多資訊,請參見create-table

    樣本:

    /usr/local/bin/aws dynamodb --endpoint-url http://dds-xxxx.mongodb.rds.aliyuncs.com:3717 #串連到指定的DynamoDB協議相容版執行個體地址。 \
        create-table --table-name student #建立一個名為student的表。 \
        --attribute-definitions AttributeName=name,AttributeType=S AttributeName=age,AttributeType=N #表的架構中,有類型為String的name屬性和類型為Number的age屬性。 \
        --key-schema AttributeName=name,KeyType=HASH AttributeName=age,KeyType=RANGE #指定name屬性為分區鍵,並指定age屬性為排序鍵。 \
        --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 #指定預設的讀寫輸送量各為5。

    當命令列中列印出如下內容,則表示您已成功串連到目標DynamoDB協議相容版執行個體並建立了一張表。

    {
        "TableDescription": {
            "TableName": "student",
            "KeySchema": [
                {
                    "AttributeName": "name",
                    "KeyType": "HASH"
                },
                {
                    "AttributeName": "age",
                    "KeyType": "RANGE"
                }
            ],
            "TableStatus": "CREATING",
            "TableSizeBytes": 0,
            "ItemCount": 0
        }
    }
                            

Python串連樣本

  • 已安裝Python 2.6或更高版本。更多資訊,請參見Python官網

  • 已安裝Boto3。更多資訊,請參見安裝Boto3

以下代碼示範通過Python串連到DynamoDB協議相容版執行個體並建立一個名為Book的表:

import boto3

def create_book_table(dynamodb=None):
 if not dynamodb:
 dynamodb = boto3.resource('dynamodb', endpoint_url="http://dds-xxxx.mongodb.rds.aliyuncs.com:3717")
 table = dynamodb.create_table(
 TableName='Book',
 KeySchema=[
 {
 'AttributeName':'title',
 'KeyType':'HASH'
 },
 {
 'AttributeName':'year',
 'KeyType':'RANGE'
 }
 ],
 AttributeDefinitions=[
 {
 'AttributeName':'title',
 'AttributeType':'S'
 },
 {
 'AttributeName':'year',
 'AttributeType':'N'
 },
 ],
 ProvisionedThroughput={
 'ReadCapacityUnits':5,
 'WriteCapacityUnits':5
 }
 )
 return table

if __name__ == '__main__':
 book_table =create_book_table()
 print("Tablestatus:", book_table.table_status)

Java串連樣本

安裝AWS SDK for Java,具體請參見安裝AWS SDK for Java

以下代碼示範通過Java串連到DynamoDB協議相容版執行個體並建立一個名為Book的表:

package com.amazonaws.codesamples.gsg;

import java.util.Arrays;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;

public class MoviesCreateTable {
 public static void main(String[] args) throws Exception {
 
        AmazonDynamoDB client =AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://dds-xxxx.mongodb.rds.aliyuncs.com:3717",
"us-east-1"))
            .build();

 DynamoDB dynamoDB = new DynamoDB(client);

 String tableName ="Book";

 try {
 System.out.println("Creating table...");
 Table table =dynamoDB.createTable(tableName,
 Arrays.asList(new
KeySchemaElement("title", KeyType.HASH), // 分區鍵
 new KeySchemaElement("year", KeyType.RANGE)), // 排序鍵
 Arrays.asList(new AttributeDefinition("title", ScalarAttributeType.S),
 new AttributeDefinition("year", ScalarAttributeType.N)),
 new ProvisionedThroughput(5L, 5L));
 table.waitForActive();
System.out.println("OK. Table status: " + table.getDescription().getTableStatus());
 }
 catch (Exception e) {
System.err.println("Unable to create table: ");
System.err.println(e.getMessage());
 }
 }
}

其他程式碼的串連樣本

請參見開始使用DynamoDB和AWS開發套件