

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

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