快速入门:使用 gocql 客户端构建 Go 应用来管理 Azure Cosmos DB Cassandra API 数据Quickstart: Build a Go app with the gocql client to manage Azure Cosmos DB Cassandra API data

Azure Cosmos DB 是一种多模型数据库服务,可让你通过多区域分布和水平缩放功能快速创建和查询文档、表、键/值和图数据库。Azure Cosmos DB is a multi-model database service that lets you quickly create and query document, table, key-value, and graph databases with multiple-region distribution and horizontal scale capabilities. 在本快速入门中,你将首先创建一个 Azure Cosmos DB Cassandra API 帐户。In this quickstart, you will start by creating an Azure Cosmos DB Cassandra API account. 然后,你将运行一个 Go 应用程序来创建 Cassandra 密钥空间、表,并执行一些操作。You will then run a Go application to create a Cassandra keyspace, table, and execute a few operations. 此 Go 应用使用 gocql,这是 Go 语言的 Cassandra 客户端。This Go app uses gocql, which is a Cassandra client for the Go language.

先决条件Prerequisites

  • 具有活动订阅的 Azure 帐户。An Azure account with an active subscription. 免费创建一个Create one for free.

  • 在计算机上安装 Go,并了解 Go 的实践知识。Go installed on your computer, and a working knowledge of Go.

  • GitGit.

创建数据库帐户Create a database account

在创建数据库之前,需通过 Azure Cosmos DB 创建 Cassandra 帐户。Before you can create a database, you need to create a Cassandra account with Azure Cosmos DB.

  1. 在新浏览器窗口中,登录到 Azure 门户In a new browser window, sign in to the Azure portal.

  2. 在左侧菜单中,选择“创建资源” 。In the left menu, select Create a resource.

    在 Azure 门户中创建资源

  3. 在“新建”页上,选择“数据库” > “Azure Cosmos DB”。 On the New page, select Databases > Azure Cosmos DB.

    Azure 门户“数据库”窗格

  4. 在“创建 Azure Cosmos DB 帐户”页中,输入新 Azure Cosmos DB 帐户的设置 。On the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    设置Setting Value 说明Description
    订阅Subscription 你的订阅Your subscription 选择要用于此 Azure Cosmos DB 帐户的 Azure 订阅。Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    资源组Resource Group 新建Create new

    然后,输入与帐户名称相同的名称。Then enter the same name as Account Name
    选择“新建”。 Select Create new. 然后输入帐户的新资源组名称。Then enter a new resource group name for your account. 为简单起见,请使用与 Azure Cosmos 帐户名称相同的名称。For simplicity, use the same name as your Azure Cosmos account name.
    帐户名Account Name 输入唯一的名称Enter a unique name 输入标识此 Azure Cosmos DB 帐户的唯一名称。Enter a unique name to identify your Azure Cosmos DB account. 帐户 URI 将是追加到唯一帐户名称的“cassandra.cosmos.azure.cn” 。Your account URI will be cassandra.cosmos.azure.cn appended to your unique account name.

    帐户名称只能使用小写字母、数字及连字符 (-),必须为 3 到 31 个字符长。The account name can use only lowercase letters, numbers, and hyphens (-), and must be between 3 and 31 characters long.
    APIAPI CassandraCassandra API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:Core(SQL)(适用于文档数据库)、Gremlin(适用于图数据库)、MongoDB(适用于文档数据库)、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) for document databases, Gremlin for graph databases, MongoDB for document databases, Azure Table, and Cassandra. 必须为每种 API 创建单独的帐户。You must create a separate account for each API.

    选择“Cassandra” ,因为本快速入门将创建使用 Cassandra API 的表。Select Cassandra, because in this quickstart you are creating a table that works with the Cassandra API.

    详细了解 Cassandra APILearn more about the Cassandra API.
    位置Location 选择离用户最近的区域Select the region closest to your users 选择用于托管 Azure Cosmos DB 帐户的地理位置。Select a geographic location to host your Azure Cosmos DB account. 使用离用户最近的位置,使他们能够以最快的速度访问数据。Use the location that's closest to your users to give them the fastest access to the data.

    选择“查看 + 创建” 。Select Review+Create. 可以跳过“网络” 和“标记” 部分。You can skip the Network and Tags section.

    Azure Cosmos DB 的“新建帐户”页

  5. 创建帐户需要几分钟时间。The account creation takes a few minutes. 等待门户中显示“祝贺你! 已创建 Azure Cosmos DB 帐户”页。Wait for the portal to display the page saying Congratulations! Your Azure Cosmos DB account was created.

