创建由 Azure Cosmos DB 触发的函数Create a function triggered by Azure Cosmos DB

了解如何创建在数据添加到 Azure Cosmos DB 或在其中更改数据时触发的函数。Learn how to create a function triggered when data is added to or changed in Azure Cosmos DB. 若要了解有关 Azure Cosmos DB 的详细信息,请参阅 Azure Cosmos DB:使用 Azure Functions 的无服务器数据库计算To learn more about Azure Cosmos DB, see Azure Cosmos DB: Serverless database computing using Azure Functions.

Azure Cosmos DB 代码

先决条件Prerequisites

完成本教程:To complete this tutorial:

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

备注

Azure Cosmos DB 绑定只能与 SQL API 配合使用。Azure Cosmos DB bindings are only supported for use with the SQL API. 对于所有其他的 Azure Cosmos DB API,应使用适用于 API 的静态客户端通过函数来访问数据库。API 包括 Azure Cosmos DB 的 API for MongoDB 和表 API。For all other Azure Cosmos DB APIs, you should access the database from your function by using the static client for your API, including Azure Cosmos DB's API for MongoDB, and Table API.

登录 AzureSign in to Azure

使用 Azure 帐户登录到 Azure 门户Sign in to the Azure portal with your Azure account.

创建 Azure Cosmos DB 帐户Create an Azure Cosmos DB account

在创建触发器之前,必须已拥有使用 SQL API 的 Azure Cosmos DB 帐户。You must have an Azure Cosmos DB account that uses the SQL API before you create the trigger.

  1. 在 Azure 门户菜单或主页中,选择“创建资源” 。From the Azure portal menu or the Home page, select Create a resource.

  2. 在“新建”页面中搜索“Azure Cosmos DB”,然后选择它。 On the New page, search for and select Azure Cosmos DB.

  3. 在“Azure Cosmos DB”页上,选择“创建”。On the Azure Cosmos DB page, select Create.

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

    设置Setting Value 说明Description
    订阅Subscription 订阅名称Subscription name 选择要用于此 Azure Cosmos 帐户的 Azure 订阅。Select the Azure subscription that you want to use for this Azure Cosmos account.
    资源组Resource Group 资源组名称Resource group name 选择一个资源组,或者选择“新建”,然后输入新资源组的唯一名称。Select a resource group, or select Create new, then enter a unique name for the new resource group.
    帐户名Account Name 唯一的名称A unique name 输入标识此 Azure Cosmos 帐户的名称。Enter a name to identify your Azure Cosmos account. 由于 documents.azure.cn 将追加到所提供的名称以创建 URI,因此,请使用唯一的名称**。Because documents.azure.cn is appended to the name that you provide to create your URI, use a unique name.

    名称只能包含小写字母、数字和连字符 (-)。The name can only contain lowercase letters, numbers, and the hyphen (-) character. 它的长度必须介于 3-44 个字符之间。It must be between 3-44 characters in length.
    APIAPI 要创建的帐户的类型The type of account to create 选择“Core (SQL)”,以便使用 SQL 语法创建文档数据库并进行查询。Select Core (SQL) to create a document database and query by using SQL syntax.

    API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:适用于文档数据的 Core (SQL) 和 MongoDB、适用于图形数据的 Gremlin、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) and MongoDB for document data, Gremlin for graph data, Azure Table, and Cassandra. 目前,你必须为每种 API 创建单独的帐户。Currently, you must create a separate account for each API.
    应用免费层折扣Apply Free Tier Discount 应用或不应用Apply or Do not apply 使用 Azure Cosmos DB 免费层,你将在帐户中获得每秒的前 400 RU 免费的吞吐量和 5 GB 的免费存储。With Azure Cosmos DB free tier, you will get the first 400 RU/s and 5 GB of storage for free in an account. 了解免费层的详细信息。Learn more about free tier.
    位置Location 离用户最近的区域The region closest to your users 选择用于托管 Azure Cosmos DB 帐户的地理位置。Select a geographic location to host your Azure Cosmos DB account. 使用离用户最近的位置,使他们能够以最快的速度访问数据。Use the location that is closest to your users to give them the fastest access to the data.
    帐户类型Account Type 生产或非生产Production or Non-Production 如果帐户将用于生产工作负荷,请选择“生产”。Select Production if the account will be used for a production workload. 如果帐户将用于非生产环境(例如开发、测试、QA 或过渡),请选择“非生产”。Select Non-Production if the account will be used for non-production, e.g. development, testing, QA, or staging. 这是一个 Azure 资源标记设置,用于调整门户体验,但不会影响基础 Azure Cosmos DB 帐户。This is an Azure resource tag setting that tunes the Portal experience but does not affect the underlying Azure Cosmos DB account. 可以随时更改此值。You can change this value anytime.

    备注

    每个 Azure 订阅最多可以有一个免费层 Azure Cosmos DB 帐户,并且你必须在创建帐户时选择加入使用。You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. 如果看不到用于应用免费层折扣的选项,这意味着订阅中的另一个帐户已启用免费层。If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.

    Azure Cosmos DB 的“新建帐户”页面

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

  6. 检查帐户设置,然后选择“创建”。Review the account settings, and then select Create. 创建帐户需要几分钟时间。It takes a few minutes to create the account. 等待门户页显示“你的部署已完成”消息。Wait for the portal page to display Your deployment is complete.

    Azure 门户“通知”窗格

  7. 选择“转到资源”,转到 Azure Cosmos DB 帐户页。Select Go to resource to go to the Azure Cosmos DB account page.

    Azure Cosmos DB 帐户页面

