

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 Cassandra 客户端驱动程序以编程方式访问 Amazon Keyspaces
<a name="programmatic.drivers"></a>

您可以使用许多第三方开源 Cassandra 驱动程序连接 Amazon Keyspaces。Amazon Keyspaces 与支持 Apache Cassandra 3.11.2 版本的 Cassandra 驱动程序兼容。以下是我们测试过并推荐用于 Amazon Keyspaces 的驱动程序和最新版本：
+ `Java v3.3`
+ `Java v4.17`
+ `Python Cassandra-driver 3.29.1`
+ `Node.js cassandra driver -v 4.7.2`
+ `GO using GOCQL v1.6`
+ `.NET CassandraCSharpDriver -v 3.20.1`

有关 Cassandra 驱动程序的更多信息，请参阅 [Apache Cassandra 客户端驱动程序](http://cassandra.apache.org/doc/latest/getting_started/drivers.html)。

**注意**  
为了帮助您入门，您可以查看和下载使用常用驱动程序与 Amazon Keyspaces 建立连接的 end-to-end代码示例。请参阅[上的 Amazon Keyspaces 示例](https://github.com/aws-samples/amazon-keyspaces-examples)。 GitHub

本章中的教程包括一个简单的 CQL 查询，用于确认已成功建立与 Amazon Keyspaces 的连接。要了解连接到 Amazon Keyspaces 端点后如何使用密钥空间和表，请参阅 [Amazon Keyspaces（Apache Cassandra 兼容）的 CQL 语言参考](cql.md)。有关展示如何从 Amazon VPC 终端节点连接到 Amazon Keyspaces 的 step-by-step教程，请参阅。[教程：使用接口 VPC 终端节点连接到 Amazon Keyspaces](vpc-endpoints-tutorial.md)

**Topics**
+ [使用 Cassandra 客户端驱动程序以编程方式访问 Amazon Keyspaces](using_java_driver.md)
+ [使用 Cassandra Python 客户端驱动程序以编程方式访问 Amazon Keyspaces](using_python_driver.md)
+ [使用 Cassandra Node.js 客户端驱动程序以编程方式访问 Amazon Keyspaces](using_nodejs_driver.md)
+ [使用 Cassandra .NET Core 客户端驱动程序以编程方式访问 Amazon Keyspaces](using_dotnetcore_driver.md)
+ [使用 Cassandra Go 客户端驱动程序以编程方式访问 Amazon Keyspaces](using_go_driver.md)
+ [使用 Cassandra Perl 客户端驱动程序以编程方式访问 Amazon Keyspaces](using_perl_driver.md)

# 使用 Cassandra 客户端驱动程序以编程方式访问 Amazon Keyspaces
<a name="using_java_driver"></a>

本部分介绍了如何使用 Java 客户端驱动程序连接 Amazon Keyspaces。

**注意**  
Java 17 和 DataStax Java 驱动程序 4.17 目前仅支持测试版。有关更多信息，请参阅 [https://docs.datastax.com/en/developer/java-driver/4.17/upgrade_guide/](https://docs.datastax.com/en/developer/java-driver/4.17/upgrade_guide/)。

要为用户和应用程序提供凭证，以通过编程方式访问 Amazon Keyspaces 资源，您可以执行以下任一操作：
+ 创建与特定 AWS Identity and Access Management (IAM) 用户关联的服务特定凭证。
+ 为了增强安全性，我们建议为所有 AWS 服务中使用的 IAM 身份创建 IAM 访问密钥。借助适用于 Cassandra 客户端驱动程序的 Amazon Keyspaces SigV4 身份验证插件，您可以使用 IAM 访问密钥而不是用户名和密码来验证对 Amazon Keyspaces 的调用。有关更多信息，请参阅 [为 Amazon Keyspaces 创建和配置 AWS 证书](access.credentials.md)。

**注意**  
有关如何在 Spring Boot 中使用 Amazon Keyspaces 的示例，请参阅。[https://github.com/aws-samples/amazon-keyspaces-examples/tree/main/java/datastax-v4/spring](https://github.com/aws-samples/amazon-keyspaces-examples/tree/main/java/datastax-v4/spring)

**Topics**
+ [开始前的准备工作](#using_java_driver.BeforeYouBegin)
+ [Step-by-step 使用适用于 Apache Cassandra 的 DataStax Java 驱动程序使用特定于服务的凭证连接亚马逊密钥空间的教程](#java_tutorial)
+ [Step-by-step 使用适用于 Apache Cassandra 的 4.x DataStax Java 驱动程序和 Sigv4 身份验证插件连接亚马逊密钥空间的教程](#java_tutorial.SigV4)
+ [使用适用于 Apache Cassandra 的 3.x DataStax Java 驱动程序和 SigV4 身份验证插件连接亚马逊密钥空间](#java3x_tutorial.SigV4)

## 开始前的准备工作
<a name="using_java_driver.BeforeYouBegin"></a>

要连接到 Amazon Keyspaces，您需要先完成以下任务。

1. Amazon Keyspaces 要求使用传输层安全性协议 (TLS) 来帮助保护与客户端的连接。

   1.  下载以下数字证书并将文件保存在本地或您的主目录中。

      1. AmazonRootCA1

      1. AmazonRootCA2

      1. AmazonRootCA3

      1. AmazonRootCA4

      1. Starfield Class 2 Root（可选 — 为了向后兼容）

      要下载证书，您可以使用以下命令。

      ```
      curl -O https://www.amazontrust.com/repository/AmazonRootCA1.pem
      curl -O https://www.amazontrust.com/repository/AmazonRootCA2.pem
      curl -O https://www.amazontrust.com/repository/AmazonRootCA3.pem
      curl -O https://www.amazontrust.com/repository/AmazonRootCA4.pem
      curl -O https://certs.secureserver.net/repository/sf-class2-root.crt
      ```
**注意**  
Amazon Keyspaces 之前使用锚定在 Starfield Class 2 CA 上的 TLS 证书。 AWS 正在将所有证书全部迁移 AWS 区域 到根据亚马逊信任服务（Amazon Root CAs 1—4）颁发的证书。在此过渡期间，将客户端配置为同时信任 Amazon Root CAs 1—4 和 Starfield 根，以确保所有区域之间的兼容性。

   1. 将数字证书转换为 TrustStore 文件并将其添加到密钥库中。

      ```
      openssl x509 -outform der -in AmazonRootCA1.pem -out temp_file.der
      keytool -import -alias amazon-root-ca-1 -keystore cassandra_truststore.jks -file temp_file.der
      
      openssl x509 -outform der -in AmazonRootCA2.pem -out temp_file.der
      keytool -import -alias amazon-root-ca-2 -keystore cassandra_truststore.jks -file temp_file.der
      
      openssl x509 -outform der -in AmazonRootCA3.pem -out temp_file.der
      keytool -import -alias amazon-root-ca-3 -keystore cassandra_truststore.jks -file temp_file.der
      
      openssl x509 -outform der -in AmazonRootCA4.pem -out temp_file.der
      keytool -import -alias amazon-root-ca-4 -keystore cassandra_truststore.jks -file temp_file.der
                   
      openssl x509 -outform der -in sf-class2-root.crt -out temp_file.der
      keytool -import -alias cassandra -keystore cassandra_truststore.jks -file temp_file.der
      ```

      在最后一步中，您需要为密钥库创建密码并信任每个证书。交互式命令如下所示。

      ```
      Enter keystore password:  
      Re-enter new password: 
      Owner: CN=Amazon Root CA 1, O=Amazon, C=US
      Issuer: CN=Amazon Root CA 1, O=Amazon, C=US
      Serial number: 66c9fcf99bf8c0a39e2f0788a43e696365bca
      Valid from: Tue May 26 00:00:00 UTC 2015 until: Sun Jan 17 00:00:00 UTC 2038
      Certificate fingerprints:
           SHA1: 8D:A7:F9:65:EC:5E:FC:37:91:0F:1C:6E:59:FD:C1:CC:6A:6E:DE:16
           SHA256: 8E:CD:E6:88:4F:3D:87:B1:12:5B:A3:1A:C3:FC:B1:3D:70:16:DE:7F:57:CC:90:4F:E1:CB:97:C6:AE:98:19:6E
      Signature algorithm name: SHA256withRSA
      Subject Public Key Algorithm: 2048-bit RSA key
      Version: 3
      
      Extensions: 
      
      #1: ObjectId: 2.5.29.19 Criticality=true
      BasicConstraints:[
        CA:true
        PathLen:2147483647
      ]
      
      #2: ObjectId: 2.5.29.15 Criticality=true
      KeyUsage [
        DigitalSignature
        Key_CertSign
        Crl_Sign
      ]
      
      #3: ObjectId: 2.5.29.14 Criticality=false
      SubjectKeyIdentifier [
      KeyIdentifier [
      0000: 84 18 CC 85 34 EC BC 0C   94 94 2E 08 59 9C C7 B2  ....4.......Y...
      0010: 10 4E 0A 08                                        .N..
      ]
      ]
      
      Trust this certificate? [no]:  yes
      Certificate was added to keystore
      Enter keystore password:  
      Owner: CN=Amazon Root CA 2, O=Amazon, C=US
      Issuer: CN=Amazon Root CA 2, O=Amazon, C=US
      Serial number: 66c9fd29635869f0a0fe58678f85b26bb8a37
      Valid from: Tue May 26 00:00:00 UTC 2015 until: Sat May 26 00:00:00 UTC 2040
      Certificate fingerprints:
           SHA1: 5A:8C:EF:45:D7:A6:98:59:76:7A:8C:8B:44:96:B5:78:CF:47:4B:1A
           SHA256: 1B:A5:B2:AA:8C:65:40:1A:82:96:01:18:F8:0B:EC:4F:62:30:4D:83:CE:C4:71:3A:19:C3:9C:01:1E:A4:6D:B4
      Signature algorithm name: SHA384withRSA
      Subject Public Key Algorithm: 4096-bit RSA key
      Version: 3
      
      Extensions: 
      
      #1: ObjectId: 2.5.29.19 Criticality=true
      BasicConstraints:[
        CA:true
        PathLen:2147483647
      ]
      
      #2: ObjectId: 2.5.29.15 Criticality=true
      KeyUsage [
        DigitalSignature
        Key_CertSign
        Crl_Sign
      ]
      
      #3: ObjectId: 2.5.29.14 Criticality=false
      SubjectKeyIdentifier [
      KeyIdentifier [
      0000: B0 0C F0 4C 30 F4 05 58   02 48 FD 33 E5 52 AF 4B  ...L0..X.H.3.R.K
      0010: 84 E3 66 52                                        ..fR
      ]
      ]
      
      Trust this certificate? [no]:  yes
      Certificate was added to keystore
      Enter keystore password:  
      Owner: CN=Amazon Root CA 3, O=Amazon, C=US
      Issuer: CN=Amazon Root CA 3, O=Amazon, C=US
      Serial number: 66c9fd5749736663f3b0b9ad9e89e7603f24a
      Valid from: Tue May 26 00:00:00 UTC 2015 until: Sat May 26 00:00:00 UTC 2040
      Certificate fingerprints:
           SHA1: 0D:44:DD:8C:3C:8C:1A:1A:58:75:64:81:E9:0F:2E:2A:FF:B3:D2:6E
           SHA256: 18:CE:6C:FE:7B:F1:4E:60:B2:E3:47:B8:DF:E8:68:CB:31:D0:2E:BB:3A:DA:27:15:69:F5:03:43:B4:6D:B3:A4
      Signature algorithm name: SHA256withECDSA
      Subject Public Key Algorithm: 256-bit EC (secp256r1) key
      Version: 3
      
      Extensions: 
      
      #1: ObjectId: 2.5.29.19 Criticality=true
      BasicConstraints:[
        CA:true
        PathLen:2147483647
      ]
      
      #2: ObjectId: 2.5.29.15 Criticality=true
      KeyUsage [
        DigitalSignature
        Key_CertSign
        Crl_Sign
      ]
      
      #3: ObjectId: 2.5.29.14 Criticality=false
      SubjectKeyIdentifier [
      KeyIdentifier [
      0000: AB B6 DB D7 06 9E 37 AC   30 86 07 91 70 C7 9C C4  ......7.0...p...
      0010: 19 B1 78 C0                                        ..x.
      ]
      ]
      
      Trust this certificate? [no]:  yes
      Certificate was added to keystore
      Enter keystore password:  
      Owner: CN=Amazon Root CA 4, O=Amazon, C=US
      Issuer: CN=Amazon Root CA 4, O=Amazon, C=US
      Serial number: 66c9fd7c1bb104c2943e5717b7b2cc81ac10e
      Valid from: Tue May 26 00:00:00 UTC 2015 until: Sat May 26 00:00:00 UTC 2040
      Certificate fingerprints:
           SHA1: F6:10:84:07:D6:F8:BB:67:98:0C:C2:E2:44:C2:EB:AE:1C:EF:63:BE
           SHA256: E3:5D:28:41:9E:D0:20:25:CF:A6:90:38:CD:62:39:62:45:8D:A5:C6:95:FB:DE:A3:C2:2B:0B:FB:25:89:70:92
      Signature algorithm name: SHA384withECDSA
      Subject Public Key Algorithm: 384-bit EC (secp384r1) key
      Version: 3
      
      Extensions: 
      
      #1: ObjectId: 2.5.29.19 Criticality=true
      BasicConstraints:[
        CA:true
        PathLen:2147483647
      ]
      
      #2: ObjectId: 2.5.29.15 Criticality=true
      KeyUsage [
        DigitalSignature
        Key_CertSign
        Crl_Sign
      ]
      
      #3: ObjectId: 2.5.29.14 Criticality=false
      SubjectKeyIdentifier [
      KeyIdentifier [
      0000: D3 EC C7 3A 65 6E CC E1   DA 76 9A 56 FB 9C F3 86  ...:en...v.V....
      0010: 6D 57 E5 81                                        mW..
      ]
      ]
      
      Trust this certificate? [no]:  yes
      Certificate was added to keystore
      Enter keystore password:  
      Owner: OU=Starfield Class 2 Certification Authority, O="Starfield Technologies, Inc.", C=US
      Issuer: OU=Starfield Class 2 Certification Authority, O="Starfield Technologies, Inc.", C=US
      Serial number: 0
      Valid from: Tue Jun 29 17:39:16 UTC 2004 until: Thu Jun 29 17:39:16 UTC 2034
      Certificate fingerprints:
           SHA1: AD:7E:1C:28:B0:64:EF:8F:60:03:40:20:14:C3:D0:E3:37:0E:B5:8A
           SHA256: 14:65:FA:20:53:97:B8:76:FA:A6:F0:A9:95:8E:55:90:E4:0F:CC:7F:AA:4F:B7:C2:C8:67:75:21:FB:5F:B6:58
      Signature algorithm name: SHA1withRSA (weak)
      Subject Public Key Algorithm: 2048-bit RSA key
      Version: 3
      
      Extensions: 
      
      #1: ObjectId: 2.5.29.35 Criticality=false
      AuthorityKeyIdentifier [
      KeyIdentifier [
      0000: BF 5F B7 D1 CE DD 1F 86   F4 5B 55 AC DC D7 10 C2  ._.......[U.....
      0010: 0E A9 88 E7                                        ....
      ]
      [OU=Starfield Class 2 Certification Authority, O="Starfield Technologies, Inc.", C=US]
      SerialNumber: [    00]
      ]
      
      #2: ObjectId: 2.5.29.19 Criticality=false
      BasicConstraints:[
        CA:true
        PathLen:2147483647
      ]
      
      #3: ObjectId: 2.5.29.14 Criticality=false
      SubjectKeyIdentifier [
      KeyIdentifier [
      0000: BF 5F B7 D1 CE DD 1F 86   F4 5B 55 AC DC D7 10 C2  ._.......[U.....
      0010: 0E A9 88 E7                                        ....
      ]
      ]
      
      
      Warning:
      The input uses the SHA1withRSA signature algorithm which is considered a security risk. This algorithm will be disabled in a future update.
      
      Trust this certificate? [no]:  yes
      Certificate was added to keystore
      ```

1.  将 trustStore 文件附加到 JVM 参数中：

   ```
   -Djavax.net.ssl.trustStore=path_to_file/cassandra_truststore.jks 
   -Djavax.net.ssl.trustStorePassword=my_password
   ```

## Step-by-step 使用适用于 Apache Cassandra 的 DataStax Java 驱动程序使用特定于服务的凭证连接亚马逊密钥空间的教程
<a name="java_tutorial"></a>

以下 step-by-step教程将引导您使用特定于服务的凭证使用适用于 Cassandra 的 Java 驱动程序连接到 Amazon Keyspaces。具体而言，你将使用适用于 Apache Cassandr DataStax a 的 Java 驱动程序的 4.0 版本。

**Topics**
+ [步骤 1：先决条件](#java_tutorial.prereq)
+ [步骤 2：配置驱动程序](#java_tutorial.driverconfiguration)
+ [步骤 3：运行示例应用程序](#java_tutorial.application)

### 步骤 1：先决条件
<a name="java_tutorial.prereq"></a>

要学习本教程，你需要生成特定于服务的凭证，并将适用于 Apache Cassandra 的 DataStax Java 驱动程序添加到你的 Java 项目中。
+ 完成[创建用于通过编程方式访问 Amazon Keyspaces 的服务特定凭证。](programmatic.credentials.ssc.md)中的步骤，为您的 Amazon Keyspaces IAM 用户生成服务特定凭证。如果您更喜欢使用 IAM 访问密钥进行身份验证，请参阅[Step-by-step 使用适用于 Apache Cassandra 的 4.x DataStax Java 驱动程序和 Sigv4 身份验证插件连接亚马逊密钥空间的教程](#java_tutorial.SigV4)。
+ 将 Apache Cassandra 的 DataStax Java 驱动程序添加到你的 Java 项目中。确保您使用的驱动程序版本支持 Apache Cassandra 3.11.2。有关更多信息，请参阅 A [pache Cassandra 的 DataStax Java 驱动程序](https://github.com/datastax/java-driver)文档。

### 步骤 2：配置驱动程序
<a name="java_tutorial.driverconfiguration"></a>

您可以通过为应用程序创建配置文件来指定 DataStax Java Cassandra 驱动程序的设置。此配置文件会覆盖默认设置，并告诉驱动程序使用端口 9142 连接到 Amazon Keyspaces 服务端点。有关可用服务端点的列表，请参阅 [Amazon Keyspaces 的服务端点](programmatic.endpoints.md)。

创建配置文件，并将该文件保存在应用程序的资源文件夹中，例如 `src/main/resources/application.conf`。打开 `application.conf`，然后添加以下配置设置。

1. **身份验证提供商**-使用`PlainTextAuthProvider`类创建身份验证提供程序。 *ServiceUserName*并*ServicePassword*应与您按照中的步骤生成服务专用凭证时获得的用户名和密码相匹配。[创建用于通过编程方式访问 Amazon Keyspaces 的服务特定凭证。](programmatic.credentials.ssc.md)
**注意**  
您可以使用适用于 Apache Cassandra 的 DataStax Java 驱动程序的身份验证插件，而不是在驱动程序配置文件中对凭据进行硬编码，从而使用短期证书。要了解更多信息，请按照[Step-by-step 使用适用于 Apache Cassandra 的 4.x DataStax Java 驱动程序和 Sigv4 身份验证插件连接亚马逊密钥空间的教程](#java_tutorial.SigV4)中的说明进行操作。

1. **本地数据中心**：将 `local-datacenter` 的值设置为要连接的区域。例如，如果应用程序要连接到 `cassandra.us-east-2.amazonaws.com`，则将本地数据中心设置为 `us-east-2`。有关所有可用的 AWS 区域，请参阅 [Amazon Keyspaces 的服务端点](programmatic.endpoints.md)。设置 slow-replica-avoidance = false 以针对更少的节点进行负载均衡。

1. **SSL/TLS** — 通过在配置文件中添加一个部分来初始化 SSLEngine工厂，其中有一行用于指定类。`class = DefaultSslEngineFactory`提供 trustStore 文件的路径和您之前创建的密码。Amazon Keyspaces 不支持对等设备的 `hostname-validation`，因此请将此选项设为 false。

```
datastax-java-driver {

    basic.contact-points = [ "cassandra.us-east-2.amazonaws.com:9142"]
    advanced.auth-provider{
        class = PlainTextAuthProvider
        username = "ServiceUserName"
        password = "ServicePassword"
    }
    basic.load-balancing-policy {
        local-datacenter = "us-east-2"
        slow-replica-avoidance = false           
    }

    advanced.ssl-engine-factory {
        class = DefaultSslEngineFactory
        truststore-path = "./src/main/resources/cassandra_truststore.jks"
        truststore-password = "my_password"
        hostname-validation = false
      }
}
```

**注意**  
除了在配置文件中添加 trustStore 的路径外，您还可以直接在应用程序代码中添加 trustStore 的路径，或者在 JVM 参数中添加 trustStore 的路径。

### 步骤 3：运行示例应用程序
<a name="java_tutorial.application"></a>

本代码示例展示了一个简单的命令行应用程序，它使用我们之前创建的配置文件创建了一个连接到 Amazon Keyspaces 的连接池。它通过运行一个简单的查询来确认连接已建立。

```
package <your package>;
// add the following imports to your project
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;

public class App 
{
    
    public static void main( String[] args )
    {
        //Use DriverConfigLoader to load your configuration file
        DriverConfigLoader loader = DriverConfigLoader.fromClasspath("application.conf");
        try (CqlSession session = CqlSession.builder()
                .withConfigLoader(loader)
                .build()) {

            ResultSet rs = session.execute("select * from system_schema.keyspaces");
            Row row = rs.one();
            System.out.println(row.getString("keyspace_name"));
        }
    }
}
```

**注意**  
使用 `try` 代码块建立连接，以确保连接始终处于关闭状态。如果不使用 `try` 代码块，请记得关闭连接，以免泄漏资源。

## Step-by-step 使用适用于 Apache Cassandra 的 4.x DataStax Java 驱动程序和 Sigv4 身份验证插件连接亚马逊密钥空间的教程
<a name="java_tutorial.SigV4"></a>

以下部分介绍如何使用适用于 Apache Cassandra 的开源 4.x DataStax Java 驱动程序的 SigV4 身份验证插件访问亚马逊密钥空间（适用于 Apache Cassandra）。该插件可从[GitHub存储库](https://github.com/aws/aws-sigv4-auth-cassandra-java-driver-plugin)中获得。

使用 SigV4 身份验证插件，您可以在连接 Amazon Keyspaces 时为用户或角色使用 IAM 凭据。该插件不需要用户名和密码，而是使用访问密钥签署 API 请求。有关更多信息，请参阅 [为 Amazon Keyspaces 创建和配置 AWS 证书](access.credentials.md)。

### 步骤 1：先决条件
<a name="java_tutorial.SigV4.1"></a>

要学习本教程，您需要完成以下任务。
+ 请按照[为 Amazon Keyspaces 创建和配置 AWS 证书](access.credentials.md)中的步骤为 IAM 用户或角色创建凭证（如果您尚未创建）。本教程假设访问密钥将存储为环境变量。有关更多信息，请参阅 [存储用于通过编程方式进行访问的访问密钥](aws.credentials.manage.md)。
+ 将 Apache Cassandra 的 DataStax Java 驱动程序添加到你的 Java 项目中。确保您使用的驱动程序版本支持 Apache Cassandra 3.11.2。有关更多信息，请参阅 A [pache Cassandra 的 DataStax Java 驱动程序](https://github.com/datastax/java-driver)文档。
+ 将身份验证插件添加到您的应用程序。该身份验证插件支持 Apache Cassandr DataStax a 的 Java 驱动程序版本 4.x。如果您使用的是 Apache Maven 或可以使用 Maven 依赖关系的构建系统，请将以下依赖关系添加到您的 `pom.xml` 文件中。
**重要**  
将插件版本替换为[GitHub 存储库](https://github.com/aws/aws-sigv4-auth-cassandra-java-driver-plugin#add-the-authentication-plugin-to-the-application)中显示的最新版本。

  ```
  <dependency>
          <groupId>software.aws.mcs</groupId>
          <artifactId>aws-sigv4-auth-cassandra-java-driver-plugin</artifactId>
          <version>4.0.9</version>
  </dependency>
  ```

### 步骤 2：配置驱动程序
<a name="java_tutorial.SigV4.2"></a>

您可以通过为应用程序创建配置文件来指定 DataStax Java Cassandra 驱动程序的设置。此配置文件会覆盖默认设置，并告诉驱动程序使用端口 9142 连接到 Amazon Keyspaces 服务端点。有关可用服务端点的列表，请参阅 [Amazon Keyspaces 的服务端点](programmatic.endpoints.md)。

创建配置文件，并将该文件保存在应用程序的资源文件夹中，例如 `src/main/resources/application.conf`。打开 `application.conf`，然后添加以下配置设置。

1. **身份验证提供程序**：将 `advanced.auth-provider.class`设置为 `software.aws.mcs.auth.SigV4AuthProvider` 的新实例。Sigv4 AuthProvider 是插件提供的用于执行 Sigv4 身份验证的身份验证处理程序。

1. **本地数据中心**：将 `local-datacenter` 的值设置为要连接的区域。例如，如果应用程序要连接到 `cassandra.us-east-2.amazonaws.com`，则将本地数据中心设置为 `us-east-2`。有关所有可用信息 AWS 区域，请参阅[Amazon Keyspaces 的服务端点](programmatic.endpoints.md)。设置 `slow-replica-avoidance = false` 以针对所有可用节点进行负载均衡。

1. **Idempotence** — 将应用程序的默认值设置为，将驱动程序配置`idempotence``true`为始终重试失败的请求。read/write/prepare/execute这是适用于分布式应用程序的最佳实践，可通过重试失败的请求来协助处理暂时性故障。

1. **SSL/TLS** — 通过在配置文件中添加一个部分来初始化 SSLEngine工厂，其中有一行用于指定类。`class = DefaultSslEngineFactory`提供 trustStore 文件的路径和您之前创建的密码。Amazon Keyspaces 不支持对等设备的 `hostname-validation`，因此请将此选项设为 false。

1. **连接** - 通过设置 `local.size = 3` 为每个端点创建至少 3 个本地连接。这是一种最佳实践，方便您的应用程序应对开销和流量暴增。有关如何根据预期流量模式计算应用程序每个端点需要多少本地连接的更多信息，请参阅[如何在 Amazon Keyspaces 中配置连接](connections.md#connections.howtoconfigure)。

1. **重试策略** - 实施 Amazon Keyspaces 重试策略 `AmazonKeyspacesExponentialRetryPolicy`，而非 Cassandra 驱动程序附带的 `DefaultRetryPolicy`。这样您就可以根据自己的需求配置 `AmazonKeyspacesExponentialRetryPolicy` 的重试次数。默认情况下，`AmazonKeyspacesExponentialRetryPolicy` 的重试次数设置为 3。有关更多信息，请参阅 [如何在 Amazon Keyspaces 中配置连接的重试策略](connections.md#connections.retry-policies)。

1. **准备的语句** - 将 `prepare-on-all-nodes` 设置为 false 以优化网络使用情况。

```
datastax-java-driver {
    basic {
        contact-points = [ "cassandra.us-east-2.amazonaws.com:9142"]  
        request {
            timeout = 2 seconds
            consistency = LOCAL_QUORUM
            page-size = 1024
            default-idempotence = true
        }
        load-balancing-policy {
            local-datacenter = "us-east-2"
            class = DefaultLoadBalancingPolicy
            slow-replica-avoidance = false           
        }
    }
    advanced {
        auth-provider {
            class = software.aws.mcs.auth.SigV4AuthProvider
            aws-region = us-east-2
        }
        ssl-engine-factory {
            class = DefaultSslEngineFactory
            truststore-path = "./src/main/resources/cassandra_truststore.jks"
            truststore-password = "my_password"
            hostname-validation = false
        }
        connection {
	     connect-timeout = 5 seconds
	     max-requests-per-connection = 512
	     pool {
                local.size = 3
	     }
        }
       retry-policy {
           class =  com.aws.ssa.keyspaces.retry.AmazonKeyspacesExponentialRetryPolicy
	    max-attempts = 3
	    min-wait = 10 mills
	    max-wait = 100 mills
       }
       prepared-statements {
	    prepare-on-all-nodes = false
       }
    }
}
```

**注意**  
除了在配置文件中添加 trustStore 的路径外，您还可以直接在应用程序代码中添加 trustStore 的路径，或者在 JVM 参数中添加 trustStore 的路径。

### 步骤 3：运行应用程序
<a name="java_tutorial.SigV4.3"></a>

本代码示例展示了一个简单的命令行应用程序，它使用我们之前创建的配置文件创建了一个连接到 Amazon Keyspaces 的连接池。它通过运行一个简单的查询来确认连接已建立。

```
package <your package>;
// add the following imports to your project
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;

public class App 
{
    
    public static void main( String[] args )
    {
        //Use DriverConfigLoader to load your configuration file
        DriverConfigLoader loader = DriverConfigLoader.fromClasspath("application.conf");
        try (CqlSession session = CqlSession.builder()
                .withConfigLoader(loader)
                .build()) {

            ResultSet rs = session.execute("select * from system_schema.keyspaces");
            Row row = rs.one();
            System.out.println(row.getString("keyspace_name"));
        }
    }
}
```

**注意**  
使用 `try` 代码块建立连接，以确保连接始终处于关闭状态。如果不使用 `try` 代码块，请记得关闭连接，以免泄漏资源。

## 使用适用于 Apache Cassandra 的 3.x DataStax Java 驱动程序和 SigV4 身份验证插件连接亚马逊密钥空间
<a name="java3x_tutorial.SigV4"></a>

以下部分介绍如何使用适用于 Apache Cassandra 的 3.x 开源 DataStax Java 驱动程序的 Sigv4 身份验证插件来访问亚马逊密钥空间。该插件可从[GitHub 存储库](https://github.com/aws/aws-sigv4-auth-cassandra-java-driver-plugin/tree/3.x-Driver-Compatible)中获得。

使用 SigV4 身份验证插件，您可以在连接 Amazon Keyspaces 时为用户和角色使用 IAM 凭据。该插件不需要用户名和密码，而是使用访问密钥签署 API 请求。有关更多信息，请参阅 [为 Amazon Keyspaces 创建和配置 AWS 证书](access.credentials.md)。

### 步骤 1：先决条件
<a name="java3x_tutorial.SigV4.1"></a>

要运行此代码示例，您首先需要完成以下任务。
+ 按照[为 Amazon Keyspaces 创建和配置 AWS 证书](access.credentials.md)中的步骤为 IAM 用户或角色创建凭证。本教程假设访问密钥将存储为环境变量。有关更多信息，请参阅 [存储用于通过编程方式进行访问的访问密钥](aws.credentials.manage.md)。
+ 按照中的步骤下载数字证书，将其转换为 TrustStore 文件，然后将 JVM 参数中的密钥库附加到您的应用程序。[开始前的准备工作](#using_java_driver.BeforeYouBegin)
+ 将 Apache Cassandra 的 DataStax Java 驱动程序添加到你的 Java 项目中。确保您使用的驱动程序版本支持 Apache Cassandra 3.11.2。有关更多信息，请参阅 A [pache Cassandra 的 DataStax Java 驱动程序](https://github.com/datastax/java-driver)文档。
+ 将身份验证插件添加到您的应用程序。该身份验证插件支持 Apache Cassandr DataStax a 的 Java 驱动程序版本 3.x。如果您使用的是 Apache Maven 或可以使用 Maven 依赖关系的构建系统，请将以下依赖关系添加到您的 `pom.xml` 文件中。将插件版本替换为[GitHub 存储库](https://github.com/aws/aws-sigv4-auth-cassandra-java-driver-plugin/tree/3.x-Driver-Compatible)中显示的最新版本。

  ```
  <dependency>
          <groupId>software.aws.mcs</groupId>
          <artifactId>aws-sigv4-auth-cassandra-java-driver-plugin_3</artifactId>
          <version>3.0.3</version>
  </dependency>
  ```

### 步骤 2：运行应用程序
<a name="java3x_tutorial.SigV4.3"></a>

本代码示例展示了一个简单的命令行应用程序，它创建了一个连接到 Amazon Keyspaces 的连接池。它通过运行一个简单的查询来确认连接已建立。

```
package <your package>;
// add the following imports to your project

import software.aws.mcs.auth.SigV4AuthProvider;  
import com.datastax.driver.core.Cluster;  
import com.datastax.driver.core.ResultSet;  
import com.datastax.driver.core.Row;  
import com.datastax.driver.core.Session;

public class App 
{
    
    public static void main( String[] args )
    {
        String endPoint = "cassandra.us-east-2.amazonaws.com";  
        int portNumber = 9142;
        Session session = Cluster.builder()  
	                                 .addContactPoint(endPoint)  
	                                 .withPort(portNumber)  
	                                 .withAuthProvider(new SigV4AuthProvider("us-east-2"))  
	                                 .withSSL()  
	                                 .build()  
	                                 .connect();

        ResultSet rs = session.execute("select * from system_schema.keyspaces");  
        Row row = rs.one();  
        System.out.println(row.getString("keyspace_name"));
    }
}
```

使用说明：

有关可用端点的列表，请参阅[Amazon Keyspaces 的服务端点](programmatic.endpoints.md)。

请参阅以下存储库，获取实用的 Java 驱动程序策略、示例，以及结合使用 Java 驱动程序和 Amazon Keyspaces 的最佳实践，：[https://github.com/aws-samples/amazon-keyspaces-java-driver-helpers](https://github.com/aws-samples/amazon-keyspaces-java-driver-helpers)。

# 使用 Cassandra Python 客户端驱动程序以编程方式访问 Amazon Keyspaces
<a name="using_python_driver"></a>

 在本部分中，我们介绍了如何使用 Python 客户端驱动程序连接 Amazon Keyspaces。要为用户和应用程序提供凭证，以通过编程方式访问 Amazon Keyspaces 资源，您可以执行以下任一操作：
+ 创建与特定 AWS Identity and Access Management (IAM) 用户关联的服务特定凭证。
+ 为了增强安全性，我们建议为所有 AWS 服务中使用的 IAM 用户或角色创建 IAM 访问密钥。借助适用于 Cassandra 客户端驱动程序的 Amazon Keyspaces SigV4 身份验证插件，您可以使用 IAM 访问密钥而不是用户名和密码来验证对 Amazon Keyspaces 的调用。有关更多信息，请参阅 [为 Amazon Keyspaces 创建和配置 AWS 证书](access.credentials.md)。

**Topics**
+ [开始前的准备工作](#using_python_driver.BeforeYouBegin)
+ [使用适用于 Apache Cassandra 的 Python 驱动程序和服务特定凭证连接 Amazon Keyspaces](#python_ssc)
+ [使用适用于 Apache Cassandra 的 Pyt DataStax hon 驱动程序和 SigV4 身份验证插件连接到亚马逊密钥空间](#python_SigV4)

## 开始前的准备工作
<a name="using_python_driver.BeforeYouBegin"></a>

在开始之前，您需要完成以下任务。

Amazon Keyspaces 要求使用传输层安全性协议 (TLS) 来帮助保护与客户端的连接。要使用 TLS 连接到亚马逊密钥空间，您需要下载亚马逊数字证书并将 Python 驱动程序配置为使用 TLS。

 下载以下数字证书并将文件保存在本地或您的主目录中。

1. AmazonRootCA1

1. AmazonRootCA2

1. AmazonRootCA3

1. AmazonRootCA4

1. Starfield Class 2 Root（可选 — 为了向后兼容）

要下载证书，您可以使用以下命令。

```
curl -O https://www.amazontrust.com/repository/AmazonRootCA1.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA2.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA3.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA4.pem
curl -O https://certs.secureserver.net/repository/sf-class2-root.crt
```

**注意**  
Amazon Keyspaces 之前使用锚定在 Starfield Class 2 CA 上的 TLS 证书。 AWS 正在将所有证书全部迁移 AWS 区域 到根据亚马逊信任服务（Amazon Root CAs 1—4）颁发的证书。在此过渡期间，将客户端配置为同时信任 Amazon Root CAs 1—4 和 Starfield 根，以确保所有区域之间的兼容性。

将所有下载的证书合并到一个`pem`文件中，其名称与我们的示例*keyspaces-bundle.pem*中的名称相同。您可以使用以下 命令进行这项操作：记下文件的路径，稍后需要这个。

```
cat AmazonRootCA1.pem \
 AmazonRootCA2.pem \
 AmazonRootCA3.pem \
 AmazonRootCA4.pem \
 sf-class2-root.crt \
 > keyspaces-bundle.pem
```

## 使用适用于 Apache Cassandra 的 Python 驱动程序和服务特定凭证连接 Amazon Keyspaces
<a name="python_ssc"></a>

以下代码示例向您展示了如何使用 Python 客户端驱动程序和服务特定凭证连接 Amazon Keyspaces。

```
from cassandra.cluster import Cluster
from ssl import SSLContext, PROTOCOL_TLSv1_2 , CERT_REQUIRED
from cassandra.auth import PlainTextAuthProvider

ssl_context = SSLContext(PROTOCOL_TLSv1_2 )

ssl_context.load_verify_locations('path_to_file/keyspaces-bundle.pem')

ssl_context.verify_mode = CERT_REQUIRED
auth_provider = PlainTextAuthProvider(username='ServiceUserName', password='ServicePassword')
cluster = Cluster(['cassandra.us-east-2.amazonaws.com'], ssl_context=ssl_context, auth_provider=auth_provider, port=9142)
session = cluster.connect()
r = session.execute('select * from system_schema.keyspaces')
print(r.current_rows)
```

使用说明：

1. `"path_to_file/keyspaces-bundle.pem"`替换为第一步中保存的合并证书文件的路径。

1. 按照以下步骤操作，确保和与您在生成服务特定凭证时获得的用户名和密码*ServicePassword*相匹配。*ServiceUserName* [创建用于通过编程方式访问 Amazon Keyspaces 的服务特定凭证。](programmatic.credentials.ssc.md)

1. 有关可用端点的列表，请参阅[Amazon Keyspaces 的服务端点](programmatic.endpoints.md)。

## 使用适用于 Apache Cassandra 的 Pyt DataStax hon 驱动程序和 SigV4 身份验证插件连接到亚马逊密钥空间
<a name="python_SigV4"></a>

以下部分介绍如何使用适用于 Apache Cassandra 的开源 Pyth DataStax on 驱动程序的 Sigv4 身份验证插件来访问亚马逊密钥空间（适用于 Apache Cassandra）。

请先按照[为 Amazon Keyspaces 创建和配置 AWS 证书](access.credentials.md)中的步骤为 IAM 角色创建凭证（如果您尚未创建）。本教程使用临时凭证，需要一个 IAM 角色。有关临时凭证的更多信息，请参阅[使用 IAM 角色和 SigV4 插件创建用于连接 Amazon Keyspaces 的临时凭证](temporary.credentials.IAM.md)。

[然后，将 Python Sigv4 身份验证插件从存储库添加到您的环境中。GitHub ](https://github.com/aws/aws-sigv4-auth-cassandra-python-driver-plugin)

```
pip install cassandra-sigv4
```

以下代码示例展示了如何使用适用于 Cassandra 的开源 Python 驱动程序和 SigV4 身份验证插件连接到 Amaz DataStax on Keyspaces。该插件依赖于适用于 Python 的 AWS SDK (Boto3)。它使用 `boto3.session` 获取临时凭证。

```
from cassandra.cluster import Cluster
from ssl import SSLContext, PROTOCOL_TLSv1_2 , CERT_REQUIRED
from cassandra.auth import PlainTextAuthProvider
import boto3
from cassandra_sigv4.auth import SigV4AuthProvider

ssl_context = SSLContext(PROTOCOL_TLSv1_2)
ssl_context.load_verify_locations('path_to_file/keyspaces-bundle.pem')
ssl_context.verify_mode = CERT_REQUIRED

# use this if you want to use Boto to set the session parameters.
boto_session = boto3.Session(aws_access_key_id="AKIAIOSFODNN7EXAMPLE",
                             aws_secret_access_key="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
                             aws_session_token="AQoDYXdzEJr...<remainder of token>",
                             region_name="us-east-2")
auth_provider = SigV4AuthProvider(boto_session)

# Use this instead of the above line if you want to use the Default Credentials and not bother with a session.
# auth_provider = SigV4AuthProvider()

cluster = Cluster(['cassandra.us-east-2.amazonaws.com'], ssl_context=ssl_context, auth_provider=auth_provider,
                  port=9142)
session = cluster.connect()
r = session.execute('select * from system_schema.keyspaces')
print(r.current_rows)
```

使用说明：

1. 将 `"path_to_file/keyspaces-bundle.pem"` 替换为第一步中保存的证书的路径。

1. 确保*aws\$1access\$1key\$1id*、和*aws\$1secret\$1access\$1key*、与`Session Token`您使用获得的`Access Key``Secret Access Key`、和*aws\$1session\$1token*相匹配`boto3.session`。有关详细信息，请参阅*适用于 Python (Boto3) 的 AWS SDK* 中的[凭证](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html)。

1. 有关可用端点的列表，请参阅[Amazon Keyspaces 的服务端点](programmatic.endpoints.md)。

# 使用 Cassandra Node.js 客户端驱动程序以编程方式访问 Amazon Keyspaces
<a name="using_nodejs_driver"></a>

 本部分介绍了如何使用 Node.js 客户端驱动程序连接 Amazon Keyspaces。要为用户和应用程序提供凭证，以通过编程方式访问 Amazon Keyspaces 资源，您可以执行以下任一操作：
+ 创建与特定 AWS Identity and Access Management (IAM) 用户关联的服务特定凭证。
+ 为了增强安全性，我们建议为所有 AWS 服务中使用的 IAM 用户或角色创建 IAM 访问密钥。借助适用于 Cassandra 客户端驱动程序的 Amazon Keyspaces SigV4 身份验证插件，您可以使用 IAM 访问密钥而不是用户名和密码来验证对 Amazon Keyspaces 的调用。有关更多信息，请参阅 [为 Amazon Keyspaces 创建和配置 AWS 证书](access.credentials.md)。

**Topics**
+ [开始前的准备工作](#using_nodejs_driver.BeforeYouBegin)
+ [使用适用于 Apache Cassandra 的 Node.js DataStax 驱动程序和特定于服务的凭证连接到亚马逊密钥空间](#nodejs_ssc)
+ [使用适用于 Apache Cassandra DataStax 的 Node.js 驱动程序和 SigV4 身份验证插件连接到亚马逊密钥空间](#nodejs_SigV4)

## 开始前的准备工作
<a name="using_nodejs_driver.BeforeYouBegin"></a>

在开始之前，您需要完成以下任务。

Amazon Keyspaces 要求使用传输层安全性协议 (TLS) 来帮助保护与客户端的连接。要使用 TLS 连接到 Amazon Keyspaces，您需要下载 Amazon 数字证书，并将 Python 驱动程序配置为使用 TLS。

 下载以下数字证书并将文件保存在本地或您的主目录中。

1. AmazonRootCA1

1. AmazonRootCA2

1. AmazonRootCA3

1. AmazonRootCA4

1. Starfield Class 2 Root（可选 — 为了向后兼容）

要下载证书，您可以使用以下命令。

```
curl -O https://www.amazontrust.com/repository/AmazonRootCA1.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA2.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA3.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA4.pem
curl -O https://certs.secureserver.net/repository/sf-class2-root.crt
```

**注意**  
Amazon Keyspaces 之前使用锚定在 Starfield Class 2 CA 上的 TLS 证书。 AWS 正在将所有证书全部迁移 AWS 区域 到根据亚马逊信任服务（Amazon Root CAs 1—4）颁发的证书。在此过渡期间，将客户端配置为同时信任 Amazon Root CAs 1—4 和 Starfield 根，以确保所有区域之间的兼容性。

将所有下载的证书合并到一个`pem`文件中，其名称与我们的示例*keyspaces-bundle.pem*中的名称相同。您可以使用以下 命令进行这项操作：记下文件的路径，稍后需要这个。

```
cat AmazonRootCA1.pem \
 AmazonRootCA2.pem \
 AmazonRootCA3.pem \
 AmazonRootCA4.pem \
 sf-class2-root.crt \
 > keyspaces-bundle.pem
```

## 使用适用于 Apache Cassandra 的 Node.js DataStax 驱动程序和特定于服务的凭证连接到亚马逊密钥空间
<a name="nodejs_ssc"></a>

 将您的驱动程序配置为使用 TLS 的组合证书文件`keyspaces-bundle.pem`，并使用特定于服务的凭据进行身份验证。例如：

```
const cassandra = require('cassandra-driver');
const fs = require('fs');
const auth = new cassandra.auth.PlainTextAuthProvider('ServiceUserName', 'ServicePassword');
const sslOptions1 = {
         ca: [
                    fs.readFileSync('path_to_file/keyspaces-bundle.pem', 'utf-8')],      
                    host: 'cassandra.us-west-2.amazonaws.com',
                    rejectUnauthorized: true
        };
const client = new cassandra.Client({
                   contactPoints: ['cassandra.us-west-2.amazonaws.com'],
                   localDataCenter: 'us-west-2',
                   authProvider: auth,
                   sslOptions: sslOptions1,
                   protocolOptions: { port: 9142 }
        });
const query = 'SELECT * FROM system_schema.keyspaces';
 
client.execute(query)
                    .then( result => console.log('Row from Keyspaces %s', result.rows[0]))
                    .catch( e=> console.log(`${e}`));
```

使用说明：

1. `"path_to_file/keyspaces-bundle.pem"`替换为第一步中保存的合并证书文件的路径。

1. 按照以下步骤操作，确保和与您在生成服务特定凭证时获得的用户名和密码*ServicePassword*相匹配。*ServiceUserName* [创建用于通过编程方式访问 Amazon Keyspaces 的服务特定凭证。](programmatic.credentials.ssc.md)

1. 有关可用端点的列表，请参阅[Amazon Keyspaces 的服务端点](programmatic.endpoints.md)。

## 使用适用于 Apache Cassandra DataStax 的 Node.js 驱动程序和 SigV4 身份验证插件连接到亚马逊密钥空间
<a name="nodejs_SigV4"></a>

以下部分介绍如何使用适用于 Apache Cassandra 的开源 DataStax Node.js 驱动程序的 Sigv4 身份验证插件来访问亚马逊密钥空间（适用于 Apache Cassandra）。

请按照[为 Amazon Keyspaces 创建和配置 AWS 证书](access.credentials.md)中的步骤为 IAM 用户或角色创建凭证（如果您尚未创建）。

[从存储库中将 Node.js Sigv4 身份验证插件添加到您的应用程序中。GitHub ](https://github.com/aws/aws-sigv4-auth-cassandra-nodejs-driver-plugin)该插件支持 Cassandra 的 DataStax Node.js 驱动程序版本 4.x，并且依赖于 Node.js 的 AWS SDK。它使用 `AWSCredentialsProvider` 获取凭证。

```
$ npm install aws-sigv4-auth-cassandra-plugin --save
```

本代码示例展示了如何将 `SigV4AuthProvider` 的区域特定实例设置为身份验证提供商。

```
const cassandra = require('cassandra-driver');
const fs = require('fs');
const sigV4 = require('aws-sigv4-auth-cassandra-plugin');

const auth = new sigV4.SigV4AuthProvider({
    region: 'us-west-2', 
    accessKeyId:'AKIAIOSFODNN7EXAMPLE',
    secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'});

const sslOptions1 = {
  ca: [
      fs.readFileSync('path_to_file/keyspaces-bundle.pem', 'utf-8')],
  host: 'cassandra.us-west-2.amazonaws.com',
  rejectUnauthorized: true
};


const client = new cassandra.Client({
  contactPoints: ['cassandra.us-west-2.amazonaws.com'],
  localDataCenter: 'us-west-2',
  authProvider: auth,
  sslOptions: sslOptions1,
  protocolOptions: { port: 9142 }
});


const query = 'SELECT * FROM system_schema.keyspaces';

client.execute(query).then(
    result => console.log('Row from Keyspaces %s', result.rows[0]))
    .catch( e=> console.log(`${e}`));
```

使用说明：

1. 将 `"path_to_file/keyspaces-bundle.pem"` 替换为第一步中保存的证书的路径。

1. 确保*accessKeyId*和*secretAccessKey*与您使用获得的访问密钥和私有访问密钥相匹配`AWSCredentialsProvider`。有关更多信息，请参阅 *Node.js 中的AWS SDK 中在 Node.js JavaScript 中*[设置凭证](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html)。

1. 要在代码之外存储访问密钥，请参阅[存储用于通过编程方式进行访问的访问密钥](aws.credentials.manage.md)中的最佳实践。

1. 有关可用端点的列表，请参阅[Amazon Keyspaces 的服务端点](programmatic.endpoints.md)。

# 使用 Cassandra .NET Core 客户端驱动程序以编程方式访问 Amazon Keyspaces
<a name="using_dotnetcore_driver"></a>

本部分介绍了如何使用 .NET Core 客户端驱动程序连接 Amazon Keyspaces。设置步骤因环境和操作系统而异，您可能需要相应地进行修改。Amazon Keyspaces 要求使用传输层安全性协议 (TLS) 来帮助保护与客户端的连接。要使用 TLS 连接到 Amazon Keyspaces，请将您的驱动程序配置为使用系统信任存储，其中包括亚马逊根 CAs 1-4。

1.  使用 nuget 控制台，通过 nuget 安装 Cassandra CSharp 驱动程序。

   ```
   PM> Install-Package CassandraCSharpDriver
   ```

1. 下面的示例使用 .NET Core C\$1 控制台项目连接到 Amazon Keyspaces 并运行查询。

   ```
   using Cassandra;
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Net.Security;
   using System.Runtime.ConstrainedExecution;
   using System.Security.Cryptography.X509Certificates;
   using System.Text;
   using System.Threading.Tasks;
   
   namespace CSharpKeyspacesExample
   {
       class Program
       {
           public Program(){}
   
           static void Main(string[] args)
           {
               var userName = "ServiceUserName";
               var pwd = "ServicePassword";
               certCollection.Add(amazoncert);
    
               var awsEndpoint =  "cassandra.us-east-2.amazonaws.com" ;  
   
               var cluster = Cluster.Builder()
                        .AddContactPoints(awsEndpoint)
                        .WithPort(9142)
                        .WithAuthProvider(new PlainTextAuthProvider(userName, pwd))
                        .WithSSL(new SSLOptions().SetCertificateCollection(certCollection))
                        .Build();
   
               var session = cluster.Connect();
               var rs = session.Execute("SELECT * FROM system_schema.tables;");
               foreach (var row in rs)
               {
                   var name = row.GetValue<String>("keyspace_name");
                   Console.WriteLine(name);
               }
           }
       }
   }
   ```

使用说明：

1. 请确保使用默认的系统信任存储库，其中包括 Amazon 根 CAs 1-4。

1. 按照以下步骤操作，确保和与您在生成服务特定凭证时获得的用户名和密码*ServicePassword*相匹配。*ServiceUserName* [创建用于通过编程方式访问 Amazon Keyspaces 的服务特定凭证。](programmatic.credentials.ssc.md)

1. 有关可用端点的列表，请参阅[Amazon Keyspaces 的服务端点](programmatic.endpoints.md)。

# 使用 Cassandra Go 客户端驱动程序以编程方式访问 Amazon Keyspaces
<a name="using_go_driver"></a>

本部分介绍了如何使用 Go Cassandra 客户端驱动程序连接 Amazon Keyspaces。要为用户和应用程序提供凭证，以通过编程方式访问 Amazon Keyspaces 资源，您可以执行以下任一操作：
+ 创建与特定 AWS Identity and Access Management (IAM) 用户关联的服务特定凭证。
+ 为了增强安全性，我们建议为所有 AWS 服务中使用的 IAM 委托人创建 IAM 访问密钥。借助适用于 Cassandra 客户端驱动程序的 Amazon Keyspaces SigV4 身份验证插件，您可以使用 IAM 访问密钥而不是用户名和密码来验证对 Amazon Keyspaces 的调用。有关更多信息，请参阅 [为 Amazon Keyspaces 创建和配置 AWS 证书](access.credentials.md)。

**Topics**
+ [开始前的准备工作](#using_go_driver.BeforeYouBegin)
+ [使用适用于 Apache Cassandra 的 Gocql 驱动程序和服务特定凭证连接 Amazon Keyspaces](#go_ssc)
+ [使用适用于 Apache Cassandra 的 Go 驱动程序和 SigV4 身份验证插件连接 Amazon Keyspaces](#go_SigV4)

## 开始前的准备工作
<a name="using_go_driver.BeforeYouBegin"></a>

在开始之前，您需要完成以下任务。

Amazon Keyspaces 要求使用传输层安全性协议 (TLS) 来帮助保护与客户端的连接。要使用 TLS 连接到 Amazon Keyspaces，您需要下载 Amazon 数字证书，并将 Go 驱动程序配置为使用 TLS。

 下载以下数字证书并将文件保存在本地或您的主目录中。

1. AmazonRootCA1

1. AmazonRootCA2

1. AmazonRootCA3

1. AmazonRootCA4

1. Starfield Class 2 Root（可选 — 为了向后兼容）

要下载证书，您可以使用以下命令。

```
curl -O https://www.amazontrust.com/repository/AmazonRootCA1.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA2.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA3.pem
curl -O https://www.amazontrust.com/repository/AmazonRootCA4.pem
curl -O https://certs.secureserver.net/repository/sf-class2-root.crt
```

**注意**  
Amazon Keyspaces 之前使用锚定在 Starfield Class 2 CA 上的 TLS 证书。 AWS 正在将所有证书全部迁移 AWS 区域 到根据亚马逊信任服务（Amazon Root CAs 1—4）颁发的证书。在此过渡期间，将客户端配置为同时信任 Amazon Root CAs 1—4 和 Starfield 根，以确保所有区域之间的兼容性。

将所有下载的证书合并到一个`pem`文件中，其名称与我们的示例*keyspaces-bundle.pem*中的名称相同。您可以使用以下 命令进行这项操作：记下文件的路径，稍后需要这个。

```
cat AmazonRootCA1.pem \
 AmazonRootCA2.pem \
 AmazonRootCA3.pem \
 AmazonRootCA4.pem \
 sf-class2-root.crt \
 > keyspaces-bundle.pem
```

## 使用适用于 Apache Cassandra 的 Gocql 驱动程序和服务特定凭证连接 Amazon Keyspaces
<a name="go_ssc"></a>

1. 为您的应用程序创建一个目录。

   ```
   mkdir ./gocqlexample
   ```

1. 导航到新目录。

   ```
   cd gocqlexample
   ```

1. 为应用程序创建一个文件。

   ```
   touch cqlapp.go
   ```

1. 下载 Go 驱动程序。

   ```
   go get github.com/gocql/gocql
   ```

1. 将以下示例代码添加到 cqlapp.go 文件。

   ```
   package main
   
   import (
   	    "fmt"
   	    "github.com/gocql/gocql"
   	    "log"
   )
   
   func main() {
   
       // add the Amazon Keyspaces service endpoint 
       cluster := gocql.NewCluster("cassandra.us-east-2.amazonaws.com")
       cluster.Port=9142
       // add your service specific credentials
       cluster.Authenticator = gocql.PasswordAuthenticator{
               Username: "ServiceUserName",
               Password: "ServicePassword"}
   
       // provide the path to the keyspaces-bundle.pem
       cluster.SslOpts = &gocql.SslOptions{
               CaPath: "path_to_file/keyspaces-bundle.pem",
               EnableHostVerification: false,            
        }
   
        // Override default Consistency to LocalQuorum
        cluster.Consistency = gocql.LocalQuorum
        cluster.DisableInitialHostLookup = false
   
        session, err := cluster.CreateSession()
        if err != nil {
               fmt.Println("err>", err)
        }
        defer session.Close()
   
        // run a sample query from the system keyspace
        var text string
        iter := session.Query("SELECT keyspace_name FROM system_schema.tables;").Iter()
        for iter.Scan(&text) {
               fmt.Println("keyspace_name:", text)
        }
        if err := iter.Close(); err != nil {
               log.Fatal(err)
        }
        session.Close()
   }
   ```

   使用说明：

   1. `"path_to_file/keyspaces-bundle.pem"`替换为第一步中保存的合并证书文件的路径。

   1. 按照以下步骤操作，确保和与您在生成服务特定凭证时获得的用户名和密码*ServicePassword*相匹配。*ServiceUserName* [创建用于通过编程方式访问 Amazon Keyspaces 的服务特定凭证。](programmatic.credentials.ssc.md)

   1. 有关可用端点的列表，请参阅[Amazon Keyspaces 的服务端点](programmatic.endpoints.md)。

1. 构建程序。

   ```
   go build cqlapp.go
   ```

1. 运行程序。

   ```
   ./cqlapp
   ```

## 使用适用于 Apache Cassandra 的 Go 驱动程序和 SigV4 身份验证插件连接 Amazon Keyspaces
<a name="go_SigV4"></a>

以下代码示例展示了如何使用开源 Go 驱动程序的 SigV4 身份验证插件访问 Amazon Keyspaces（Apache Cassandra 兼容）。

请按照[为 Amazon Keyspaces 创建和配置 AWS 证书](access.credentials.md)中的步骤为 IAM 主体创建凭证（如果您尚未创建）。如果应用程序在 Lambda 或 Amazon EC2 实例上运行，则您的应用程序将自动使用该实例的凭证。要在本地运行本教程，可以将凭证存储为本地环境变量。

[将 Go Sigv4 身份验证插件从存储库添加到您的应用程序中。GitHub](https://github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin)该插件支持适用于 Cassandra 的开源 Go 驱动程序 1.2.x 版本，并且依赖于 Go 的 AWS SDK。

```
$ go mod init
$ go get github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin
```

在此代码示例中，Amazon Keyspaces 端点由 `Cluster` 类表示。它使用集群的身份验证器属性 `AwsAuthenticator` 来获取凭证。

```
package main

import (
        "fmt"
        "github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin/sigv4"
        "github.com/gocql/gocql"
        "log"
)

func main() {
    // configuring the cluster options
    cluster := gocql.NewCluster("cassandra.us-west-2.amazonaws.com")
    cluster.Port=9142
    
    // the authenticator uses the default credential chain to find AWS credentials
    cluster.Authenticator = sigv4.NewAwsAuthenticator()

    cluster.SslOpts = &gocql.SslOptions{

            CaPath: "path_to_file/keyspaces-bundle.pem",
            EnableHostVerification: false,
    }
    cluster.Consistency = gocql.LocalQuorum
    cluster.DisableInitialHostLookup = false
   
    session, err := cluster.CreateSession()
    if err != nil {
	    fmt.Println("err>", err)
	    return
    }
    defer session.Close()

    // doing the query
    var text string
    iter := session.Query("SELECT keyspace_name FROM system_schema.tables;").Iter()
    for iter.Scan(&text) {
	    fmt.Println("keyspace_name:", text)
    }
    if err := iter.Close(); err != nil {
	    log.Fatal(err)
    }
}
```

使用说明：

1. `"path_to_file/keyspaces-bundle.pem"`替换为第一步中保存的证书文件的路径。

1. 要使此示例在本地运行，您需要将以下变量定义为环境变量：
   + `AWS_ACCESS_KEY_ID`
   + `AWS_SECRET_ACCESS_KEY`
   + `AWS_DEFAULT_REGION`

1. 要在代码之外存储访问密钥，请参阅[存储用于通过编程方式进行访问的访问密钥](aws.credentials.manage.md)中的最佳实践。

1. 有关可用端点的列表，请参阅[Amazon Keyspaces 的服务端点](programmatic.endpoints.md)。

# 使用 Cassandra Perl 客户端驱动程序以编程方式访问 Amazon Keyspaces
<a name="using_perl_driver"></a>

本部分介绍了如何使用 Perl 客户端驱动程序连接 Amazon Keyspaces。在本代码示例中，我们使用的是 Perl 5。Amazon Keyspaces 要求使用传输层安全性协议 (TLS) 来帮助保护与客户端的连接。

**重要**  
Amazon KeyspacesCertificents 正在过渡到亚马逊信任服务 (ATS) 层次结构。确保您的环境信任 Amazon 根 CAs 1—4，以避免在此轮换期间出现连接错误。Perl 驱动程序不会验证服务器的 Amazon SSL 证书，这意味着无法确认您是否能连接到 Amazon Keyspaces。第二步，务必要在连接 Amazon Keyspaces 时配置驱动程序以使用 TLS，这可以确保在客户端和服务器之间传输的数据经过加密。

1. 从 [https://metacpan.org/pod/DBD::Cassandra](https://metacpan.org/pod/DBD::Cassandra) 下载 Cassandra DBI 驱动程序，并将其安装到您的 Perl 环境中。具体步骤取决于您的环境。下面是一个常见示例。

   ```
   cpanm DBD::Cassandra
   ```

1. 为应用程序创建一个文件。

   ```
   touch cqlapp.pl
   ```

1. 将以下示例代码添加到 cqlapp.pl 文件。

   ```
   use DBI;
   my $user = "ServiceUserName";
   my $password = "ServicePassword";
   my $db = DBI->connect("dbi:Cassandra:host=cassandra.us-east-2.amazonaws.com;port=9142;tls=1;", 
   $user, $password);
   
   my $rows = $db->selectall_arrayref("select * from system_schema.keyspaces"); 
   print "Found the following Keyspaces...\n"; 
   for my $row (@$rows) { 
         print join(" ",@$row['keyspace_name']),"\n"; 
   } 
   
   $db->disconnect;
   ```
**重要**  
 按照以下步骤操作，确保和与您在生成服务特定凭证时获得的用户名和密码*ServicePassword*相匹配。*ServiceUserName* [创建用于通过编程方式访问 Amazon Keyspaces 的服务特定凭证。](programmatic.credentials.ssc.md)
**注意**  
有关可用端点的列表，请参阅[Amazon Keyspaces 的服务端点](programmatic.endpoints.md)。

1. 运行 应用程序。

   ```
   perl cqlapp.pl
   ```