您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

创建与 Azure 逻辑应用集成的函数Create a function that integrates with Azure Logic Apps

Azure Functions 在逻辑应用设计器中与 Azure 逻辑应用集成。Azure Functions integrates with Azure Logic Apps in the Logic Apps Designer. 借助这种集成,可以利用 Functions 的计算能力来与其他 Azure 服务和第三方服务进行协调。This integration lets you use the computing power of Functions in orchestrations with other Azure and third-party services.

本教程介绍如何在 Azure 上使用 Functions、逻辑应用和认知服务对 Twitter 文章中的情感进行分析。This tutorial shows you how to use Functions with Logic Apps and Cognitive Services on Azure to run sentiment analysis from Twitter posts. HTTP 触发的函数根据情感评分将推文分类为绿色、黄色或红色。An HTTP triggered function categorizes tweets as green, yellow, or red based on the sentiment score. 检测到较差的情感时,会发送一封电子邮件。An email is sent when poor sentiment is detected.

逻辑应用设计器中应用的前两个步骤的示意图

本教程介绍如何执行下列操作:In this tutorial, you learn how to:

  • 创建认知服务 API 资源。Create a Cognitive Services API Resource.
  • 创建一个用来对推文情感进行分类的函数。Create a function that categorizes tweet sentiment.
  • 创建连接到 Twitter 的逻辑应用。Create a logic app that connects to Twitter.
  • 将情感检测功能添加到逻辑应用。Add sentiment detection to the logic app.
  • 将逻辑应用连接到函数。Connect the logic app to the function.
  • 根据函数的响应发送电子邮件。Send an email based on the response from the function.

先决条件Prerequisites

创建认知服务资源Create a Cognitive Services resource

Azure 中以单个资源的形式提供了认知服务 API。The Cognitive Services APIs are available in Azure as individual resources. 使用文本分析 API 可检测受监视的推文观点。Use the Text Analytics API to detect the sentiment of the tweets being monitored.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 在 Azure 门户的左上角单击“创建资源”。 Click Create a resource in the upper left-hand corner of the Azure portal.

  3. 单击“AI + 机器学习” > “文本分析”。Click AI + Machine Learning > Text Analytics. 然后,使用表中指定的设置来创建资源。Then, use the settings as specified in the table to create the resource.

    创建认知资源页

    设置Setting 建议的值Suggested value 说明Description
    名称Name MyCognitiveServicesAccntMyCognitiveServicesAccnt 选择唯一的帐户名称。Choose a unique account name.
    位置Location 美国西部West US 使用最靠近的位置。Use the location nearest you.
    定价层Pricing tier F0F0 从最低的层着手。Start with the lowest tier. 如果已用完调用配额,请扩展到更高的层。If you run out of calls, scale to a higher tier.
    资源组Resource group myResourceGroupmyResourceGroup 请本教程中的所有服务使用同一个资源组。Use the same resource group for all services in this tutorial.
  4. 单击“创建”以创建资源。 Click Create to create your resource.

  5. 单击“概览” ,将终结点的值复制到文本编辑器。Click on Overview and copy the value of the Endpoint to a text editor. 创建到认知服务 API 的连接时使用此值。This value is used when creating a connection to the Cognitive Services API.

    认知服务设置

  6. 在左侧导航栏中单击“密钥”,复制“密钥 1”的值并将其留存在文本编辑器中。 In the left navigation column, click Keys, and then copy the value of Key 1 and set it aside in a text editor. 使用此密钥将逻辑应用连接到认知服务 API。You use the key to connect the logic app to your Cognitive Services API.

    认知服务密钥

创建函数应用Create the function app

