

# Node.js 和 DAX
<a name="DAX.client.run-application-nodejs-3"></a>

适用于 Node.js 的 DAX SDK v3.x 与 [AWS SDK for Node.js v3.x](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/introduction/) 兼容。适用于 Node.js 的 DAX SDK v3.x 支持使用 [aggregated](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/introduction/#high-level-concepts) 客户端。请注意，DAX 不支持创建基本客户端。有关不支持的功能的更多详细信息，请参阅[与 AWS SDK V3 不对等的功能](#DAX.client.run-application-nodejs-3-not-in-parity)。

执行这些步骤可在 Amazon EC2 实例上运行 Node.js 示例应用程序。

**运行 DAX 的 Node.js 示例**

1. 在 Amazon EC2 实例上设置 Node.js，如下所示：

   1. 安装节点版本管理器 (`nvm`)。

      ```
      curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
      ```

   1. 使用 nvm 安装 Node.js。

      ```
      nvm install 18
      ```

   1. 通过 nvm 使用 Node 18

      ```
      nvm use 18
      ```

   1. 测试 Node.js 已安装且运行正常。

      ```
      node -e "console.log('Running Node.js ' + process.version)"
      ```

      这应该显示以下消息。

      `Running Node.js v18.x.x`

1. 使用节点程序包管理器 (`npm`) 安装 DaxDocument Node.js 客户端。

   ```
   npm install @amazon-dax-sdk/lib-dax
   ```

## TryDax 示例代码
<a name="DAX.client.run-application-nodejs-3-TryDax-sample-code"></a>

要评估 DynamoDB Accelerator（DAX）的性能优势，请按照以下步骤运行一个示例测试，来比较标准 DynamoDB 和 DAX 集群之间的读取操作时间。

1. 设置工作区并将 `lib-dax` 安装为依赖项后，将 [TryDax.js](DAX.client.tutorial-TryDax.md) 复制到项目。

1. 对您的 DAX 集群运行该程序。要确定 DAX 集群的端点，请选择下列选项之一：
   +  **使用 DynamoDB 控制台** — 选择 DAX 集群。集群端点显示在控制台中，如下面的示例所示。

     ```
     dax://my-cluster.l6fzcv.dax-clusters.us-east-1.amazonaws.com
     ```
   + **使用 AWS CLI** — 输入下面的命令。

     ```
     aws dax describe-clusters --query "Clusters[*].ClusterDiscoveryEndpoint"
     ```

     集群端点显示在输出中，如下面的示例所示。

     ```
     {
         "Address": "my-cluster.l6fzcv.dax-clusters.us-east-1.amazonaws.com",
         "Port": 8111,
         "URL": "dax://my-cluster.l6fzcv.dax-clusters.us-east-1.amazonaws.com"
     }
     ```

1. 现在，通过将集群端点指定为命令行参数来运行该程序。

   ```
   node TryDax.js dax://my-cluster.l6fzcv.dax-clusters.us-east-1.amazonaws.com
   ```

   您应该可以看到类似于如下所示的输出内容：

   ```
   Attempting to create table; please wait...
   Successfully created table. Table status: ACTIVE
   Writing data to the table...
   Writing 20 items for partition key:  1
   Writing 20 items for partition key:  2
   Writing 20 items for partition key:  3
   ...
   Running GetItem Test
           Total time: 153555.10 µs - Avg time: 383.89 µs
           Total time: 44679.96 µs - Avg time: 111.70 µs
           Total time: 36885.86 µs - Avg time: 92.21 µs
           Total time: 32467.25 µs - Avg time: 81.17 µs
           Total time: 32202.60 µs - Avg time: 80.51 µs
   Running Query Test
           Total time: 14869.25 µs - Avg time: 2973.85 µs
           Total time: 3036.31 µs - Avg time: 607.26 µs
           Total time: 2468.92 µs - Avg time: 493.78 µs
           Total time: 2062.53 µs - Avg time: 412.51 µs
           Total time: 2178.22 µs - Avg time: 435.64 µs
   Running Scan Test
           Total time: 2395.88 µs - Avg time: 479.18 µs
           Total time: 2207.16 µs - Avg time: 441.43 µs
           Total time: 2443.14 µs - Avg time: 488.63 µs
           Total time: 2038.24 µs - Avg time: 407.65 µs
           Total time: 1972.17 µs - Avg time: 394.43 µs
   Running Pagination Test
   Scan Pagination
   [
     { pk: 1, sk: 1, someData: 'XXXXXXXXXX' },
     { pk: 1, sk: 2, someData: 'XXXXXXXXXX' },
     { pk: 1, sk: 3, someData: 'XXXXXXXXXX' }
   ]
   [
     { pk: 1, sk: 4, someData: 'XXXXXXXXXX' },
     { pk: 1, sk: 5, someData: 'XXXXXXXXXX' },
     { pk: 1, sk: 6, someData: 'XXXXXXXXXX' }
   ]
   ...
   Query Pagination
   [
     { pk: 1, sk: 1, someData: 'XXXXXXXXXX' },
     { pk: 1, sk: 2, someData: 'XXXXXXXXXX' },
     { pk: 1, sk: 3, someData: 'XXXXXXXXXX' }
   ]
   [
     { pk: 1, sk: 4, someData: 'XXXXXXXXXX' },
     { pk: 1, sk: 5, someData: 'XXXXXXXXXX' },
     { pk: 1, sk: 6, someData: 'XXXXXXXXXX' }
   ]
   ...
   Attempting to delete table; please wait...
   Successfully deleted table.
   ```

   记下时间信息。`GetItem`、`Query`、`Scan` 测试所需的微秒数。

1. 在这种情况下，您对 DAX 集群运行了程序。现在，您将再次运行该程序，这次是针对 DynamoDB。

1. 现在再次运行该程序，但这一次不需要将集群端点作为命令行参数。

   ```
   node TryDax.js
   ```

   查看输出，并记下计时信息。与使用 DynamoDB 相比，使用 DAX 时，`GetItem`、`Query` 和 `Scan` 所耗时间应明显更短。

## 与 AWS SDK V3 不对等的功能
<a name="DAX.client.run-application-nodejs-3-not-in-parity"></a>
+ [Bare-bones](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/introduction/#high-level-concepts) 客户端：Dax Node.js V3 不支持基本客户端。

  ```
  const dynamoDBClient = new DynamoDBClient({ region: 'us-west-2' });
  const regularParams = {
      TableName: 'TryDaxTable',
      Key: {
          pk: 1,
          sk: 1
      }
  };
  // The DynamoDB client supports the send operation.
  const dynamoResult = await dynamoDBClient.send(new GetCommand(regularParams));
  
  // However, the DaxDocument client does not support the send operation.
  const daxClient = new DaxDocument({
      endpoints: ['your-dax-endpoint'],
      region: 'us-west-2',
  });
  
  const params = {
      TableName: 'TryDaxTable',
      Key: {
          pk: 1,
          sk: 1
      }
  };
  
  // This will throw an error - send operation is not supported for DAX. Please refer to documentation.
  const result = await daxClient.send(new GetCommand(params));
  console.log(result);
  ```
+ [Middleware Stack](https://aws.amazon.com/blogs/developer/middleware-stack-modular-aws-sdk-js/)：Dax Node.js V3 不支持使用中间件函数。

  ```
  const dynamoDBClient = new DynamoDBClient({ region: 'us-west-2' });
  // The DynamoDB client supports the middlewareStack.
  dynamoDBClient.middlewareStack.add(
    (next, context) =>> async (args) => {
      console.log("Before operation:", args);
      const result = await next(args);
      console.log("After operation:", result);
      return result;
    },
    {
      step: "initialize", // or "build", "finalizeRequest", "deserialize"
      name: "loggingMiddleware",
    }
  );
  
  // However, the DaxDocument client does not support the middlewareStack.
  const daxClient = new DaxDocument({
      endpoints: ['your-dax-endpoint'],
      region: 'us-west-2',
  });
  
  // This will throw an error - custom middleware and middlewareStacks are not supported for DAX. Please refer to documentation.
  daxClient.middlewareStack.add(
    (next, context) => async (args) => {
      console.log("Before operation:", args);
      const result = await next(args);
      console.log("After operation:", result);
      return result;
    },
    {
      step: "initialize", // or "build", "finalizeRequest", "deserialize"
      name: "loggingMiddleware",
    }
  );
  ```