你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:适用于 Go 的 Azure Cosmos DB for Apache Cassandra 客户端库

适用于 Go 的 Azure Cosmos DB for Apache Cassandra 客户端库入门,用于存储、管理和查询非结构化数据。 按照本指南中的步骤创建新帐户、安装 Go 客户端库、连接到帐户、执行常见作以及查询最终示例数据。

API 参考文档 | 库源代码 | 包 (Go)

先决条件

  • Azure 订阅服务

    • 如果没有 Azure 订阅,请在开始之前创建一个免费帐户
  • Go 1.24 或更高版本

设置

首先,为本指南设置帐户和开发环境。 本部分将指导你完成创建帐户、获取其凭据以及准备开发环境的过程。

创建帐户

首先,创建用于 Apache Cassandra 帐户的 API。 创建帐户后,创建密钥空间和表资源。

  1. 如果还没有目标资源组,请使用 az group create 命令在订阅中创建新的资源组。

    az group create \
        --name "<resource-group-name>" \
        --location "<location>"
    
  2. 使用az cosmosdb create命令来创建一个具有默认设置的适用于Apache Cassandra的新Azure Cosmos DB帐户。

    az cosmosdb create \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --locations "regionName=<location>" \
        --capabilities "EnableCassandra"
    
  3. 使用 az cosmosdb cassandra keyspace create 命名的 cosmicworks 创建新的密钥空间。

    az cosmosdb cassandra keyspace create \
        --resource-group "<resource-group-name>" \
        --account-name "<account-name>" \
        --name "cosmicworks"
    
  4. 使用多行 Bash 命令创建新的 JSON 对象来表示架构。 然后,使用 az cosmosdb cassandra table create 命令创建一个名为 products 的新表。

    schemaJson=$(cat <<EOF
    {
      "columns": [
        {
          "name": "id",
          "type": "text"
        },
        {
          "name": "name",
          "type": "text"
        },
        {
          "name": "category",
          "type": "text"
        },
        {
          "name": "quantity",
          "type": "int"
        },
        {
          "name": "price",
          "type": "decimal"
        },
        {
          "name": "clearance",
          "type": "boolean"
        }
      ],
      "partitionKeys": [
        {
          "name": "id"
        }
      ]
    }
    EOF
    )
    
    az cosmosdb cassandra table create \
        --resource-group "<resource-group-name>" \
        --account-name "<account-name>" \
        --keyspace-name "cosmicworks" \
        --name "product" \
        --schema "$schemaJson"
    

获取凭据

现在,获取用于创建与最近创建的帐户的连接的客户端库的密码。

  1. 使用 az cosmosdb show 获取帐户的联系点和用户名。

    az cosmosdb show \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --query "{username:name,contactPoint:documentEndpoint}"
    
  2. 记录上述命令输出中的 contactPoint 值和 username 属性。 这些属性的值分别是“联系点”和“用户名”,将在本指南的后续步骤中使用它们通过库连接到该帐户。

  3. 使用 az cosmosdb keys list 来获取帐户的 密钥

    az cosmosdb keys list \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --type "keys"
    
  4. 记录来自上一个命令输出的属性 primaryMasterKey 的值。 此属性的值是稍后在本指南中使用的 密码 ,用于使用库连接到帐户。

准备开发环境

然后,使用新项目和客户端库配置开发环境。 在转到本指南的其余部分之前,此步骤是最后一个必需的先决条件。

  1. 从空目录中开始。

  2. 创建新的 Go 模块。

    go mod init quickstart
    
  3. github.com/apache/cassandra-gocql-driver/v2包导入 Go。

    go get github.com/apache/cassandra-gocql-driver/v2
    
  4. 创建 main.go 文件。

  5. 添加 Go 应用程序代码模板。

    package main
    
    func main() {    
    }
    

    重要

    本指南中的剩余步骤假定你在函数中添加 main 代码。

对象模型

DESCRIPTION
Cluster 表示与群集的特定连接
Session 保持与群集的特定连接的实体

代码示例

对客户端进行身份验证

首先,使用本指南前面收集的凭据对客户端进行身份验证。

  1. 在集成开发环境中打开 main.go 文件(IDE)。

  2. main 函数中,导入以下包以及 github.com/apache/cassandra-gocql-driver/v2 包:

    • context
    • crypto/tls
    import (
        "context"
        "crypto/tls"
        "github.com/apache/cassandra-gocql-driver/v2"
    )
    
  3. 为本指南前面收集的凭据创建字符串变量。 为变量 username命名, password以及 contactPoint

    username := "<username>"
    password := "<password>"
    contactPoint := "<contact-point>"
    
  4. 使用前几步中指定的凭据,配置一个 PasswordAuthenticator 类型的实例。 将结果存储在名为 authentication 的变量中。

    authentication := gocql.PasswordAuthenticator{
        Username: username,
        Password: password,
    }
    
  5. 配置一个实例SslOptions,要求最低传输层安全性版本为 TLS 1.2,并使用contactPoint变量作为目标服务器名称。 将结果存储在名为 sslOptions 的变量中。

    sslOptions := &gocql.SslOptions{
        Config: &tls.Config{
            MinVersion: tls.VersionTLS12,
            ServerName: contactPoint,
        },
    }
    
  6. 使用 NewCluster 变量和 contactPoint 变量创建新的群集规范。

    cluster := gocql.NewCluster(contactPoint)
    
  7. 使用前面步骤中创建的凭据和配置变量配置群集规范对象。

    cluster.SslOpts = sslOptions
    cluster.Authenticator = authentication
    
  8. 使用这些静态值配置群集规范对象的其余部分。

    cluster.Keyspace = "cosmicworks"
    cluster.Port = 10350
    cluster.ProtoVersion = 4    
    
  9. 创建一个新的会话,使用 CreateSession 连接到群集。

    session, _ := cluster.CreateSession()
    
  10. 配置会话以在main函数返回后调用Close函数。

    defer session.Close()
    
  11. 创建新的 Background 上下文对象并将其存储在变量中 ctx

    ctx := context.Background()
    

