LoginSignup
45
50

More than 5 years have passed since last update.

DynamoDBをlocal環境で動かしてみる

Last updated at Posted at 2016-10-27

Dynamodbをlocal環境で動かすメモ

AWS上で使っているDynamodbに対して色々開発段階でデバッグなどしたい!
でも、アクセスしまくって課金されるのは困る。
みたいな時、Dynamodbには「DynamoDB Local」という、ローカルマシン内で稼働するdownloadable version of DynamoDBが公開されています。

公式のドキュメントに詳しく書かれています。
日本語版もあります。

環境

OSX 10.11.4
Java 1.8.0_101
IntelliJ IDEA 2016.1.4
Homebrew 1.0.8 もしくは pipとか(今回はHomebrewを使っています)

DynamodbLocalのセットアップ

[Step1]DynamodbLocalをダウンロード

ドキュメントにもある通りいずれかからダウンロード。

形式 URL
tar.gz 形式 http://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.tar.gz
zip 形式 http://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.zip

[Step2]任意のディレクトリ下で展開し、そのディレクトリ下に移動

こんな感じです
スクリーンショット 2016-10-27 8.33.10.png

[Step3]DynamodbLocalを起動

ここも、ドキュメントにあるようにまずはDynamodbLocalを起動してみます。

$ java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb
Initializing DynamoDB Local with the following configuration:
Port:   8000
InMemory:   false
DbPath: null
SharedDb:   true
shouldDelayTransientStatuses:   false
CorsParams: *

これで起動は完了です。終了する場合はCtrl+Cです。

AWS コマンドラインインターフェイス (CLI)のインストール

[Step1]インストールします

公式ドキュメントではpipでaws-cliをインストールしていますが、homebrewで今回はインストールします。
これによって、コマンドラインで、Dynamodbのテーブルを作成したり、確認したりいろいろできるようになります。

$ sudo brew install awscli
Password:
~~~~省略~~~~
==> Renamed Formulae
stash-cli -> atlassian-cli
==> Deleted Formulae
dwarf                       jsdoc-toolkit               puddletag                   sonar-runner
homebrew/science/minc       libmarisa                   qbzr                        treeline

==> Downloading https://homebrew.bintray.com/bottles/awscli-1.11.10.el_capitan.bottle.tar.gz
######################################################################## 100.0%
==> Pouring awscli-1.11.10.el_capitan.bottle.tar.gz
==> Caveats
The "examples" directory has been installed to:
  /usr/local/share/awscli/examples

Before using aws-cli, you need to tell it about your AWS credentials.
The quickest way to do this is to run:
  aws configure

More information:
  https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
  https://pypi.python.org/pypi/awscli#getting-started

Bash completion has been installed to:
  /usr/local/etc/bash_completion.d

zsh completion has been installed to:
  /usr/local/share/zsh/site-functions
==> Summary
🍺  /usr/local/Cellar/awscli/1.11.10: 3,459 files, 28.4M

[Step2]aws configureの設定

http://www.task-notes.com/entry/20141026/1414322858
などを参考に。

$aws configure
AWS Access Key ID [None]: accesskey
AWS Secret Access Key [None]: secretkey
Default region name [None]: localhost:8000
Default output format [None]: 

[Step3]DynamoDB JavaScript consoleを立ち上げる

DynamodbLocalを起動している状態で、
http://localhost:8000/shell/
を開くと、以下のようなDynamoDB JavaScript consoleが開きます。

詳細な使い方についてはこちらがかなりわかりやすかったです。
http://dev.classmethod.jp/cloud/aws/dynamodb-local-shell-console/

[Step4]DynamodbLocalのtableをaws-cliで出力

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

ここではまだ何もtableが登録されていないのでtableは空です

IntelliJ IDEAでDynamodbを触るプロジェクトを作ってみる(Java)

[Step1]IntelliJをダウンロード・インストールします

Comunity(無償)でも問題ないと思いますが(使ったことないですが)学生はUltimateも無料なのでそちらを使いましょう!
https://www.jetbrains.com/idea/
違いについてはこちらにまとまっています

[Step2]IntelliJを起動

[Step2]プロジェクトを作成(Create New Project)

Mavenを選択しProjectSDKはJava1.8にしました。


[Step3]テーブル作成のプロジェクトを作る

以下のStepではこのGettingStartedを参考にしています。というかコードはそのままです。
https://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/gettingstartedguide/GettingStarted.Java.html

Javaファイルを作成します

作成先で以下のコードをコピペしてみましょう。

MoviesCreateTable.java
import java.util.Arrays;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
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 {

        AmazonDynamoDBClient client = new AmazonDynamoDBClient()
                .withEndpoint("http://localhost:8000");

        DynamoDB dynamoDB = new DynamoDB(client);

        String tableName = "Movies";

        try {
            System.out.println("Attempting to create table; please wait...");
            Table table = dynamoDB.createTable(tableName,
                    Arrays.asList(
                            new KeySchemaElement("year", KeyType.HASH),  //Partition key
                            new KeySchemaElement("title", KeyType.RANGE)), //Sort key
                    Arrays.asList(
                            new AttributeDefinition("year", ScalarAttributeType.N),
                            new AttributeDefinition("title", ScalarAttributeType.S)),
                    new ProvisionedThroughput(10L, 10L));
            table.waitForActive();
            System.out.println("Success.  Table status: " + table.getDescription().getTableStatus());

        } catch (Exception e) {
            System.err.println("Unable to create table: ");
            System.err.println(e.getMessage());
        }

    }
}

真っ赤になりました。

Add Maven Dependency... を行います

全て選択しAddします

右上にImport Changesとでてくるのでクリックすると

赤いのが消えます!

これはpom.xmlを確認してもらえれば分かりますが

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>hiroki11x</groupId>
    <artifactId>DynamodbSample</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-dynamodb</artifactId>
            <version>1.11.41</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-dynamodb</artifactId>
            <version>1.11.41</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-dynamodb</artifactId>
            <version>1.11.41</version>
        </dependency>
    </dependencies>
</project>

みたいにプロジェクトが依存するライブラリが指定されています。

現段階ではaws-cliでテーブルのリストを出力すると

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

ですが、先ほどのMoviesCreateTable.javaを実行すると

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

Moviesが追加されました!
あとはGettingStartedに色々あるので引き続きこの記事に追加していこうと思います。

参考

追記(メモ)

別のローカル環境でgithub経由で環境(http://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.zip を展開したもの)をcloneして使おうとしたら、

$ aws dynamodb list-tables --endpoint-url http://localhost:8000

だとか

MoviesCreateTable.java
//~(略)~
Table table = dynamoDB.createTable(tableName, //~(略)~
//~(略)~

みたいなことしても、反応がない、、
みたいなことがありました。その場合、環境のファイル郡やディレクトリ構成、gitignoreされたファイルがあるなどが原因だったのでメモ

45
50
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
45
50