Nodejs课堂笔记-第五课 在nodejs中使用DynamoDB Local

从博客园搬到了CSDN,具体原因就不明说了,简单一句话就是原创被当抄袭,这种感觉很不爽。

好了,我们继续开始学习历程吧。在第四课中,我们介绍了DynamoDB Local版本的使用方式。这节课中,我们开始在nodejs中使用DynamoDB。

在Amazon的网站中,提供了一个DynamoDB的sample,请看下面:

// Load the SDK and UUID
var AWS = require('aws-sdk');
var uuid = require('node-uuid');

// Create an S3 client
var s3 = new AWS.S3();

// Create a bucket and upload something into it
var bucketName = 'node-sdk-sample-' + uuid.v4();
var keyName = 'hello_world.txt';

s3.createBucket({Bucket: bucketName}, function() {
  var params = {Bucket: bucketName, Key: keyName, Body: 'Hello World!'};
  s3.putObject(params, function(err, data) {
    if (err)
      console.log(err)
    else
      console.log("Successfully uploaded data to " + bucketName + "/" + keyName);
  });
});

这段示例代码直接使用的DynamoDB Web Service,而不是DynamoDB Local服务。和我们的需求不太一样,所以再次研究Amazon的API文档。

看到dynamodb在使用之前需要配置amazon账户,点击这里查看配置说明。 按照文档中的说明,我们补充下面的配置代码:

/* Auth Config */
AWS.config.update({
    aws_access_key_id : "andy-aws-account",
    aws_secret_access_key : "andy-aws-account",
    region : "eu-west-1"
})

在第四课中提到过,当使用local模式时,账户信息都会被忽略。因此输入任意账户信息都可以。

下一步就是创建一个指向local的endpoint,我们使用下面代码进行创建:

dyn= new AWS.DynamoDB({ endpoint: new AWS.Endpoint('http://localhost:8000') });

当endpoint创建成功后,就相当于获取了一个dynamodb的实例,下面就可以执行SQL操作了。我们首先做一个简单的操作:创建一张表,再查询所有表。

在dynamodb的api中,创建表的API是(点击这里,查看API文档):

createTable(params = {}, callback) ⇒ AWS.Request

需要给createTable传递一个参数对象,这个参数对象有些复杂:

var params = {
  AttributeDefinitions: [ /* required */
    {
      AttributeName: 'STRING_VALUE', /* required */
      AttributeType: 'S | N | B' /* required */
    },
    /* more items */
  ],
  KeySchema: [ /* required */
    {
      AttributeName: 'STRING_VALUE', /* required */
      KeyType: 'HASH | RANGE' /* required */
    },
    /* more items */
  ],
  ProvisionedThroughput: { /* required */
    ReadCapacityUnits: 0, /* required */
    WriteCapacityUnits: 0 /* required */
  },
  TableName: 'STRING_VALUE', /* required */
  GlobalSecondaryIndexes: [
    {
      IndexName: 'STRING_VALUE', /* required */
      KeySchema: [ /* required */
        {
          AttributeName: 'STRING_VALUE', /* required */
          KeyType: 'HASH | RANGE' /* required */
        },
        /* more items */
      ],
      Projection: { /* required */
        NonKeyAttributes: [
          'STRING_VALUE',
          /* more items */
        ],
        ProjectionType: 'ALL | KEYS_ONLY | INCLUDE'
      },
      ProvisionedThroughput: { /* required */
        ReadCapacityUnits: 0, /* required */
        WriteCapacityUnits: 0 /* required */
      }
    },
    /* more items */
  ],
  LocalSecondaryIndexes: [
    {
      IndexName: 'STRING_VALUE', /* required */
      KeySchema: [ /* required */
        {
          AttributeName: 'STRING_VALUE', /* required */
          KeyType: 'HASH | RANGE' /* required */
        },
        /* more items */
      ],
      Projection: { /* required */
        NonKeyAttributes: [
          'STRING_VALUE',
          /* more items */
        ],
        ProjectionType: 'ALL | KEYS_ONLY | INCLUDE'
      }
    },
    /* more items */
  ],
  StreamSpecification: {
    StreamEnabled: true || false,
    StreamViewType: 'NEW_IMAGE | OLD_IMAGE | NEW_AND_OLD_IMAGES | KEYS_ONLY'
  }
};

