Docker + DynamoDB local + C ++ environment construction and practice

Environment

Click here for what to use this time

Also, use VC ++ for the C ++ build environment.

Introducing Docker

Docker is a software platform that allows you to quickly build, test, and deploy applications using containers.

https://www.docker.com/

download

Download the installer from the Docker site.

Installation

Docker Desktop requires Windows 10 Pro/Enterprise (16299+) or Windows 10 Home (18362.1040+). If you get the above error message during installation, please check Windows Update. After the update, try the installation again.

Version confirmation

Let's check the version of Docker from the command line. If the installation is successful, you should get output similar to the following:

> docker --version
Docker version 20.10.0, build 7287ab3

Introducing DynamoDB local

The downloadable version of Amazon DynamoDB (DynamoDB local) allows you to develop and test your application without accessing the DynamoDB web service. Instead, the database is self-contained on the computer.

Get an image

Let's use Docker to get the DynamoDB local image.

Since there is a Docker image of DynamoDB local published by Amazon, Get it using the docker pull command.

> docker pull amazon/dynamodb-local

Start the container

Let's use Docker to start DynamoDB local. Start it using the docker run command.

> docker run -p 8000:8000 amazon/dynamodb-local

The DynamoDB local container is now started. I used 8000 as the port number for easy understanding.

Check the container

The docker ps command prints a list of currently running containers.

> docker ps
CONTAINER ID   IMAGE                   COMMAND                  CREATED         STATUS         PORTS                    NAMES
607c8a202aac   amazon/dynamodb-local   "java -jar DynamoDBL…"   2 seconds ago   Up 7 seconds   0.0.0.0:8000->8000/tcp   frosty_goldstine

Exit the container

You can use the docker kill command to kill a running container. At this time, specify the container ID.

> docker kill 607c8a202aac

Introducing AWS CLI version 2

The AWS CLI includes command line tools for working with DynamoDB local.

Let's install it in advance. https://docs.aws.amazon.com/ja_jp/cli/latest/userguide/install-cliv2-windows.html

Initial setting

Let's set these 4 items only once.

Each setting can be a dummy, but you need to remember it. If you forget it, set it again.

> aws configure
AWS Access Key ID [****************XXXX]:(Since it is used locally, a dummy key ID is sufficient)
AWS Secret Access Key [****************XXXX]:(Since it is used locally, a dummy access key is sufficient)
Default region name [us-west-2]:(Dummy region is fine as it is used locally)
Default output format [json]:

Operation check (get the table list of DynamoDB local)

Let's access DynamoDB local and check the operation. Since we haven't created the table yet, we should be able to get the following JSON.

> aws dynamodb list-tables --endpoint-url http://localhost:8000
{
    "TableNames": []
}

Introducing AWS SDK for C ++

This time, we'll be accessing DynamoDB local from C ++, so we'll use a library called ** AWS SDK for C ++ **.

Install vcpkg

vcpkg is a C ++ command line package manager. This greatly simplifies the task of retrieving and installing third-party libraries on Windows, Linux, and macOS.

https://github.com/Microsoft/vcpkg

Get it from github and run bootstrap.

> git clone https://github.com/microsoft/vcpkg
> ./vcpkg/bootstrap-vcpkg.bat

Get the AWS SDK for C ++

Use vcpkg to get the library.

> ./vcpkg/vcpkg install aws-sdk-cpp:x64-windows

Integrate into VC ++

Integrate vcpkg into VC ++. This will automatically set the include path for the AWS SDK for C ++ you downloaded earlier and link the .lib.

> ./vcpkg/vcpkg integrate install

Also, if you want to cancel the integration, use the following command.

> ./vcpkg/vcpkg integrate remove

coding

Here are the major database operations and the corresponding AWS SDK for C ++ function names. There is also sample code on the AWS site, so please refer to it.

Use Function name
Add table Aws::DynamoDB::DynamoDBClient::CreateTable
Delete table Aws::DynamoDB::DynamoDBClient::DeleteTable
Item acquisition Aws::DynamoDB::DynamoDBClient::GetItem
Item addition Aws::DynamoDB::DynamoDBClient::PutItem
Item update Aws::DynamoDB::DynamoDBClient::UpdateItem
Item deletion Aws::DynamoDB::DynamoDBClient::DeleteItem