创建 Azure Function AppCreate an Azure Function app

  1. 在 Azure 门户菜单或“主页”页中,选择“创建资源” 。From the Azure portal menu or the Home page, select Create a resource.

  2. “新建” 页面,选择 “计算” > “函数应用”In the New page, select Compute > Function App.

  3. 在“基本信息”页上,使用下表中指定的函数应用设置。On the Basics page, use the function app settings as specified in the following table.

    设置Setting 建议的值Suggested value 说明Description
    订阅Subscription 你的订阅Your subscription 要在其下创建此新函数应用的订阅。The subscription under which this new function app is created.
    资源组Resource Group myResourceGroupmyResourceGroup 要在其中创建 Function App 的新资源组的名称。Name for the new resource group in which to create your function app.
    函数应用名称Function App name 全局唯一名称Globally unique name 用于标识新 Function App 的名称。Name that identifies your new function app. 有效字符为 a-z(不区分大小写)、0-9-Valid characters are a-z (case insensitive), 0-9, and -.
    Publish 代码Code 用于发布代码文件或 Docker 容器的选项。Option to publish code files or a Docker container.
    运行时堆栈Runtime stack 首选语言Preferred language 选择支持你喜欢的函数编程语言的运行时。Choose a runtime that supports your favorite function programming language. 对于 C# 和 F# 函数,选择 .NET CoreChoose .NET Core for C# and F# functions.
    版本Version 版本号Version number 选择已安装的运行时的版本。Choose the version of your installed runtime.
    区域Region 首选区域Preferred region 选择离你近或离函数访问的其他服务近的区域Choose a region near you or near other services your functions access.

    基础知识

  4. 选择“下一步: 托管”。Select Next : Hosting. 在“托管” 页上,输入以下设置。On the Hosting page, enter the following settings.

    设置Setting 建议的值Suggested value 说明Description
    存储帐户Storage account 全局唯一名称Globally unique name 创建函数应用使用的存储帐户。Create a storage account used by your function app. 存储帐户名称必须为 3 到 24 个字符,并且只能包含数字和小写字母。Storage account names must be between 3 and 24 characters in length and can contain numbers and lowercase letters only. 也可使用现有帐户,但该帐户必须符合存储帐户要求You can also use an existing account, which must meet the storage account requirements.
    操作系统Operating system 首选操作系统Preferred operating system 系统会根据你的运行时堆栈选择为你预先选择一个操作系统,但你可以根据需要更改该设置。An operating system is pre-selected for you based on your runtime stack selection, but you can change the setting if necessary.
    计划Plan 消耗(无服务器)Consumption (Serverless) 定义如何将资源分配给 Function App 的托管计划。Hosting plan that defines how resources are allocated to your function app. 在默认的消耗计划中,根据函数需求动态添加资源。In the default Consumption plan, resources are added dynamically as required by your functions. 在此无服务器托管中,只需为函数运行时间付费。In this serverless hosting, you pay only for the time your functions run. 按应用服务计划运行时,必须管理函数应用的缩放When you run in an App Service plan, you must manage the scaling of your function app.

    Hosting

  5. 选择“下一步: 监视”。Select Next : Monitoring. 在“监视” 页上,输入以下设置。On the Monitoring page, enter the following settings.

    设置Setting 建议的值Suggested value 说明Description
    Application InsightsApplication Insights 默认Default 当前不受支持Not supported currently

    监视

  6. 选择“查看 + 创建”,以便查看应用配置选择。Select Review + create to review the app configuration selections.

  7. 在“查看 + 创建”页上查看设置,然后选择“创建”来预配并部署函数应用 。On the Review + create page, review your settings, and then select Create to provision and deploy the function app.

  8. 选择门户右上角的“通知”图标,留意是否显示了“部署成功”消息。 Select the Notifications icon in the upper-right corner of the portal and watch for the Deployment succeeded message.

  9. 选择“转到资源”,查看新的函数应用。Select Go to resource to view your new function app. 还可选择“固定到仪表板”。You can also select Pin to dashboard. 固定可以更轻松地从仪表板返回此函数应用资源。Pinning makes it easier to return to this function app resource from your dashboard.

    部署通知