函数可让你方便地卸载逻辑应用工作流中的处理任务。Functions provides a great way to offload processing tasks in a logic apps workflow. 本教程使用 HTTP 触发的函数来处理认知服务提供的推文情感评分,并返回一个类别值。This tutorial uses an HTTP triggered function to process tweet sentiment scores from Cognitive Services and return a category value.

  1. 选择 Azure 门户左上角的“创建资源”按钮,然后选择“计算” > “函数应用”。 Select the Create a resource button found on the upper left-hand corner of the Azure portal, then select Compute > Function App.

    在 Azure 门户中创建函数应用

  2. 使用图像下面的表格中指定的函数应用设置。Use the function app settings as specified in the table below the image.

    定义新的函数应用设置

    设置Setting 建议的值Suggested value 说明Description
    应用名称App name 全局唯一名称Globally unique name 用于标识新 Function App 的名称。Name that identifies your new function app. 有效的字符是 a-z0-9-Valid characters are a-z, 0-9, and -.
    订阅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.
    OSOS WindowsWindows Linux 上的无服务器托管目前为预览版。Serverless hosting on Linux is currently in preview. 有关详细信息,请参阅此注意事项文章For more information, see this considerations article.
    托管计划Hosting plan 消耗量计划Consumption plan 定义如何将资源分配给 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 only pay for the time your functions run. 按应用服务计划运行时,必须管理函数应用的缩放When you run in an App Service plan, you must manage the scaling of your function app.
    位置Location 西欧West Europe 选择离你近或离函数访问的其他服务近的区域Choose a region near you or near other services your functions access.
    运行时堆栈Runtime stack 首选语言Preferred language 选择支持你喜欢的函数编程语言的运行时。Choose a runtime that supports your favorite function programming language. 对于 C# 和 F# 函数,选择 .NETChoose .NET for C# and F# functions.
    存储Storage 全局唯一名称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 may contain numbers and lowercase letters only. 也可使用现有帐户,但该帐户必须符合存储帐户要求You can also use an existing account, which must meets the storage account requirements.
    Application InsightsApplication Insights 默认Default 在最近的受支持的区域中,创建一个具有相同应用名称 的 Application Insights 资源。Creates an Application Insights resource of the same App name in the nearest supported region. 展开此设置即可更改“新建资源名称”,或者在 Azure 地理位置中选择另一个需要在其中存储数据的位置By expanding this setting, you can change the New resource name or choose a different Location in an Azure geography where you want to store your data.
  3. 选择“创建” 以预配和部署函数应用。Select Create to provision and deploy the function app.

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

    定义新的函数应用设置

  5. 选择“转到资源” ,查看新的函数应用。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.

创建 HTTP 触发的函数Create an HTTP triggered function

  1. 展开 Function App,单击“Functions”旁边的 + 按钮 。Expand your function app and click the + button next to Functions. 如果这是函数应用中的第一个函数,请选择“门户中” 。If this is the first function in your function app, select In-portal.

    Azure 门户中的 Functions 快速入门页

  2. 接下来选择“WebHook + API” ,然后单击“创建” 。Next, select Webhook + API and click Create.

    选择 HTTP 触发器

  3. run.csx 文件的内容替换为以下代码,然后单击“保存” :Replace the contents of the run.csx file with the following code, then click Save:

    #r "Newtonsoft.Json"
    
    using System;
    using System.Net;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Primitives;
    using Newtonsoft.Json;
    
    public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
    {
        string category = "GREEN";
    
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        log.LogInformation(string.Format("The sentiment score received is '{0}'.", requestBody));
    
        double score = Convert.ToDouble(requestBody);
    
        if(score < .3)
        {
            category = "RED";
        }
        else if (score < .6) 
        {
            category = "YELLOW";
        }
    
        return requestBody != null
            ? (ActionResult)new OkObjectResult(category)
            : new BadRequestObjectResult("Please pass a value on the query string or in the request body");
    }
    

    此函数代码基于请求中收到的情感评分返回颜色类别。This function code returns a color category based on the sentiment score received in the request.

  4. 若要测试该函数,请单击最右边的“测试”展开“测试”选项卡。 在“请求正文”中键入 0.2 的值,并单击“运行”。 To test the function, click Test at the far right to expand the Test tab. Type a value of 0.2 for the Request body, and then click Run. 响应正文中将返回 RED 值。A value of RED is returned in the body of the response.

    在 Azure 门户中测试函数

现已创建一个可对情感评分分类的函数。Now you have a function that categorizes sentiment scores. 接下来,请创建用于将函数与 Twitter 和认知服务 API 集成的逻辑应用。Next, you create a logic app that integrates your function with your Twitter and Cognitive Services API.

创建逻辑应用Create a logic app

  1. 在 Azure 门户中,单击左上角的“新建”按钮。 In the Azure portal, click the New button found on the upper left-hand corner of the Azure portal.

  2. 单击“Web” > “逻辑应用”。Click Web > Logic App.

  3. 然后,键入一个值(例如 TweetSentiment)作为名称,并使用表中指定的设置。Then, type a value for Name like TweetSentiment, and use the settings as specified in the table.

    在 Azure 门户创建逻辑应用

    设置Setting 建议的值Suggested value 说明Description
    名称Name TweetSentimentTweetSentiment 选择适当的应用名称。Choose an appropriate name for your app.
    资源组Resource group myResourceGroupmyResourceGroup 选择与前面相同的现有资源组。Choose the same existing resource group as before.
    位置Location 美国东部East US 选择靠近你的位置。Choose a location close to you.
  4. 输入适当的设置值以后,请单击“创建”以创建逻辑应用。 Once you have entered the proper settings values, click Create to create your logic app.

  5. 创建应用后,请单击已固定到仪表板的新逻辑应用。After the app is created, click your new logic app pinned to the dashboard. 然后,在逻辑应用设计器中向下滚动并单击“空白逻辑应用” 模板。Then in the Logic Apps Designer, scroll down and click the Blank Logic App template.

    “空白逻辑应用”模板