C++ Code Samples for Amazon DynamoDB https://docs.aws.amazon.com/code-samples/latest/catalog/code-catalog-cpp-example_code-dynamodb.html

Create-table

#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h> 
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/CreateTableRequest.h>
#include <aws/dynamodb/model/KeySchemaElement.h>
#include <aws/dynamodb/model/ProvisionedThroughput.h>
#include <aws/dynamodb/model/ScalarAttributeType.h>
#include <iostream>

//Here, use the preset access key
const Aws::String AWS_ACCESS_KEY_ID     = "XXXXXXXXXXXXXXXXXXXX";
const Aws::String AWS_SECRET_ACCESS_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

Aws::SDKOptions options;
Aws::InitAPI(options);

//Decide the name of the table you want to create
const Aws::String table("Game");
//Here, use the preset region name
const Aws::String region("us-west-2");

//Specify the endpoint
Aws::Client::ClientConfiguration clientConfig;
clientConfig.requestTimeoutMs = 1000;
clientConfig.region = region;
clientConfig.endpointOverride = "http://localhost:8000";

const Aws::DynamoDB::DynamoDBClient dynamoClient(Aws::Auth::AWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY), clientConfig);

//Table creation request
Aws::DynamoDB::Model::CreateTableRequest req;

Aws::DynamoDB::Model::AttributeDefinition haskKey;
// "Name"Define an attribute named,"Name"Is a string type
haskKey.SetAttributeName("Name");
haskKey.SetAttributeType(Aws::DynamoDB::Model::ScalarAttributeType::S);
req.AddAttributeDefinitions(haskKey);

// "Name"Define the schema to treat as a hash key (partition key)
Aws::DynamoDB::Model::KeySchemaElement keyscelt;
keyscelt.WithAttributeName("Name").WithKeyType(Aws::DynamoDB::Model::KeyType::HASH);
req.AddKeySchema(keyscelt);

//Set an appropriate capacity unit
Aws::DynamoDB::Model::ProvisionedThroughput thruput;
thruput.WithReadCapacityUnits(5).WithWriteCapacityUnits(5);
req.SetProvisionedThroughput(thruput);

//Specify the table name
req.SetTableName(table);

//Send a table creation request to DynamoDB local (note that this function blocks!)
const Aws::DynamoDB::Model::CreateTableOutcome& result = dynamoClient.CreateTable(req);
if (result.IsSuccess())
{
    std::cout << "Table \"" << result.GetResult().GetTableDescription().GetTableName() <<
        " created!" << std::endl;
}
else
{
    std::cout << "Failed to create table: " << result.GetError().GetMessage();
}

Aws::ShutdownAPI(options);

Let's check if the table has been created using the AWS CLI. If you've created it successfully, you should be able to get the following JSON.

> aws dynamodb list-tables --endpoint-url http://localhost:8000
{
    "TableNames": [
        "Game"
    ]
}

Add item (put-item)

#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h> 
#include <aws/core/auth/AWSCredentialsProvider.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
//#include <aws/dynamodb/model/CreateTableRequest.h>
#include <aws/dynamodb/model/PutItemRequest.h>
#include <aws/dynamodb/model/PutItemResult.h>
#include <iostream>

//(Omitted in the middle...)

Aws::DynamoDB::Model::PutItemRequest req;
//Specify the target table name
req.SetTableName(table);

Aws::DynamoDB::Model::AttributeValue av;

// "Name"Is a string type"Switch"
av.SetS("Switch");
req.AddItem("Name", av);

// "State"Is a string type"off"
av.SetS("off");
req.AddItem("State",av);

//Send an item addition request to DynamoDB local (note that this function blocks!)
const Aws::DynamoDB::Model::PutItemOutcome result = dynamoClient.PutItem(req);
if (!result.IsSuccess())
{
    std::cout << result.GetError().GetMessage() << std::endl;
    return 1;
}
std::cout << "Done!" << std::endl;