接下来,在新的 Function App 中创建一个函数。Next, you create a function in the new function app.

创建 Azure Cosmos DB 触发器Create Azure Cosmos DB trigger

  1. 在函数应用中,从左菜单中选择“函数”,然后从顶部菜单中选择“添加” 。In your function app, select Functions from the left menu, and then select Add from the top menu.

  2. 在“新函数”页面上,在搜索字段中输入 cosmos,然后选择“Azure Cosmos DB 触发器”模板 。On the New Function page, enter cosmos in the search field and then choose the Azure Cosmos DB trigger template.

    Azure 门户中的 Functions 页

  3. 使用下表中指定的设置配置新触发器:Configure the new trigger with the settings as specified in the following table:

    设置Setting 建议的值Suggested value 说明Description
    新建函数New Function 接受默认名称Accept the default name 函数的名称。The name of the function.
    Cosmos DB 帐户连接Cosmos DB account connection 接受默认新名称Accept the default new name 选择“新建”,选择之前创建的“数据库帐户”,然后选择“确定” 。Select New, the Database Account you created earlier, and then OK. 此操作将为帐户连接创建应用程序设置。This action creates an application setting for your account connection. 此设置由数据库连接的绑定使用。This setting is used by the binding to connection to the database.
    数据库名称Database name 任务Tasks 包含要监视的集合的数据库的名称。Name of the database that includes the collection to be monitored.
    集合名称Collection name ItemsItems 要监视的集合的名称。Name of the collection to be monitored.
    租用的集合名称Collection name for leases 租约leases 要存储租用的集合的名称。Name of the collection to store the leases.
    如果不存在,创建租用集合Create lease collection if it does not exist Yes 检查是否存在并自动创建租用集合。Checks for existence of the lease collection and automatically creates it.

    创建 Azure Cosmos DB 触发函数

  4. 选择“创建函数”。Select Create Function.

    Azure 会创建该 Cosmos DB 触发器函数。Azure creates the Cosmos DB trigger function.

  5. 若要显示基于模板的函数代码,请选择“代码 + 测试”。To display the template-based function code, select Code + Test.

    运用 C# 语言的 Cosmos DB 函数模板

    此函数模板将文档的数量和第一个文档 ID 写入到日志中。This function template writes the number of documents and the first document ID to the logs.

接下来,连接到 Azure Cosmos DB 帐户并在 Tasks 数据库中创建 Items 容器。Next, you connect to your Azure Cosmos DB account and create the Items container in the Tasks database.

创建 Items 容器Create the Items container

  1. 在浏览器的新选项卡中打开 Azure 门户的第二个实例。Open a second instance of the Azure portal in a new tab in the browser.

  2. 在门户左侧展开图标栏,在搜索字段中键入 cosmos,然后选择“Azure Cosmos DB”。On the left side of the portal, expand the icon bar, type cosmos in the search field, and select Azure Cosmos DB.

    搜索 Azure Cosmos DB 服务

  3. 选择你的 Azure Cosmos DB 帐户,然后选择“数据资源管理器”。Choose your Azure Cosmos DB account, then select the Data Explorer.

  4. 在“SQL API” 下,选择“Tasks” 数据库,然后选择“新建容器”。Under SQL API, choose Tasks database and select New Container.

    创建容器

  5. 在“添加容器” 中,使用图像下的表中所示的设置。In Add Container, use the settings shown in the table below the image.

    定义 Tasks 容器

    设置Setting 建议的值Suggested value 说明Description
    数据库 IDDatabase ID 任务Tasks 新数据库的名称。The name for your new database. 它必须匹配函数绑定中定义的名称。This must match the name defined in your function binding.
    容器 IDContainer ID ItemsItems 新容器的名称。The name for the new container. 它必须匹配函数绑定中定义的名称。This must match the name defined in your function binding.
    分区键Partition key /category/category 一个分区键,用于将数据均匀分配到每个分区。A partition key that distributes data evenly to each partition. 选择正确的分区键对于创建高性能容器而言很重要。Selecting the correct partition key is important in creating a performant container.
    吞吐量Throughput 400 RU400 RU 使用默认值。Use the default value. 如果想要减少延迟,以后可以增加吞吐量。If you want to reduce latency, you can scale up the throughput later.
  6. 单击“确定” 创建 Items 容器。Click OK to create the Items container. 创建该容器可能需要少许时间。It may take a short time for the container to get created.