现在,可以使用逻辑应用设计器将服务和触发器添加到应用。You can now use the Logic Apps Designer to add services and triggers to your app.

连接到 TwitterConnect to Twitter

首先,请与 Twitter 帐户建立连接。First, create a connection to your Twitter account. 逻辑应用将轮询推文,这会触发应用运行。The logic app polls for tweets, which trigger the app to run.

  1. 在设计器中单击“Twitter”服务,并单击“发布新推文时”触发器。 In the designer, click the Twitter service, and click the When a new tweet is posted trigger. 登录到 Twitter 帐户,并授权逻辑应用使用你的帐户。Sign in to your Twitter account and authorize Logic Apps to use your account.

  2. 使用表中指定的 Twitter 触发器设置。Use the Twitter trigger settings as specified in the table.

    Twitter 连接器设置

    设置Setting 建议的值Suggested value 说明Description
    搜索文本Search text #Azure#Azure 使用足够热门的井号标签按所选的间隔生成新的推文。Use a hashtag that is popular enough to generate new tweets in the chosen interval. 如果使用免费层并且井号标签过于热门,可能很快就会用完认知服务 API 中的事务配额。When using the Free tier and your hashtag is too popular, you can quickly use up the transaction quota in your Cognitive Services API.
    间隔 Interval 1515 每两次处理 Twitter 请求所用的时间,采用频率单位。The time elapsed between Twitter requests, in frequency units.
    频率Frequency 分钟Minute 用于轮询 Twitter 的频率单位。The frequency unit used for polling Twitter.
  3. 单击“保存”连接到 Twitter 帐户。 Click Save to connect to your Twitter account.

应用现已连接到 Twitter。Now your app is connected to Twitter. 接下来,请连接到文本分析以检测收集到的推文的情感。Next, you connect to text analytics to detect the sentiment of collected tweets.

添加情感检测Add sentiment detection

  1. 单击“新建步骤”,并单击“添加操作”。 Click New Step, and then Add an action.

  2. 在“选择操作”中键入“文本分析”,然后单击“检测情感”操作。 In Choose an action, type Text Analytics, and then click the Detect sentiment action.

    选择“新建步骤”,并选择“添加操作”

  3. 键入连接名称(例如 MyCognitiveServicesConnection),粘贴在文本编辑器中留存的认知服务 API 和认知服务终结点的密钥,然后单击“创建”。 Type a connection name such as MyCognitiveServicesConnection, paste the key for your Cognitive Services API and the Cognitive Services endpoint you set aside in a text editor, and click Create.

    选择“新建步骤”,并选择“添加操作”

  4. 接下来在文本框中输入“推文文本”,然后单击“新建步骤”。 Next, enter Tweet Text in the text box and then click on New Step.

    定义要分析的文本

配置情感检测后,可将一个连接添加到使用情感评分输出的函数。Now that sentiment detection is configured, you can add a connection to your function that consumes the sentiment score output.

将情感输出连接到函数Connect sentiment output to your function

  1. 在逻辑应用设计器中单击“新建步骤” > “添加操作”,在 Azure Functions 上进行筛选,然后单击“选择一个 Azure 函数”。 In the Logic Apps Designer, click New step > Add an action, filter on Azure Functions and click Choose an Azure function.

    检测情感

  2. 选择前面创建的函数应用。Select the function app you created earlier.

    选择函数

  3. 选择为本教程创建的函数。Select the function you created for this tutorial.

    选择函数

  4. 在“请求正文”中单击“评分”,并单击“保存”。 In Request Body, click Score and then Save.

    Score

现在,在从逻辑应用发送情感评分时,将触发该函数。Now, your function is triggered when a sentiment score is sent from the logic app. 该函数会将一个带有颜色编码的类别返回到逻辑应用。A color-coded category is returned to the logic app by the function. 接下来,请添加当函数返回 RED 情感值时要发送的电子邮件通知。Next, you add an email notification that is sent when a sentiment value of RED is returned from the function.

添加电子邮件通知Add email notifications

