快速入门:使用 Azure Cosmos DB 的用于 MongoDB 的 API 和 Golang SDK 生成控制台应用Quickstart: Build a console app using Azure Cosmos DB's API for MongoDB and Golang SDK

Azure Cosmos DB 是 Azure 提供的多区域分布式多模型数据库服务。Azure Cosmos DB is Azure's multiple-regionally distributed multi-model database service. 可快速创建和查询文档、键/值和图形数据库,所有这些都受益于 Cosmos DB 核心的多区域分布和水平缩放功能。You can quickly create and query document, key/value, and graph databases, all of which benefit from the multiple-region distribution and horizontal scale capabilities at the core of Cosmos DB.

本快速入门演示如何采用以 Golang 编写的现有 MongoDB 应用,并使用 Azure Cosmos DB 的用于 MongoDB 的 API 将其连接到 Cosmos 数据库。This quickstart demonstrates how to take an existing MongoDB app written in Golang and connect it to your Cosmos database using the Azure Cosmos DB's API for MongoDB.

换而言之,Golang 应用程序仅知道它要使用 MongoDB 客户端进行连接。In other words, your Golang application only knows that it's connecting using a MongoDB client. 该应用程序完全知道数据存储在 Cosmos 数据库中。It is transparent to the application that the data is stored in a Cosmos database.

先决条件Prerequisites

  • Azure 订阅。An Azure subscription. 如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

    对于本教程,可以使用 Azure Cosmos DB 模拟器,其连接字符串为:You can use the Azure Cosmos DB Emulator for this tutorial with a connection string of

    mongodb://localhost:C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==@localhost:10255/admin?ssl=true
    
  • Go 以及 Go 语言的基础知识。Go and a basic knowledge of the Go language.

  • IDE — GoLand(由 Jetbrains 推出)、Visual Studio Code(由 Microsoft 推出)或 AtomAn IDE — GoLand by Jetbrains, Visual Studio Code by Microsoft, or Atom. 在本教程中,我将使用 GoLand。In this tutorial, I'm using GoLand.

创建数据库帐户Create a database account

  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 DB 帐户名称相同的名称。For simplicity, use the same name as your Azure Cosmos DB account name.
    帐户名Account Name 输入唯一的名称Enter a unique name 输入标识此 Azure Cosmos DB 帐户的唯一名称。Enter a unique name to identify your Azure Cosmos DB account. 帐户 URI 将是追加到唯一帐户名称的“mongo.cosmos.azure.cn” 。Your account URI will be mongo.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 Azure Cosmos DB for Mongo DB APIAzure Cosmos DB for Mongo DB API API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:适用于文档数据库的 Core (SQL)、适用于图形数据库的 Gremlin、适用于文档数据库的 Azure Cosmos DB for Mongo DB API、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) for document databases, Gremlin for graph databases, Azure Cosmos DB for Mongo DB API for document databases, Azure Table, and Cassandra. 目前,你必须为每种 API 创建单独的帐户。Currently, you must create a separate account for each API.

    选择“Azure Cosmos DB for Mongo DB API”,因为本快速入门将创建使用 MongoDB 的集合 。Select Azure Cosmos DB for Mongo DB API because in this quickstart you are creating a collection that works with MongoDB.

    了解有关 Azure Cosmos DB for MongoDB API 的详细信息Learn more about Azure Cosmos DB for MongoDB 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 for MongoDB 帐户已准备就绪”页。Wait for the portal to display the Congratulations! Your Azure Cosmos DB for Mongo DB API account is ready page.

    Azure 门户“通知”窗格

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

克隆示例应用程序,并安装所需包。Clone the sample application and install the required packages.

  1. 在 GOROOT\src 文件夹(默认位于 C:\Go\ 中)中创建名为 CosmosDBSample 的文件夹。Create a folder named CosmosDBSample inside the GOROOT\src folder, which is C:\Go\ by default.

  2. 使用 git 终端窗口(例如 git bash)运行以下命令,将示例存储库克隆到 CosmosDBSample 文件夹中。Run the following command using a git terminal window such as git bash to clone the sample repository into the CosmosDBSample folder.

    git clone https://github.com/Azure-Samples/azure-cosmos-db-mongodb-golang-getting-started.git
    
  3. 运行以下命令以获取 mgo 包。Run the following command to get the mgo package.

    go get gopkg.in/mgo.v2
    