克隆示例应用程序Clone the sample application

首先从 GitHub 克隆应用程序开始。Start by cloning the application from GitHub.

  1. 打开命令提示符,然后创建一个新的名为 git-samples 的文件夹。Open a command prompt and create a new folder named git-samples.

    md "C:\git-samples"
    
  2. 打开 git 终端窗口(例如 git bash)。Open a git terminal window, such as git bash. 使用 cd 命令转到新文件夹并安装示例应用。Use the cd command to change into the new folder and install the sample app.

    cd "C:\git-samples"
    
  3. 运行下列命令以克隆示例存储库。Run the following command to clone the sample repository. 此命令在计算机上创建示例应用程序的副本。This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/azure-cosmos-db-cassandra-go-getting-started.git
    

查看代码Review the code

此步骤是可选的。This step is optional. 如果有心了解如何通过代码创建数据库资源,可以查看以下代码片段。If you're interested to learn how the code creates the database resources, you can review the following code snippets. 否则,可以跳到运行应用程序Otherwise, you can skip ahead to Run the application

GetSession 函数(utils\utils.go 的一部分)返回一个 *gocql.Session,该函数用于执行 insert、find 等群集操作。The GetSession function (part of utils\utils.go) returns a *gocql.Session that is used to execute cluster operations such as insert, find etc.

func GetSession(cosmosCassandraContactPoint, cosmosCassandraPort, cosmosCassandraUser, cosmosCassandraPassword string) *gocql.Session {
    clusterConfig := gocql.NewCluster(cosmosCassandraContactPoint)
    port, err := strconv.Atoi(cosmosCassandraPort)

    clusterConfig.Authenticator = gocql.PasswordAuthenticator{Username: cosmosCassandraUser, Password: cosmosCassandraPassword}
    clusterConfig.Port = port
    clusterConfig.SslOpts = &gocql.SslOptions{Config: &tls.Config{MinVersion: tls.VersionTLS12}}
    clusterConfig.ProtoVersion = 4

    session, err := clusterConfig.CreateSession()
    ...
    return session
}