工作流的最后一部分是当情感评分为 RED 时触发电子邮件。The last part of the workflow is to trigger an email when the sentiment is scored as RED. 本主题使用 Outlook.com 连接器。This topic uses an Outlook.com connector. 可以执行类似的步骤来使用 Gmail 或 Office 365 Outlook 连接器。You can perform similar steps to use a Gmail or Office 365 Outlook connector.

  1. 在逻辑应用设计器中,单击“新建步骤” > “添加条件”。 In the Logic Apps Designer, click New step > Add a condition.

    将条件添加到逻辑应用。

  2. 单击“选择值”,并单击“正文”。 Click Choose a value, then click Body. 选择“等于” ,单击“选择值” 并键入 RED,然后单击“保存” 。Select is equal to, click Choose a value and type RED, and click Save.

    为条件选择操作。

  3. 在“如果是”中单击“添加操作”,搜索 outlook.com,单击“发送电子邮件”,并登录到 Outlook.com 帐户。 In IF TRUE, click Add an action, search for outlook.com, click Send an email, and sign in to your Outlook.com account.

    为“发送电子邮件”操作配置电子邮件。

    备注

    如果没有 Outlook.com 帐户,可以选择另一个连接器,例如 Gmail 或 Office 365 OutlookIf you don't have an Outlook.com account, you can choose another connector, such as Gmail or Office 365 Outlook

  4. 在“发送电子邮件”操作中,请使用表中指定的电子邮件设置。 In the Send an email action, use the email settings as specified in the table.

    为“发送电子邮件”操作配置电子邮件。

设置Setting 建议的值Suggested value 说明Description
收件人To 键入电子邮件地址Type your email address 接收通知的电子邮件地址。The email address that receives the notification.
主题Subject 检测到消极的推文情感Negative tweet sentiment detected 电子邮件通知的主题行。The subject line of the email notification.
正文Body 推文文本、位置Tweet text, Location 单击“推文文本”和“位置”参数。 Click the Tweet text and Location parameters.
  1. 单击“ 保存”。Click Save.

完成工作流后,可以启用逻辑应用并查看函数的工作状态。Now that the workflow is complete, you can enable the logic app and see the function at work.

测试工作流Test the workflow

  1. 在逻辑应用设计器中,单击“运行”启动应用。 In the Logic App Designer, click Run to start the app.

  2. 在左列中,单击“概述”查看逻辑应用的状态。 In the left column, click Overview to see the status of the logic app.

    逻辑应用执行状态

  3. (可选)单击某个运行查看执行详细信息。(Optional) Click one of the runs to see details of the execution.

  4. 转到函数,查看日志,并验证是否已收到并处理情绪值。Go to your function, view the logs, and verify that sentiment values were received and processed.

    查看函数日志

  5. 检测到潜在的消极情感时,将收到一封电子邮件。When a potentially negative sentiment is detected, you receive an email. 如果未收到电子邮件,可以更改函数代码,以便每次都返回 RED:If you haven't received an email, you can change the function code to return RED every time:

    return (ActionResult)new OkObjectResult("RED");
    

    验证电子邮件通知后,请改回原始代码:After you have verified email notifications, change back to the original code:

    return requestBody != null
        ? (ActionResult)new OkObjectResult(category)
        : new BadRequestObjectResult("Please pass a value on the query string or in the request body");
    

    重要

    完成本教程后,应禁用该逻辑应用。After you have completed this tutorial, you should disable the logic app. 禁用该应用可以避免产生执行费用,以及用完认知服务 API 中的事务配额。By disabling the app, you avoid being charged for executions and using up the transactions in your Cognitive Services API.

我们已看到,将 Functions 集成到逻辑应用工作流的过程是多么简单。Now you have seen how easy it is to integrate Functions into a Logic Apps workflow.

禁用逻辑应用Disable the logic app

要禁用逻辑应用,请单击“概述”,并单击屏幕顶部的“禁用”。 To disable the logic app, click Overview and then click Disable at the top of the screen. 禁用应用会停止应用的运行并避免产生费用,同时又不必删除该应用。Disabling the app stops it from running and incurring charges without deleting the app.

函数日志

后续步骤Next steps

本教程介绍了如何:In this tutorial, you learned how to:

  • 创建认知服务 API 资源。Create a Cognitive Services API Resource.
  • 创建一个用来对推文情感进行分类的函数。Create a function that categorizes tweet sentiment.
  • 创建连接到 Twitter 的逻辑应用。Create a logic app that connects to Twitter.
  • 将情感检测功能添加到逻辑应用。Add sentiment detection to the logic app.
  • 将逻辑应用连接到函数。Connect the logic app to the function.
  • 根据函数的响应发送电子邮件。Send an email based on the response from the function.

请继续学习下一教程,了解如何为函数创建无服务器 API。Advance to the next tutorial to learn how to create a serverless API for your function.

若要详细了解逻辑应用,请参阅 Azure 逻辑应用To learn more about Logic Apps, see Azure Logic Apps.