DynamoDBLocal:如何启动和停止数据库?

时间:2016-08-10 05:53:15

标签: node.js amazon-dynamodb dynamo-local

我有一个“dynamodb_helper.js”,我使用local-dynamo在本地模拟DynamoDB。 我能够在测试之前启动服务器并成功运行它,但是stopDB()似乎不起作用。任何帮助/建议将不胜感激。因此,即使在测试结束后,服务器子进程仍然保持运行。

请在下面找到我的代码。

    var AWS = require("aws-sdk");
var localDynamo = require('local-dynamo');
var dynamoServer = null;
var dynamodb = null;
var dynamo = null;

module.exports = {
  startDB: function() {
    dynamoServer = localDynamo.launch({
     port: 4567,
     detached: true,
     heap: '512m',
     stdio: 'pipe'
    })
    var awsConfig = require('../lib/util').ymlParser('aws');
    AWS.config.update(awsConfig);
    AWS.config.update({
     accessKeyId: "TestData",
     secretAccessKey: "TestData",
     region: "localhost",
     endpoint: "http://localhost:4567"
    });
    dynamodb = new AWS.DynamoDB();
    dynamo = dynamodb.DocumentClient;
  },

  stopDB: function() {
    setTimeout(function () {
        dynamoServer.kill();
      }, 1000)
  },

  createTable: function() {
    var params = {
        TableName : "Movies",
        KeySchema: [
            { AttributeName: "year", KeyType: "HASH"},  //Partition key
            { AttributeName: "title", KeyType: "RANGE" }  //Sort key
        ],
        AttributeDefinitions: [
            { AttributeName: "year", AttributeType: "N" },
            { AttributeName: "title", AttributeType: "S" }
        ],
        ProvisionedThroughput: {
            ReadCapacityUnits: 10,
            WriteCapacityUnits: 10
        }
    };
    dynamodb.createTable(params, function(err, data) {
        if (err) {
            console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            console.log("Created table. Table description JSON:", JSON.stringify(data, null, 2));
        }
    });
  }
};

1 个答案:

答案 0 :(得分:1)

在顶部添加: -

var treeKill = require('tree-kill');

如下所述更改stopDB: -

stopDB : function() {
    console.log("Stop the dynamodb");
    console.log("Dynamodb pid number :" + dynamoServer.pid);        

    treeKill(dynamoServer.pid, 'SIGTERM', function(err) {
        if (err === null) {
            console.log("Dynamodb process has been killed");    
        } else {
            console.log("Dynamodb process hasn't been killed : " + JSON.stringify(err));
        }

    });
},

使用treeKill来杀死进程,因为“kill”方法并没有真正杀死进程。

  

注意,虽然该函数被称为kill,但传递给的信号   子进程可能实际上不会终止该进程。

Child Process Kill Reference Document