

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

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