函数绑定中指定的容器存在后,可以通过将项添加到此新容器来测试函数。After the container specified in the function binding exists, you can test the function by adding items to this new container.

测试函数Test the function

  1. 展开数据资源管理器中的新 Items 容器,选择“项”,然后选择“新建项”。Expand the new Items container in Data Explorer, choose Items, then select New Item.

    在 Items 容器中创建项

  2. 将新项的内容替换为以下内容,然后选择“保存”。Replace the contents of the new item with the following content, then choose Save.

     {
         "id": "task1",
         "category": "general",
         "description": "some task"
     }
    
  3. 切换到包含门户中的函数的第一个浏览器选项卡。Switch to the first browser tab that contains your function in the portal. 展开函数日志并验证新的文档已触发该函数。Expand the function logs and verify that the new document has triggered the function. 会看到 task1 文档 ID 值已写入到日志。See that the task1 document ID value is written to the logs.

    查看日志中的消息。

  4. (可选)返回到文档进行更改,然后单击“更新”。(Optional) Go back to your document, make a change, and click Update. 然后,回到函数日志,并验证此更新同样已触发该函数。Then, go back to the function logs and verify that the update has also triggered the function.

清理资源Clean up resources

本教程系列中的其他快速入门教程是在本文的基础上制作的。Other quickstarts in this collection build upon this quickstart. 如果打算使用后续的快速入门、教程或者在本快速入门中创建的任何服务,请勿清理这些资源。If you plan to work with subsequent quickstarts, tutorials, or with any of the services you have created in this quickstart, do not clean up the resources.

Azure 中的资源是指函数应用、函数、存储帐户等。Resources in Azure refer to function apps, functions, storage accounts, and so forth. 这些资源可以组合到资源组 中,删除该组即可删除组中的所有内容。They're grouped into resource groups, and you can delete everything in a group by deleting the group.

已创建完成这些快速入门所需的资源。You created resources to complete these quickstarts. 这些资源可能需要付费,具体取决于帐户状态服务定价You may be billed for these resources, depending on your account status and service pricing. 如果不再需要这些资源,请参阅下面介绍的资源删除方法:If you don't need the resources anymore, here's how to delete them:

  1. 在 Azure 门户中转到“资源组”页。 In the Azure portal, go to the Resource group page.

    若要从函数应用页转到该页,请选择“概览”选项卡,然后选择“资源组”下的链接。 To get to that page from the function app page, select the Overview tab and then select the link under Resource group.

    从函数应用页选择要删除的资源组。

    若要从仪表板转到该页,请选择“资源组”,然后选择用于本快速入门的资源组。 To get to that page from the dashboard, select Resource groups, and then select the resource group that you used for this quickstart.

  2. 在“资源组”页中查看所包括的资源的列表,然后验证这些资源是否是要删除的。 In the Resource group page, review the list of included resources, and verify that they're the ones you want to delete.

  3. 选择“删除资源组” ,然后按说明操作。Select Delete resource group, and follow the instructions.

    可能需要数分钟才能删除完毕。Deletion may take a couple of minutes. 完成后会显示一个通知,持续数秒。When it's done, a notification appears for a few seconds. 也可以选择页面顶部的钟形图标来查看通知。You can also select the bell icon at the top of the page to view the notification.

后续步骤Next steps

你已经创建一个函数,当在 Azure Cosmos DB 中添加或修改文档时会运行此函数。You have created a function that runs when a document is added or modified in your Azure Cosmos DB. 有关 Azure Cosmos DB 触发器的详细信息,请参阅适用于 Azure Functions 的 Azure Cosmos DB 绑定For more information about Azure Cosmos DB triggers, see Azure Cosmos DB bindings for Azure Functions.

现在,你已创建了第一个函数,让我们向该函数添加输出绑定,以便将消息写入存储队列。Now that you've created your first function, let's add an output binding to the function that writes a message to a Storage queue.