快速入门:使用 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 是 21Vianet 提供的多区域分布式多模型数据库服务。Azure Cosmos DB is 21Vianet's multiple-region distributed multi-model database service. 可快速创建和查询文档数据库,这些数据库受益于 Cosmos DB 核心的多区域分布和水平缩放功能。You can quickly create and query document database, 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 window, sign in to the Azure portal.

  2. 在左菜单中,依次单击“创建资源”、“数据库”,然后在“Azure Cosmos DB”下单击“创建”。In the left menu, click Create a resource, click Databases, and then under Azure Cosmos DB, click Create.

    Azure 门户的屏幕截图,其中突出显示了“更多服务”和“Azure Cosmos DB”

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

    设置Setting Value DescriptionDescription
    订阅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

    然后输入在 ID 中提供的同一唯一名称Then enter the same unique name as provided in ID
    选择“新建”。Select Create new. 然后输入帐户的新资源组名称。Then enter a new resource-group name for your account. 为简单起见,可以使用与 ID 相同的名称。For simplicity, use the same name as your ID.
    帐户名Account Name 输入唯一的名称Enter a unique name 输入标识此 Azure Cosmos DB 帐户的唯一名称。Enter a unique name to identify your Azure Cosmos DB account. 由于 documents.azure.cn 字符串将追加到所提供的 ID 后面以创建 URI,因此,请使用唯一的 ID。Because documents.azure.cn is appended to the ID that you provide to create your URI, use a unique ID.

    该 ID 只能使用小写字母、数字和连字符 (-) 字符。The ID can use only lowercase letters, numbers, and the hyphen (-) character. 它的长度必须介于 3 到 31 个字符之间。It must be between 3 and 31 characters in length.
    APIAPI Azure Cosmos DB 的用于 MongoDB 的 APIAzure Cosmos DB's API for MongoDB API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:适用于文档数据库的 Core (SQL)、适用于图形数据库的 Gremlin、适用于文档数据库的用于 Azure Cosmos DB 的 API MongoDB、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) for document databases, Gremlin for graph databases, Azure Cosmos DB's API MongoDB for document databases, Azure Table, and Cassandra. 目前,你必须为每种 API 创建单独的帐户。Currently, you must create a separate account for each API.

    选择“MongoDB”,因为本快速入门将创建使用 MongoDB 的表。Select MongoDB because in this quickstart you are creating a table that works with the MongoDB.
    位置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 的“新建帐户”页

  4. 创建帐户需要几分钟时间。The account creation takes a few minutes. 等待门户中显示“祝贺你!具有 MongoDB 的网络协议兼容性的 Cosmos 帐户已准备就绪”页面。Wait for the portal to display the Congratulations! Your Cosmos account with wire protocol compatibility for MongoDB 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 支持启用了 SSL 的连接。Azure Cosmos DB's API for MongoDB supports the SSL-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{})

没有 SSL 连接时,使用 mgo.Dial() 方法。The mgo.Dial() method is used when there is no SSL connection. 对于 SSL 连接,mgo.DialWithInfo() 方法是必需的。For an SSL 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

不再需要 Web 应用和 Azure Cosmos DB 帐户以后,即可删除创建的 Azure 资源,避免产生更多费用。When you're done with your web 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, select Resource groups on the far left. 如果左侧菜单处于折叠状态,请选择 “展开”按钮 将其展开。If the left menu is collapsed, select Expand button to expand it.

  2. 选择为本快速入门创建的资源组。Select the resource group you created for this quickstart.

    Azure 门户中的指标

  3. 在新窗口中选择“删除资源组”。In the new window, select Delete resource group.

    Azure 门户中的指标

  4. 在下一窗口中键入要删除的资源组的名称,然后选择“删除”。In the next window, type 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.