//(Omitted in the middle...)

Let's output the contents of the table using the AWS CLI. If you pass the table name to the aws dynamodb scan command, you can get the contents of the table in JSON as shown below.

> aws dynamodb scan --table-name Game --endpoint-url http://localhost:8000
{
    "Items": [
        {
            "State": {
                "S": "off"
            },
            "Name": {
                "S": "Switch"
            }
        }
    ],
    "Count": 1,
    "ScannedCount": 1,
    "ConsumedCapacity": null
}

in conclusion

It's been a long way, but I was able to work with DynamoDB local from C ++. The AWS SDK for C ++ is easy to work with and has a complete set of APIs for working with DynamoDB. With this in place, DynamoDB's threshold would be lowered for C ++ programmers at once.

DynamoDB local makes it easy to add and remove records, so it's also recommended for prototyping.

Recommended Posts

Docker + DynamoDB local + C ++ environment construction and practice
Docker environment construction
Rails Docker environment construction
Protobuf and gRPC C ++ environment construction on Ubuntu 18.04
Kaggle environment construction using official Docker and vscode
A reminder of Docker and development environment construction
Wordpress local environment construction & development procedure with Docker
Build WordPress environment with Docker (Local) and AWS (Production)
EC-CUBE4 environment construction (local edition)
MySQL 5.7 (Docker) environment construction memo
Redmine (Docker) environment construction memo
[Docker] Rails 5.2 environment construction with docker
Docker × Spring Boot environment construction
[Docker] postgres, pgadmin4 environment construction
React environment construction with Docker
Build DynamoDB local with Docker
Easy environment construction of MySQL and Redis with Docker and Alfred
Rails + MySQL environment construction with Docker
Node.js environment construction with Docker Compose
Build Couchbase local environment with Docker
Environment construction with Docker for beginners
Laravel + Docker Laradock usage environment construction
Hello World with Docker and C
Rails on Docker environment construction procedure
[Environment construction with Docker] Rails 6 & MySQL 8
[Environment construction] Uninstall rails from local
SQL statement learning ~ Environment construction ~ Docker + MySQL
GPU environment construction with Docker [October 2020 version]
Rails environment construction with Docker (personal apocalypse)
Building Rails 6 and PostgreSQL environment with Docker
Laravel development environment construction with Docker (Mac)
Sapper × Go (echo) × Docker development environment construction
Environment construction with Docker (Ubuntu20.04) + Laravel + nginx
[Docker] Development environment construction Rails6 / Ruby2.7 / MySQL8
Spring Boot + Docker Java development environment construction
Laravel + MySQL + phpMyadmin environment construction with Docker
[Environment construction] Docker startup error! Steps to enable Hyper-V and start Docker again
Install Docker and create Java runtime environment
Environment construction summary with rvm and postgresql
Minimal Java environment construction and Hello World
Try local development of AWS (S3, DynamoDB) with AWS SDK for JavaScript and Docker
Spring Boot environment construction with Docker (January 2021 version)
(Basic authentication) environment variables in rails and Docker
Environment construction command memo with Docker on AWS
CI / CD practice for beginners --Part1 --Environment construction
Rails6 [API mode] + MySQL5.7 environment construction with Docker
[Notepad ++] C language / Java compilation & execution environment construction
Prepare a scraping environment with Docker and Java
IntelliJ + Docker (APP + DB) + SpringBoot (Maven) environment construction
React + Django + Nginx + MySQL environment construction with Docker
Docker × Laravel HTTPS (SSL) communication in local environment
Environment construction method and troubleshooter at the time of joint development (rails, docker and github)
Environment construction of keras and tensorflow, jupyter lab by docker and connection to jupyter by port forwarding
[Java] Environment construction
Java environment construction
[Spring] Environment construction
BEAR application Docker development environment construction example (docker-sync, Mutagen)
virtulbox + vagrant + Docker + nginx + puma + MySQL Rails environment construction
A command that definitely cleans the local docker environment
SSL in the local environment of Docker / Rails / puma
Comfortable Docker environment created with WSL2 CentOS7 and Docker Desktop