警告

本指南中禁用了完整的传输层安全性(TLS)验证,以简化身份验证。 对于生产部署,请完全启用验证。

更新插入数据

接下来,将新数据插入或更新到表中。 Upserting 可确保根据表中是否已存在相同的数据,适当地创建或替换数据。

  1. 定义一个名为 Product 的新类型,使其字段与本指南前面创建的表格相对应。

    type Product struct {
        id        string
        name      string
        category  string
        quantity  int
        clearance bool
    }
    

    小窍门

    在 Go 中,可以在另一个文件中创建此类型,或在现有文件末尾创建它。

  2. 创建一个Product类型的新对象。 将对象存储在名为 .. 的 product变量中。

    product := Product {
        id:        "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
        name:      "Yamba Surfboard",
        category:  "gear-surf-surfboards",
        quantity:  12,
        clearance: false,
    }
    
  3. 创建一个名为 Cassandra 查询语言(CQL)查询的新字符串变量 insertQuery ,用于插入新行。

    insertQuery := `
        INSERT INTO
            product (id, name, category, quantity, clearance)
        VALUES
            (?, ?, ?, ?, ?)
    `
    
  4. 使用QueryExecContext函数来运行查询。 以查询参数的形式传入变量的各种属性 product

    _ = session.Query(
        insertQuery,
        product.id, 
        product.name, 
        product.category, 
        product.quantity, 
        product.clearance,
    ).ExecContext(ctx)
    

读取数据

然后,读取以前插入到表中的数据。

  1. 创建一个名为 CQL 查询的新字符串变量 readQuery ,该查询与具有相同 id 字段的项匹配。

    readQuery := `
        SELECT
            id,
            name,
            category,
            quantity,
            clearance
        FROM
            product
        WHERE id = ?
        LIMIT 1
    `
    
  2. 创建与本指南前面创建的产品相同的值的字符串变量 id

    id := "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb" 
    
  3. 创建另一个名为 matchedProduct 用于存储此作结果的变量。

    var matchedProduct Product
    
  4. 使用QueryConsistencyIterContextScan函数来查找与查询匹配的单个项,并将其属性分配给matchedProduct变量。

    session.Query(
        readQuery,
        &id,
    ).Consistency(gocql.One).IterContext(ctx).Scan(
        &matchedProduct.id,
        &matchedProduct.name,
        &matchedProduct.category,
        &matchedProduct.quantity,
        &matchedProduct.clearance,
    )
    

查询数据

最后,使用查询查找与表中特定筛选器匹配的所有数据。

  1. 创建名为 findQuerycategory 的字符串变量,包括 CQL 查询和必需参数。

    findQuery := `
        SELECT
            id,
            name,
            category,
            quantity,
            clearance
        FROM
            product
        WHERE
            category = ?
        ALLOW FILTERING
    `
    
    category := "gear-surf-surfboards"
    
  2. 结合使用QueryConsistencyIterContextScanner函数来创建可以遍历与查询匹配的多个项目的扫描程序。

    queriedProducts := session.Query(
        findQuery, 
        &category,
    ).Consistency(gocql.All).IterContext(ctx).Scanner()
    
  3. 使用NextScan函数遍历查询结果,并将每个结果的属性分配给内部queriedProduct变量。

    for queriedProducts.Next() {
        var queriedProduct Product
        queriedProducts.Scan(
            &queriedProduct.id,
            &queriedProduct.name,
            &queriedProduct.category,
            &queriedProduct.quantity,
            &queriedProduct.clearance,
        )
        // Do something here with each result
    }
    

运行代码

使用应用程序目录中的终端运行新创建的应用程序。

go run .

清理资源

现在,获取用于创建与最近创建的帐户的连接的客户端库的密码。

  1. 使用 az cosmosdb show 获取帐户的联系点和用户名。

    az cosmosdb show \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --query "{username:name,contactPoint:documentEndpoint}"
    
  2. 记录上述命令输出中的 contactPoint 值和 username 属性。 这些属性的值分别是“联系点”和“用户名”,将在本指南的后续步骤中使用它们通过库连接到该帐户。

  3. 使用 az cosmosdb keys list 来获取帐户的 密钥

    az cosmosdb keys list \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --type "keys"
    
  4. 记录来自上一个命令输出的属性 primaryMasterKey 的值。 此属性的值是稍后在本指南中使用的 密码 ,用于使用库连接到帐户。

后续步骤