mgo 驱动程序是适用于 Go 语言MongoDB 驱动程序,该语言采用很简单的 API 和标准的 GO 惯用语,实现了多种经过严格测试的精选功能。The mgo driver is a MongoDB driver for the Go language that implements a rich and well tested selection of features under a very simple API following standard Go idioms.

更新连接字符串Update your connection string

现在返回到 Azure 门户,获取连接字符串信息,并将其复制到应用。Now go back to the Azure portal to get your connection string information and copy it into the app.

  1. 单击左侧导航菜单中的“快速启动”,并单击“其他”,查看 Go 应用程序所需的连接字符串信息。 Click Quick start in the left navigation menu, and then click Other to view the connection string information required by the Go application.

  2. 在 Goglang 的 GOROOT\CosmosDBSample 目录中打开 main.go 文件,并使用 Azure 门户中的连接字符串信息更新以下代码行,如以下屏幕截图所示。In Goglang, open the main.go file in the GOROOT\CosmosDBSample directory and update the following lines of code using the connection string information from the Azure portal as shown in the following screenshot.

    数据库名称是 Azure 门户连接字符串窗格中 Host 值的前缀。The Database name is the prefix of the Host value in the Azure portal connection string pane. 就下图所示帐户来说,数据库名称为 golang-coach。For the account shown in the image below, the Database name is golang-coach.

    Database: "The prefix of the Host value in the Azure portal",
    Username: "The Username in the Azure portal",
    Password: "The Password in the Azure portal",
    

    Azure 门户的“快速启动”窗格中的“其他”选项卡,显示连接字符串信息

  3. 保存 main.go 文件。Save the main.go file.

查看代码Review the code

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

以下代码片段全部摘自 main.go 文件。The following snippets are all taken from the main.go file.

将 Go 应用连接到 Cosmos DBConnecting the Go app to Cosmos DB

Azure Cosmos DB 的用于 MongoDB 的 API 支持启用了 TLS 的连接。Azure Cosmos DB's API for MongoDB supports the TLS-enabled connection. 若要进行连接,需在 mgo.DialInfo 中定义 DialServer 函数,然后使用 tls.Dial 函数进行连接。To connect, you need to define the DialServer function in mgo.DialInfo, and make use of the tls.Dial function to perform the connection.

以下 Golang 代码片段通过 Azure Cosmos DB 的用于 MongoDB 的 API 连接 Go 应用。The following Golang code snippet connects the Go app with Azure Cosmos DB's API for MongoDB. DialInfo 类包含用于建立会话的选项。The DialInfo class holds options for establishing a session.

// DialInfo holds options for establishing a session.
dialInfo := &mgo.DialInfo{
    Addrs:    []string{"golang-couch.documents.azure.cn:10255"}, // Get HOST + PORT
    Timeout:  60 * time.Second,
    Database: "database", // It can be anything
    Username: "username", // Username
    Password: "Azure database connect password from Azure Portal", // PASSWORD
    DialServer: func(addr *mgo.ServerAddr) (net.Conn, error) {
        return tls.Dial("tcp", addr.String(), &tls.Config{})
    },
}

// Create a session which maintains a pool of socket connections
// to Cosmos database (using Azure Cosmos DB's API for MongoDB).
session, err := mgo.DialWithInfo(dialInfo)

if err != nil {
    fmt.Printf("Can't connect, go error %v\n", err)
    os.Exit(1)
}

defer session.Close()

// SetSafe changes the session safety mode.
// If the safe parameter is nil, the session is put in unsafe mode, 
// and writes become fire-and-forget,
// without error checking. The unsafe mode is faster since operations won't hold on waiting for a confirmation.
// 
session.SetSafe(&mgo.Safe{})

没有 TLS 连接时会使用 mgo.Dial() 方法。The mgo.Dial() method is used when there is no TLS connection. 对于 TLS 连接,mgo.DialWithInfo() 方法是必需的。 For a TLS connection, the mgo.DialWithInfo() method is required.