嗯。 这里感觉需要对amazon的文档做些吐槽。为啥这个文档里面的参数,比如S|B|N是什么意思,NEW_IMAGE,OLD_IMAGE 是什么意思也没有说明。只看上面的说明,感觉跟没说是一样的。

再经历了多次失败之后,终于写出了下面验证通过的param:

/* Create A Table*/
var params = {
    AttributeDefinitions: [ /* required */
        {
            AttributeName: 'ID', /* required */
            AttributeType: 'S' /* required */
        },
        {
            AttributeName: 'NAME', /* required */
            AttributeType: 'S' /* required */
        }
        /* more items */
    ],
    TableName: 'DNMDB', /* required */
    KeySchema: [ /* required */
        {
            AttributeName: 'ID', /* required */
            KeyType: 'HASH' /* required */
        },
        {
            AttributeName: "NAME",
            KeyType: "RANGE"
        }
        /* more items */
    ],
    LocalSecondaryIndexes: [
        {
            IndexName: 'Index1', /* required */
            KeySchema: [ /* required */
                {
                    AttributeName: 'ID', /* required */
                    KeyType: 'HASH' /* required */
                },
                {
                    AttributeName: 'NAME', /* required */
                    KeyType: 'RANGE' /* required */
                }
                /* more items */
            ],
            Projection: { /* required */
                NonKeyAttributes: [
                    'ID'
                    /* more items */
                ],
                ProjectionType: 'INCLUDE'
            }
        }
        /* more items */
    ],
    StreamSpecification: {
        StreamEnabled: true,
        StreamViewType: 'NEW_IMAGE'
    },
    ProvisionedThroughput: { /* required */
        ReadCapacityUnits: 1, /* required */
        WriteCapacityUnits: 1 /* required */
    },
    GlobalSecondaryIndexes: [
        {
            IndexName: 'GIND1', /* required */
            KeySchema: [ /* required */
                {
                    AttributeName: 'ID', /* required */
                    KeyType: 'HASH' /* required */
                },
                /* more items */
            ],
            Projection: { /* required */
                NonKeyAttributes: [
                    'NAME'
                    /* more items */
                ],
                ProjectionType: 'INCLUDE'
            },
            ProvisionedThroughput: { /* required */
                ReadCapacityUnits: 1, /* required */
                WriteCapacityUnits: 1 /* required */
            }
        }
        /* more items */
    ]
};

然后我们将params传递给createTable函数,因为创建表是异步操作,当开始创建表时,table的状态会是CREATEING,只有创建完毕之后,才会变成ACTIVE。
代码如下:

dyn.createTable(params, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
})

而查询表的API就显得简单了

listTables(params = {}, callback) ⇒ AWS.Request

代码原样拷贝过来:

dyn.listTables(function (err, data)
{
    console.log('listTables',err,data);
});

OK,一个非常简单使用DynamoDB Local的demo就完成了,完整代码如下:

/**
 * Created by andy on 2015/9/11.
 */
var AWS = require('aws-sdk');
var uuid = require('node-uuid');

/* Auth Config */
AWS.config.update({
    aws_access_key_id : "andy-aws-account",
    aws_secret_access_key : "andy-aws-account",
    region : "eu-west-1"
})

dyn= new AWS.DynamoDB({ endpoint: new AWS.Endpoint('http://localhost:8000') });

