

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 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)。

**注意**  
為了協助您開始使用，您可以檢視和下載end-to-end程式碼範例，這些範例使用熱門驅動程式建立與 Amazon Keyspaces 的連線。請參閱 GitHub 上的 [Amazon Keyspaces 範例](https://github.com/aws-samples/amazon-keyspaces-examples)。

本章中的教學課程包含簡單的 CQL 查詢，以確認已成功建立與 Amazon Keyspaces 的連線。若要了解如何在連線至 Amazon Keyspaces 端點後使用金鑰空間和資料表，請參閱 [Amazon Keyspaces 的 CQL 語言參考 （適用於 Apache Cassandra)](cql.md)。如需示範如何從 Amazon VPC 端點連線至 Amazon Keyspaces 的step-by-step教學課程，請參閱 [教學課程：使用介面 VPC 端點連線至 Amazon Keyspaces](vpc-endpoints-tutorial.md)。

**Topics**
+ [

# 使用 Cassandra Java 用戶端驅動程式以程式設計方式存取 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 Java 用戶端驅動程式以程式設計方式存取 Amazon Keyspaces
<a name="using_java_driver"></a>

本節說明如何使用 Java 用戶端驅動程式連線至 Amazon Keyspaces。

**注意**  
Java 17 和 DataStax Java 驅動程式 4.17 目前僅支援 Beta 版。如需詳細資訊，請參閱[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)。

**注意**  
如需如何使用 Amazon Keyspaces 搭配 Spring Boot 的範例，請參閱 [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)
+ [

## 使用服務特定登入資料，使用適用於 Apache Cassandra 的 DataStax Java 驅動程式連線至 Amazon Keyspaces 的Step-by-step教學課程
](#java_tutorial)
+ [

## 使用適用於 Apache Cassandra 的 4.x DataStax Java 驅動程式和 SigV4 身分驗證外掛程式連線至 Amazon Keyspaces 的Step-by-step教學課程
](#java_tutorial.SigV4)
+ [

## 使用適用於 Apache Cassandra 的 3.x DataStax Java 驅動程式和 SigV4 身分驗證外掛程式連線至 Amazon Keyspaces
](#java3x_tutorial.SigV4)

## 開始之前
<a name="using_java_driver.BeforeYouBegin"></a>

若要連線至 Amazon Keyspaces，您需要先完成下列任務，才能開始。

1. Amazon Keyspaces 需要使用 Transport Layer Security (TLS) 來協助保護與用戶端的連線。

   1.  下載下列數位憑證，並將檔案儲存在本機或主目錄中。

      1. AmazonRootCA1

      1. AmazonRootCA2

      1. AmazonRootCA3

      1. AmazonRootCA4

      1. Starfield Class 2 根目錄 （選用 – 用於回溯相容性）

      若要下載憑證，您可以使用下列命令。

      ```
      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 類別 2 CA 為基礎的 TLS 憑證。 AWS 正在將所有 遷移 AWS 區域 至根據 Amazon Trust Services (Amazon 根 CAs 發行的憑證。在此轉換期間，請將用戶端設定為信任 Amazon 根 CAs1–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.  在 JVM 引數中連接 trustStore 檔案：

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

## 使用服務特定登入資料，使用適用於 Apache Cassandra 的 DataStax Java 驅動程式連線至 Amazon Keyspaces 的Step-by-step教學課程
<a name="java_tutorial"></a>

下列step-by-step教學課程會逐步引導您使用適用於 Cassandra 的 Java 驅動程式，使用服務特定的登入資料連線至 Amazon Keyspaces。具體而言，您將使用適用於 Apache Cassandra 的 DataStax 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 IAM 使用者產生服務特定的登入資料[建立服務特定的登入資料，以程式設計方式存取 Amazon Keyspaces](programmatic.credentials.ssc.md)。如果您偏好使用 IAM 存取金鑰進行身分驗證，請參閱 [使用適用於 Apache Cassandra 的 4.x DataStax Java 驅動程式和 SigV4 身分驗證外掛程式連線至 Amazon Keyspaces 的Step-by-step教學課程](#java_tutorial.SigV4)。
+ 將 Apache Cassandra 的 DataStax Java 驅動程式新增至您的 Java 專案。請確定您使用的驅動程式版本支援 Apache Cassandra 3.11.2。如需詳細資訊，請參閱 [Apache 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 驅動程式的身分驗證外掛程式來使用短期憑證，而不是驅動程式組態檔案中的硬式編碼憑證。若要進一步了解，請遵循 的指示[使用適用於 Apache Cassandra 的 4.x DataStax Java 驅動程式和 SigV4 身分驗證外掛程式連線至 Amazon Keyspaces 的Step-by-step教學課程](#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** – 使用指定具有 類別的單行，在組態檔案中新增區段，以初始化 SSLEngineFactory`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 路徑，或是將 trustStore 路徑新增至 JVM 引數。

### 步驟 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` 區塊，請記得關閉您的連線，以避免資源洩漏。

## 使用適用於 Apache Cassandra 的 4.x DataStax Java 驅動程式和 SigV4 身分驗證外掛程式連線至 Amazon Keyspaces 的Step-by-step教學課程
<a name="java_tutorial.SigV4"></a>

下一節說明如何使用開放原始碼 4.x DataStax Java 驅動程式的 SigV4 身分驗證外掛程式，讓 Apache Cassandra 存取 Amazon Keyspaces （適用於 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>

若要遵循本教學課程，您需要完成下列任務。
+ 如果您尚未這麼做，請依照 中的步驟為 IAM 使用者或角色建立登入資料[建立和設定 Amazon Keyspaces 的 AWS 登入資料](access.credentials.md)。本教學假設存取金鑰儲存為環境變數。如需詳細資訊，請參閱[存放用於程式設計存取的存取金鑰](aws.credentials.manage.md)。
+ 將 Apache Cassandra 的 DataStax Java 驅動程式新增至您的 Java 專案。請確定您使用的驅動程式版本支援 Apache Cassandra 3.11.2。如需詳細資訊，請參閱 [DataStax Java Driver for Apache Cassandra 文件](https://github.com/datastax/java-driver)。
+ 將身分驗證外掛程式新增至您的應用程式。身分驗證外掛程式支援適用於 Apache Cassandra 的 DataStax 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`。SigV4AuthProvider 是由外掛程式提供的身分驗證處理常式，用於執行 SigV4 身分驗證。

1. **本機資料中心** – 將 的值設定為您要連線`local-datacenter`的區域。例如，如果應用程式正在連線至 `cassandra.us-east-2.amazonaws.com`，請將本機資料中心設定為 `us-east-2`。如需所有可用的 AWS 區域，請參閱 [Amazon Keyspaces 的服務端點](programmatic.endpoints.md)。`slow-replica-avoidance = false` 設定為針對所有可用節點進行負載平衡。

1. **冪等性** – 將應用程式的預設值設定為 `true`，以設定驅動程式一律重試失敗`idempotence`的read/write/prepare/執行請求。這是分散式應用程式的最佳實務，可透過重試失敗的請求，協助處理暫時性故障。

1. **SSL/TLS** – 初始化 SSLEngineFactory，方法是在組態檔案中新增一個區段，並使用 指定類別`class = DefaultSslEngineFactory`。提供 trustStore 檔案的路徑以及您先前建立的密碼。Amazon Keyspaces 不支援`hostname-validation`對等，因此請將此選項設定為 false。

1. **連線** – 透過設定 ，為每個端點建立至少 3 個本機連線`local.size = 3`。這是最佳實務，可協助應用程式處理額外負荷和流量暴增。如需如何根據預期的流量模式，計算應用程式每個端點需要多少本機連線的詳細資訊，請參閱 [如何在 Amazon Keyspaces 中設定連線](connections.md#connections.howtoconfigure)。

1. **重試政策** – 實作 Amazon Keyspaces 重試政策`DefaultRetryPolicy`，`AmazonKeyspacesExponentialRetryPolicy`而非 Cassandra 驅動程式隨附的 。這可讓您為`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 路徑，或是將 trustStore 路徑新增至 JVM 引數。

### 步驟 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 身分驗證外掛程式連線至 Amazon Keyspaces
<a name="java3x_tutorial.SigV4"></a>

下一節說明如何使用 3.x 開放原始碼 DataStax Java 驅動程式的 SigV4 身分驗證外掛程式，讓 Apache Cassandra 存取 Amazon Keyspaces。外掛程式可從 [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>

若要執行此程式碼範例，您必須先完成下列任務。
+ 遵循 中的步驟，為您的 IAM 使用者或角色建立登入資料[建立和設定 Amazon Keyspaces 的 AWS 登入資料](access.credentials.md)。本教學假設存取金鑰會儲存為環境變數。如需詳細資訊，請參閱[存放用於程式設計存取的存取金鑰](aws.credentials.manage.md)。
+ 請依照 中的步驟[開始之前](#using_java_driver.BeforeYouBegin)下載數位憑證、將其轉換為 trustStore 檔案，並將 JVM 引數中的金鑰存放區連接至您的應用程式。
+ 將 Apache Cassandra 的 DataStax Java 驅動程式新增至您的 Java 專案。請確定您使用的驅動程式版本支援 Apache Cassandra 3.11.2。如需詳細資訊，請參閱 [DataStax Java Driver for Apache Cassandra 文件](https://github.com/datastax/java-driver)。
+ 將身分驗證外掛程式新增至您的應用程式。身分驗證外掛程式支援適用於 Apache Cassandra 的 DataStax 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 驅動程式搭配 Amazon Keyspaces 時的實用 Java 驅動程式政策、範例和最佳實務，請參閱下列儲存庫：[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 的 DataStax Python 驅動程式和 SigV4 身分驗證外掛程式連線至 Amazon Keyspaces
](#python_SigV4)

## 開始之前
<a name="using_python_driver.BeforeYouBegin"></a>

您需要先完成下列任務，才能開始。

Amazon Keyspaces 需要使用 Transport Layer Security (TLS) 來協助保護與用戶端的連線。若要使用 TLS 連線至 Amazon Keyspaces，您需要下載 Amazon 數位憑證，並將 Python 驅動程式設定為使用 TLS。

 下載下列數位憑證，並將檔案儲存在本機或主目錄中。

1. AmazonRootCA1

1. AmazonRootCA2

1. AmazonRootCA3

1. AmazonRootCA4

1. Starfield Class 2 根目錄 （選用 – 用於回溯相容性）

若要下載憑證，您可以使用下列命令。

```
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 類別 2 CA 的 TLS 憑證。 AWS 正在將所有 遷移 AWS 區域 至根據 Amazon Trust Services (Amazon 根 CAs 發行的憑證。在此轉換期間，請將用戶端設定為信任 Amazon 根 CAs1–4 和 Starfield 根，以確保所有區域的相容性。

使用範例中的名稱 *keyspaces-bundle.pem*，將所有下載的憑證合併成單一`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. 依照 的步驟，確保 *ServiceUserName* 和 *ServicePassword* 與您產生服務特定登入資料時取得的使用者名稱和密碼相符[建立服務特定的登入資料，以程式設計方式存取 Amazon Keyspaces](programmatic.credentials.ssc.md)。

1. 如需可用端點的清單，請參閱 [Amazon Keyspaces 的服務端點](programmatic.endpoints.md)。

## 使用適用於 Apache Cassandra 的 DataStax Python 驅動程式和 SigV4 身分驗證外掛程式連線至 Amazon Keyspaces
<a name="python_SigV4"></a>

下一節說明如何使用開放原始碼 DataStax Python 驅動程式的 SigV4 身分驗證外掛程式，讓 Apache Cassandra 存取 Amazon Keyspaces （適用於 Apache Cassandra)。

如果您尚未這麼做，請先依照 中的步驟，為您的 IAM 角色建立登入資料[建立和設定 Amazon Keyspaces 的 AWS 登入資料](access.credentials.md)。本教學課程使用臨時登入資料，需要 IAM 角色。如需臨時登入資料的詳細資訊，請參閱 [使用 IAM 角色和 SigV4 外掛程式建立臨時登入資料以連線至 Amazon Keyspaces](temporary.credentials.IAM.md)。

然後，從 [GitHub 儲存庫](https://github.com/aws/aws-sigv4-auth-cassandra-python-driver-plugin)將 Python SigV4 身分驗證外掛程式新增至您的環境。

```
pip install cassandra-sigv4
```

下列程式碼範例示範如何使用適用於 Cassandra 的開放原始碼 DataStax Python 驅動程式和 SigV4 身分驗證外掛程式連線至 Amazon 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* 和 *aws\$1session\$1token* 符合 `Access Key`、 `Secret Access Key``Session Token`以及您使用 取得的 `boto3.session`。如需詳細資訊，請參閱 中的[登入資料](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html)*適用於 Python (Boto3) 的 AWS SDK*。

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 驅動程式和服務特定登入資料連線至 Amazon Keyspaces
](#nodejs_ssc)
+ [

## 使用適用於 Apache Cassandra 的 DataStax Node.js 驅動程式和 SigV4 身分驗證外掛程式連線至 Amazon Keyspaces
](#nodejs_SigV4)

## 開始之前
<a name="using_nodejs_driver.BeforeYouBegin"></a>

您需要先完成下列任務，才能開始。

Amazon Keyspaces 需要使用 Transport Layer Security (TLS) 來協助保護與用戶端的連線。若要使用 TLS 連線至 Amazon Keyspaces，您需要下載 Amazon 數位憑證，並將 Python 驅動程式設定為使用 TLS。

 下載下列數位憑證，並將檔案儲存在本機或主目錄中。

1. AmazonRootCA1

1. AmazonRootCA2

1. AmazonRootCA3

1. AmazonRootCA4

1. Starfield Class 2 根目錄 （選用 – 用於回溯相容性）

若要下載憑證，您可以使用下列命令。

```
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 類別 2 CA 的 TLS 憑證。 AWS 正在將所有 遷移 AWS 區域 至根據 Amazon Trust Services (Amazon 根 CAs 發行的憑證。在此轉換期間，請將用戶端設定為信任 Amazon 根 CAs1–4 和 Starfield 根，以確保所有區域的相容性。

使用範例中的名稱 *keyspaces-bundle.pem*，將所有下載的憑證合併成單一`pem`檔案。您可以執行下列 命令，即可進行新增：請記下 檔案的路徑，您稍後會需要此項目。

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

## 使用適用於 Apache Cassandra 的 Node.js DataStax 驅動程式和服務特定登入資料連線至 Amazon Keyspaces
<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. 依照 的步驟，確保 *ServiceUserName* 和 *ServicePassword* 與您產生服務特定登入資料時取得的使用者名稱和密碼相符[建立服務特定的登入資料，以程式設計方式存取 Amazon Keyspaces](programmatic.credentials.ssc.md)。

1. 如需可用端點的清單，請參閱 [Amazon Keyspaces 的服務端點](programmatic.endpoints.md)。

## 使用適用於 Apache Cassandra 的 DataStax Node.js 驅動程式和 SigV4 身分驗證外掛程式連線至 Amazon Keyspaces
<a name="nodejs_SigV4"></a>

下一節說明如何針對 Apache Cassandra 的開放原始碼 DataStax Node.js 驅動程式使用 SigV4 身分驗證外掛程式來存取 Amazon Keyspaces （適用於 Apache Cassandra)。

如果您尚未這麼做，請依照 中的步驟為 IAM 使用者或角色建立登入資料[建立和設定 Amazon Keyspaces 的 AWS 登入資料](access.credentials.md)。

從 [GitHub 儲存庫](https://github.com/aws/aws-sigv4-auth-cassandra-nodejs-driver-plugin)將 Node.js SigV4 身分驗證外掛程式新增至您的應用程式。外掛程式支援適用於 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 中適用於 JavaScript 的 SDK 中的在 Node.js 中設定登入](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html)資料。 *AWS JavaScript * 

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 需要使用 Transport Layer Security (TLS) 來協助保護與用戶端的連線。若要使用 TLS 連線至 Amazon Keyspaces，請將驅動程式設定為使用系統信任存放區，其中包含 Amazon 根 CAs1-4。

1.  使用 nuget 主控台透過 nuget 安裝 CassandraCSharpDriver。

   ```
   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 根 CAs1-4。

1. 依照 的步驟，確定 *ServiceUserName* 和 *ServicePassword* 與您產生服務特定登入資料時取得的使用者名稱和密碼相符[建立服務特定的登入資料，以程式設計方式存取 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 需要使用 Transport Layer Security (TLS) 來協助保護與用戶端的連線。若要使用 TLS 連線至 Amazon Keyspaces，您需要下載 Amazon 數位憑證，並將 Go 驅動程式設定為使用 TLS。

 下載下列數位憑證，並將檔案儲存在本機或主目錄中。

1. AmazonRootCA1

1. AmazonRootCA2

1. AmazonRootCA3

1. AmazonRootCA4

1. Starfield Class 2 根目錄 （選用 – 用於回溯相容性）

若要下載憑證，您可以使用下列命令。

```
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 類別 2 CA 的 TLS 憑證。 AWS 正在將所有 遷移 AWS 區域 至根據 Amazon Trust Services (Amazon 根 CAs 發行的憑證。在此轉換期間，請將用戶端設定為信任 Amazon 根 CAs1–4 和 Starfield 根，以確保所有區域的相容性。

使用範例中的名稱 *keyspaces-bundle.pem*，將所有下載的憑證合併成單一`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. 依照 的步驟，確保 *ServiceUserName* 和 *ServicePassword* 與您產生服務特定登入資料時取得的使用者名稱和密碼相符[建立服務特定的登入資料，以程式設計方式存取 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)。

如果您尚未這麼做，請依照 中的步驟建立 IAM 主體的登入資料[建立和設定 Amazon Keyspaces 的 AWS 登入資料](access.credentials.md)。如果應用程式在 Lambda 或 Amazon EC2 執行個體上執行，您的應用程式會自動使用執行個體的登入資料。若要在本機執行本教學課程，您可以將登入資料儲存為本機環境變數。

從 [GitHub 儲存庫](https://github.com/aws/aws-sigv4-auth-cassandra-gocql-driver-plugin)將 Go SigV4 身分驗證外掛程式新增至您的應用程式。外掛程式支援適用於 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 需要使用 Transport Layer Security (TLS) 來協助保護與用戶端的連線。

**重要**  
Amazon Keyspacescertificates 正在轉換至 Amazon Trust Services (ATS) 階層。確保您的環境信任 Amazon 根 CAs1–4，以避免在此輪換期間發生連線錯誤。Perl 驅動程式不會驗證伺服器的 Amazon SSL 憑證，這表示您無法確認您連線到 Amazon Keyspaces。第二個步驟是設定驅動程式在連線至 Amazon Keyspaces 時使用 TLS，並確保用戶端和伺服器之間傳輸的資料已加密。

1. 從 下載 Cassandra DBI 驅動程式，[https://metacpan.org/pod/DBD::Cassandra](https://metacpan.org/pod/DBD::Cassandra)並將驅動程式安裝到您的 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;
   ```
**重要**  
 依照 的步驟，確定 *ServiceUserName* 和 *ServicePassword* 與您產生服務特定登入資料時取得的使用者名稱和密碼相符[建立服務特定的登入資料，以程式設計方式存取 Amazon Keyspaces](programmatic.credentials.ssc.md)。
**注意**  
如需可用端點的清單，請參閱 [Amazon Keyspaces 的服務端點](programmatic.endpoints.md)。

1. 執行應用程式。

   ```
   perl cqlapp.pl
   ```