可以使用 DialWIthInfo{} 对象的实例来创建会话对象。An instance of the DialWIthInfo{} object is used to create the session object. 建立会话以后,即可使用以下代码片段访问集合:Once the session is established, you can access the collection by using the following code snippet:

collection := session.DB("database").C("package")

创建文档Create a document

// Model
type Package struct {
    Id bson.ObjectId  `bson:"_id,omitempty"`
    FullName      string
    Description   string
    StarsCount    int
    ForksCount    int
    LastUpdatedBy string
}

// insert Document in collection
err = collection.Insert(&Package{
    FullName:"react",
    Description:"A framework for building native apps with React.",
    ForksCount: 11392,
    StarsCount:48794,
    LastUpdatedBy:"shergin",

})

if err != nil {
    log.Fatal("Problem inserting data: ", err)
    return
}

查询或读取文档Query or read a document

Cosmos DB 支持对存储在每个集合中的数据进行各种查询。Cosmos DB supports rich queries against data stored in each collection. 下面的示例代码演示可针对集合中文档运行的查询。The following sample code shows a query that you can run against the documents in your collection.

// Get a Document from the collection
result := Package{}
err = collection.Find(bson.M{"fullname": "react"}).One(&result)
if err != nil {
    log.Fatal("Error finding record: ", err)
    return
}

fmt.Println("Description:", result.Description)

更新文档Update a document

// Update a document
updateQuery := bson.M{"_id": result.Id}
change := bson.M{"$set": bson.M{"fullname": "react-native"}}
err = collection.Update(updateQuery, change)
if err != nil {
    log.Fatal("Error updating record: ", err)
    return
}

删除文档Delete a document

Cosmos DB 支持删除文档。Cosmos DB supports deletion of documents.

// Delete a document
query := bson.M{"_id": result.Id}
err = collection.Remove(query)
if err != nil {
   log.Fatal("Error deleting record: ", err)
   return
}

运行应用程序Run the app

  1. 在 Golang 中,确保 GOPATH(依次单击“文件”、“设置”、“Go”、“GOPATH”即可找到)包含安装 gopkg 时所在的位置,默认为 USERPROFILE\go。 In Golang, ensure that your GOPATH (available under File, Settings, Go, GOPATH) include the location in which the gopkg was installed, which is USERPROFILE\go by default.

  2. 注释掉用于删除文档的行(即第 103-107 行),这样就能在运行应用后看到文档。Comment out the lines that delete the document, lines 103-107, so that you can see the document after running the app.

  3. 在 Golang 中单击“运行”,然后单击“运行‘生成 main.go 并运行’”。 In Golang, click Run, and then click Run 'Build main.go and run'.

    应用完成后,将会显示在创建文档中创建的文档的说明。The app finishes and displays the description of the document created in Create a document.

    Description: A framework for building native apps with React.
    
    Process finished with exit code 0
    

    Golang,显示应用输出

在数据资源管理器中查看文档Review your document in Data Explorer

回到 Azure 门户,在数据资源管理器中查看文档。Go back to the Azure portal to see your document in Data Explorer.

  1. 在左侧导航菜单中单击“数据资源管理器(预览)”,展开“golang-coach”、“包”,并单击“文档”。 Click Data Explorer (Preview) in the left navigation menu, expand golang-coach, package, and then click Documents. 在“文档”选项卡中单击 “_id”,在右窗格中显示文档。In the Documents tab, click the _id to display the document in the right pane.

    数据资源管理器,显示新创建的文档

  2. 然后即可使用内联文档,单击“更新”将其保存。 You can then work with the document inline and click Update to save it. 也可删除该文档,或者创建新文档或查询。You can also delete the document, or create new documents or queries.

在 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

在本快速入门中,你已学习了如何创建 Cosmos 帐户和运行 Golang 应用。In this quickstart, you've learned how to create a Cosmos account and run a Golang app. 现在可以向你的 Cosmos 数据库导入更多数据。You can now import additional data to your Cosmos database.