/* Create A Table*/
var params = {
    AttributeDefinitions: [ /* required */
        {
            AttributeName: 'ID', /* required */
            AttributeType: 'S' /* required */
        },
        {
            AttributeName: 'NAME', /* required */
            AttributeType: 'S' /* required */
        }
        /* more items */
    ],
    TableName: 'DNMDB', /* required */
    KeySchema: [ /* required */
        {
            AttributeName: 'ID', /* required */
            KeyType: 'HASH' /* required */
        },
        {
            AttributeName: "NAME",
            KeyType: "RANGE"
        }
        /* more items */
    ],
    LocalSecondaryIndexes: [
        {
            IndexName: 'Index1', /* required */
            KeySchema: [ /* required */
                {
                    AttributeName: 'ID', /* required */
                    KeyType: 'HASH' /* required */
                },
                {
                    AttributeName: 'NAME', /* required */
                    KeyType: 'RANGE' /* required */
                }
                /* more items */
            ],
            Projection: { /* required */
                NonKeyAttributes: [
                    'ID'
                    /* more items */
                ],
                ProjectionType: 'INCLUDE'
            }
        }
        /* more items */
    ],
    StreamSpecification: {
        StreamEnabled: true,
        StreamViewType: 'NEW_IMAGE'
    },
    ProvisionedThroughput: { /* required */
        ReadCapacityUnits: 1, /* required */
        WriteCapacityUnits: 1 /* required */
    },
    GlobalSecondaryIndexes: [
        {
            IndexName: 'GIND1', /* required */
            KeySchema: [ /* required */
                {
                    AttributeName: 'ID', /* required */
                    KeyType: 'HASH' /* required */
                },
                /* more items */
            ],
            Projection: { /* required */
                NonKeyAttributes: [
                    'NAME'
                    /* more items */
                ],
                ProjectionType: 'INCLUDE'
            },
            ProvisionedThroughput: { /* required */
                ReadCapacityUnits: 1, /* required */
                WriteCapacityUnits: 1 /* required */
            }
        }
        /* more items */
    ]
};
dyn.createTable(params, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
})

dyn.listTables(function (err, data)
{
    console.log('listTables',err,data);
});

第一次执行时,因为createtable是异步操作,所以查询表会报空. 而createTable会返回所创建表的信息:

listTables null { TableNames: [] }
{ TableDescription: 
   { AttributeDefinitions: [ [Object], [Object] ],
     TableName: 'DNMDB',
     KeySchema: [ [Object], [Object] ],
     TableStatus: 'ACTIVE',
     CreationDateTime: Fri Sep 11 2015 19:49:41 GMT+0800 (China Standard Time),
     ProvisionedThroughput: 
      { LastIncreaseDateTime: Thu Jan 01 1970 08:00:00 GMT+0800 (China Standard Time),
        LastDecreaseDateTime: Thu Jan 01 1970 08:00:00 GMT+0800 (China Standard Time),
        NumberOfDecreasesToday: 0,
        ReadCapacityUnits: 1,
        WriteCapacityUnits: 1 },
     TableSizeBytes: 0,
     ItemCount: 0,
     TableArn: 'arn:aws:dynamodb:ddblocal:000000000000:table/DNMDB',
     LocalSecondaryIndexes: [ [Object] ],
     GlobalSecondaryIndexes: [ [Object] ],
     StreamSpecification: { StreamEnabled: true, StreamViewType: 'NEW_IMAGE' },
     LatestStreamLabel: '2015-09-11T11:49:41.684',
     LatestStreamArn: 'arn:aws:dynamodb:ddblocal:000000000000:table/DNMDB/stream/2015-09-11T11:49:41.684' } }

第二次执行,就可以查询表名了。如下:

listTables null { TableNames: [ 'DNMDB' ] }

虽然表创建成功了,但创建表的各项参数还是没搞明白。功夫不负有心人,终于找到了相关参数说明。
可今天是周五了,还是早点下课过周末吧。 各项参数说明,留待下节课再讲。OK,下课,起立~

你可能感兴趣的:(nodejs,amazon,dynamodb,cloud)