会将 Azure Cosmos DB Cassandra 主机传递给 gocql.NewCluster 函数,以获取 *gocql.ClusterConfig 结构,然后进行配置,使其使用用户名、密码、端口以及合适的 TLS 版本(HTTPS/SSL/TLS 加密安全要求The Azure Cosmos DB Cassandra host is passed to the gocql.NewCluster function to get a *gocql.ClusterConfig struct that is then configured to use the username, password, port, and appropriate TLS version (HTTPS/SSL/TLS encryption Security requirement)

然后从 main 函数 (main.go) 调用 GetSession 函数。The GetSession function is then called from the main function (main.go).

func main() {
    session := utils.GetSession(cosmosCassandraContactPoint, cosmosCassandraPort, cosmosCassandraUser, cosmosCassandraPassword)
    defer session.Close()
    ...
}

以环境变量的形式接受连接信息和凭证(在 init 方法中解析)The connectivity information and credentials are accepted in the form of environment variables (resolved in the init method)

func init() {
    cosmosCassandraContactPoint = os.Getenv("COSMOSDB_CASSANDRA_CONTACT_POINT")
    cosmosCassandraPort = os.Getenv("COSMOSDB_CASSANDRA_PORT")
    cosmosCassandraUser = os.Getenv("COSMOSDB_CASSANDRA_USER")
    cosmosCassandraPassword = os.Getenv("COSMOSDB_CASSANDRA_PASSWORD")

    if cosmosCassandraContactPoint == "" || cosmosCassandraUser == "" || cosmosCassandraPassword == "" {
        log.Fatal("missing mandatory environment variables")
    }
}

然后使用它在 Azure Cosmos DB 上执行各种操作(operations\setup.go 的一部分),并从 keyspacetable 创建开始。It is then used to execute various operations (part of operations\setup.go) on Azure Cosmos DB starting with keyspace and table creation.

顾名思义,DropKeySpaceIfExists 函数只在 keyspace 存在时才会将其删除。As the name suggests, the DropKeySpaceIfExists function drops the keyspace only if it exists.

const dropKeyspace = "DROP KEYSPACE IF EXISTS %s"

func DropKeySpaceIfExists(keyspace string, session *gocql.Session) {
    err := utils.ExecuteQuery(fmt.Sprintf(dropKeyspace, keyspace), session)
    if err != nil {
        log.Fatal("Failed to drop keyspace", err)
    }
    log.Println("Keyspace dropped")
}

CreateKeySpace 函数用于创建 keyspace (user_profile)CreateKeySpace function is used to create the keyspace (user_profile)

const createKeyspace = "CREATE KEYSPACE %s WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 1 }"

func CreateKeySpace(keyspace string, session *gocql.Session) {
    err := utils.ExecuteQuery(fmt.Sprintf(createKeyspace, keyspace), session)
    if err != nil {
        log.Fatal("Failed to create keyspace", err)
    }
    log.Println("Keyspace created")
}

接下来是表创建 (user),它负责 CreateUserTable 函数This is followed by table creation (user) which is taken care of CreateUserTable function

const createTable = "CREATE TABLE %s.%s (user_id int PRIMARY KEY, user_name text, user_bcity text)"

func CreateUserTable(keyspace, table string, session *gocql.Session) {
    err := session.Query(fmt.Sprintf(createTable, keyspace, table)).Exec()
    if err != nil {
        log.Fatal("failed to create table ", err)
    }
    log.Println("Table created")
}

创建密钥空间和表后,调用 CRUD 操作(operations\crud.go 的一部分)。Once the keyspace and table are created, we invoke CRUD operations (part of operations\crud.go).

InsertUser 用于创建 UserInsertUser is used to create a User. 它使用 Bind 设置用户信息(ID、名称和城市)作为查询参数It sets the user info (ID, name, and city) as the query arguments using Bind

const createQuery = "INSERT INTO %s.%s (user_id, user_name , user_bcity) VALUES (?,?,?)"

func InsertUser(keyspace, table string, session *gocql.Session, user model.User) {
    err := session.Query(fmt.Sprintf(createQuery, keyspace, table)).Bind(user.ID, user.Name, user.City).Exec()
    if err != nil {
        log.Fatal("Failed to create user", err)
    }
    log.Println("User created")
}

FindUser 用于使用特定的用户 ID 搜索用户 (model\user.go),而 Scan 将用户属性(由 Cassandra 返回)绑定到单个变量(useridnamecity)- 这只是将获得的结果用作搜索查询结果的方法之一FindUser is used to search for a user (model\user.go) using a specific user ID while Scan binds the user attributes (returned by Cassandra) to individual variables (userid, name, city) -it is just one of the ways in which you can use the result obtained as the search query result

const selectQuery = "SELECT * FROM %s.%s where user_id = ?"

func FindUser(keyspace, table string, id int, session *gocql.Session) model.User {
    var userid int
    var name, city string
    err := session.Query(fmt.Sprintf(selectQuery, keyspace, table)).Bind(id).Scan(&userid, &name, &city)

    if err != nil {
        if err == gocql.ErrNotFound {
            log.Printf("User with id %v does not exist\n", id)
        } else {
            log.Printf("Failed to find user with id %v - %v\n", id, err)
        }
    }
    return model.User{ID: userid, Name: name, City: city}
}

FindAllUsers 用于提取所有用户。FindAllUsers is used to fetch all the users. SliceMap 作为速记方法使用,以 map 的片段形式获取用户的所有信息。SliceMap is used as a shorthand to get all the user's info in the form of a slice of maps. 将每个 map 看作键值对,其中列名称(例如 user_id)包含键及其相应的值。Think of each map as key-value pairs where column name (for example, user_id) is the key along with its respective value.

const findAllUsersQuery = "SELECT * FROM %s.%s"

func FindAllUsers(keyspace, table string, session *gocql.Session) []model.User {
    var users []model.User
    results, _ := session.Query(fmt.Sprintf(findAllUsersQuery, keyspace, table)).Iter().SliceMap()

    for _, u := range results {
        users = append(users, mapToUser(u))
    }
    return users
}

使用 mapToUser 函数将用户信息的每个 map 转换为 User,该函数只需从相应的列中提取值并使用它来创建 User 结构的实例即可Each map of user info is converted to a User using mapToUser function that simply extracts the value from its respective column and uses it to create an instance of the User struct

func mapToUser(m map[string]interface{}) model.User {
    id, _ := m["user_id"].(int)
    name, _ := m["user_name"].(string)
    city, _ := m["user_bcity"].(string)

    return model.User{ID: id, Name: name, City: city}
}

运行应用程序Run the application

如前所述,应用程序接受环境变量形式的连接和凭据。As previously mentioned, the application accepts connectivity and credentials in the form the environment variables.

  1. Azure 门户的 Azure Cosmos DB 帐户中,选择“连接字符串”。In your Azure Cosmos DB account in the Azure portal, select Connection String.

    从 Azure 门户中的连接字符串页面查看和复制详细信息

复制以下属性(CONTACT POINTPORTUSERNAMEPRIMARY PASSWORD)的值,并将它们设置为相应的环境变量Copy the values for the following attributes (CONTACT POINT, PORT, USERNAME and PRIMARY PASSWORD) and set them to the respective environment variables

set COSMOSDB_CASSANDRA_CONTACT_POINT=<value for "CONTACT POINT">
set COSMOSDB_CASSANDRA_PORT=<value for "PORT">
set COSMOSDB_CASSANDRA_USER=<value for "USERNAME">
set COSMOSDB_CASSANDRA_PASSWORD=<value for "PRIMARY PASSWORD">

在“终端”窗口中,切换到正确的文件夹。In the terminal window, change to the correct folder. 例如:For example:

cd "C:\git-samples\azure-cosmosdb-cassandra-go-getting-started"
  1. 在终端中,运行以下命令以启动应用程序。In the terminal, run the following command to start the application.

    go run main.go
    
  2. 终端窗口显示各种操作的通知信息,包括密钥空间和表设置、用户创建等。The terminal window displays notifications for the various operations including keyspace and table setup, user creation etc.

  3. 在 Azure 门户中,打开数据资源管理器,以查询、修改和处理这些新数据。In the Azure portal, open Data Explorer to query, modify, and work with this new data.

    在数据资源管理器中查看数据 - Azure Cosmos DB

在 Azure 门户中查看 SLAReview SLAs in the Azure portal

Azure 门户监视 Cosmos DB 帐户吞吐量、存储、可用性、延迟和一致性。The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Azure Cosmos DB 服务级别协议 (SLA) 关联的指标的图表显示与实际性能相比的 SLA 值。Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. 此套指标使得监视 SLA 十分透明。This suite of metrics makes monitoring your SLAs transparent.

若要查看指标和 SLA,请执行以下操作:To review metrics and SLAs:

  1. 在 Cosmos DB 帐户的导航菜单中选择“指标” 。Select Metrics in your Cosmos DB account's navigation menu.

  2. 选择一个选项卡,如“延迟” ,然后选择右侧的时间范围。Select a tab such as Latency, and select a timeframe on the right. 比较图表上的“实际” 和“SLA” 线。Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB 指标套件

  3. 查看其他选项卡上的指标。Review the metrics on the other tabs.

清理资源Clean up resources

执行完应用和 Azure Cosmos DB 帐户的操作以后,可以删除所创建的 Azure 资源,以免产生更多费用。When you're done with your app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. 若要删除资源,请执行以下操作:To delete the resources:

  1. 在 Azure 门户的“搜索”栏中,搜索并选择“资源组” 。In the Azure portal Search bar, search for and select Resource groups.

  2. 从列表中选择为本快速入门创建的资源组。From the list, select the resource group you created for this quickstart.

    选择要删除的资源组

  3. 在资源组“概览”页上,选择“删除资源组” 。On the resource group Overview page, select Delete resource group.

    删除资源组

  4. 在下一窗口中输入要删除的资源组的名称,然后选择“删除” 。In the next window, enter the name of the resource group to delete, and then select Delete.

后续步骤Next steps

本快速入门介绍了如何使用 Cassandra API 创建 Azure Cosmos DB 帐户,以及如何运行用于创建 Cassandra 数据库和容器的 Go 应用。In this quickstart, you learned how to create an Azure Cosmos DB account with Cassandra API, and run a Go app that creates a Cassandra database and container. 现在可以将其他数据导入 Azure Cosmos DB 帐户了。You can now import additional data into your Azure Cosmos DB account.