用于事件驱动的后台处理的 Azure WebJobs SDK 入门Get started with the Azure WebJobs SDK for event-driven background processing

本文介绍如何使用 Visual Studio 2019 创建 Azure WebJobs SDK 项目、在本地运行它,然后将其部署到 Azure 应用服务This article shows how to use Visual Studio 2019 to create an Azure WebJobs SDK project, run it locally, and then deploy it to Azure App Service. WebJobs SDK 的 3.x 版同时支持 .NET Core 和 .NET Framework 控制台应用。Version 3.x of the WebJobs SDK supports both .NET Core and .NET Framework console apps. 若要了解关于使用 WebJobs SDK 的详细信息,请参阅如何将 Azure WebJobs SDK 用于处理事件驱动的后台To learn more about working with the WebJobs SDK, see How to use the Azure WebJobs SDK for event-driven background processing.

本文介绍如何将 WebJobs 部署为 .NET Core 控制台应用。This article shows you how to deploy WebJobs as a .NET Core console app. 若要将 WebJobs 部署为 .NET Framework 控制台应用,请参阅 WebJobs 作为 .NET Framework 控制台应用To deploy WebJobs as a .NET Framework console app, see WebJobs as .NET Framework console apps. 如果你对仅支持 .NET Framework 的 WebJobs SDK 版本 2.x 感兴趣,请参阅使用 Visual Studio 开发和部署 WebJob - Azure 应用服务If you are interested in WebJobs SDK version 2.x, which only supports .NET Framework, see Develop and deploy WebJobs using Visual Studio - Azure App Service.

先决条件Prerequisites

  • 安装 Visual Studio 2019其中包含 Azure 开发工作负荷。Install Visual Studio 2019 with the Azure development workload. 如果已安装 Visual Studio,但未配置该工作负荷,请选择“工具”>“获取工具和功能”添加该工作负荷。If you already have Visual Studio but don't have that workload, add the workload by selecting Tools > Get Tools and Features .

  • 必须有一个 Azure 帐户才能将 WebJobs SDK 项目发布到 Azure。You must have an Azure account to publish your WebJobs SDK project to Azure.

创建一个项目Create a project

  1. 在 Visual Studio 中,选择“新建项目”。In Visual Studio, select Create a New Project .

  2. 选择“控制台应用(.NET Core)”。Select Console App (.NET Core) .

  3. 将项目命名为 WebJobsSDKSample ,然后选择“创建”。Name the project WebJobsSDKSample , and then select Create .

    “新建项目”对话框

WebJobs NuGet 包WebJobs NuGet packages

  1. 安装 Microsoft.Azure.WebJobs.Extensions NuGet 包的最新稳定版本 3.x,其中包括 Microsoft.Azure.WebJobsInstall the latest stable 3.x version of the Microsoft.Azure.WebJobs.Extensions NuGet package, which includes Microsoft.Azure.WebJobs.

    下面是包管理器控制台命令:Here's the Package Manager Console command:

    Install-Package Microsoft.Azure.WebJobs.Extensions -version <3_X_VERSION>
    

    在此命令中,将 <3_X_VERSION> 替换为包的受支持版本。In this command, replace <3_X_VERSION> with a supported version of the package.

创建主机Create the Host

主机是函数的运行时容器,它侦听触发器并调用函数。The host is the runtime container for functions that listens for triggers and calls functions. 以下步骤创建一个实现 IHost 的主机,它是 ASP.NET Core 中的通用主机。The following steps create a host that implements IHost, which is the Generic Host in ASP.NET Core.

  1. 在 Program.cs 中,添加以下 using 语句:In Program.cs , add these using statements:

    using System.Threading.Tasks;
    using Microsoft.Extensions.Hosting;
    
  2. Main 方法替换为以下代码:Replace the Main method with the following code:

    static async Task Main()
    {
        var builder = new HostBuilder();
        builder.ConfigureWebJobs(b =>
                {
                    b.AddAzureStorageCoreServices();
                });
        var host = builder.Build();
        using (host)
        {
            await host.RunAsync();
        }
    }
    

在 ASP.NET Core 中,通过调用 HostBuilder 实例上的方法来设置主机配置。In ASP.NET Core, host configurations are set by calling methods on the HostBuilder instance. 有关详细信息,请参阅 .NET 通用主机For more information, see .NET Generic Host. ConfigureWebJobs 扩展方法初始化 WebJobs 主机。The ConfigureWebJobs extension method initializes the WebJobs host. ConfigureWebJobs 中,初始化特定的 WebJobs 扩展并设置这些扩展的属性。In ConfigureWebJobs, you initialize specific WebJobs extensions and set properties of those extensions.

启用控制台日志记录Enable console logging

本部分介绍如何设置使用 ASP.NET Core 记录框架的控制台日志记录。In this section, you set up console logging that uses the ASP.NET Core logging framework.

  1. 安装 Microsoft.Extensions.Logging.Console NuGet 包的最新稳定版本,其中包括 Microsoft.Extensions.LoggingInstall the latest stable version of the Microsoft.Extensions.Logging.Console NuGet package, which includes Microsoft.Extensions.Logging.

    下面是“包管理器控制台”命令:Here's the Package Manager Console command:

    Install-Package Microsoft.Extensions.Logging.Console -version <3_X_VERSION>
    

    在此命令中,将 <3_X_VERSION> 替换为包的受支持的 3.x 版本。In this command, replace <3_X_VERSION> with a supported 3.x version of the package.

  2. Program.cs 中,添加 using 语句:In Program.cs , add a using statement:

    using Microsoft.Extensions.Logging;
    
  3. HostBuilder 上调用 ConfigureLogging 方法。Call the ConfigureLogging method on HostBuilder. AddConsole 方法将控制台日志记录添加到配置中。The AddConsole method adds console logging to the configuration.

    builder.ConfigureLogging((context, b) =>
    {
        b.AddConsole();
    });
    

    现在,Main 方法如下所示:The Main method now looks like this:

    static async Task Main()
    {
        var builder = new HostBuilder();
        builder.ConfigureWebJobs(b =>
                {
                    b.AddAzureStorageCoreServices();
                });
        builder.ConfigureLogging((context, b) =>
                {
                    b.AddConsole();
                });
        var host = builder.Build();
        using (host)
        {
            await host.RunAsync();
        }
    }
    

    此项更新执行以下操作:This update does the following:

    • 禁用仪表板日志记录Disables dashboard logging. 仪表板是一个旧式监视工具,不建议对高吞吐量生产方案使用仪表板日志记录。The dashboard is a legacy monitoring tool, and dashboard logging is not recommended for high-throughput production scenarios.
    • 使用默认筛选添加控制台提供程序。Adds the console provider with default filtering.

现在即可添加由到达 Azure 存储队列的消息触发的函数。Now, you can add a function that is triggered by messages arriving in an Azure Storage queue.

安装存储绑定扩展Install the Storage binding extension

从版本 3.x 开始,必须显式安装 WebJobs SDK 所需的存储绑定扩展。Starting with version 3.x, you must explicitly install the Storage binding extension required by the WebJobs SDK. 在以前版本中,存储绑定已包含在 SDK 中。In prior versions, the Storage bindings were included in the SDK.

  1. 安装 Microsoft.Azure.WebJobs.Extensions.Storage NuGet 包的最新稳定版本,即 3.x 版。Install the latest stable version of the Microsoft.Azure.WebJobs.Extensions.Storage NuGet package, version 3.x.

    下面是包管理器控制台命令:Here's the Package Manager Console command:

    Install-Package Microsoft.Azure.WebJobs.Extensions.Storage -Version <3_X_VERSION>
    

    在此命令中,将 <3_X_VERSION> 替换为包的受支持版本。In this command, replace <3_X_VERSION> with a supported version of the package.

  2. ConfigureWebJobs 扩展方法中,调用 HostBuilder 实例上的 AddAzureStorage 方法来初始化存储扩展。In the ConfigureWebJobs extension method, call the AddAzureStorage method on the HostBuilder instance to initialize the Storage extension. 此时,ConfigureWebJobs 方法如下例所示:At this point, the ConfigureWebJobs method looks like the following example:

    builder.ConfigureWebJobs(b =>
                    {
                        b.AddAzureStorageCoreServices();
                        b.AddAzureStorage();
                    });
    

创建函数Create a function

  1. 右键单击项目,选择“添加” > “新建项...”,选择“类”,将新的 C# 类文件命名为 Functions.cs ,然后选择“添加”。 Right-click the project, select Add > New Item... , choose Class , name the new C# class file Functions.cs , and select Add .

  2. 在 Functions.cs 中,使用以下代码替换生成的模板:In Functions.cs, replace the generated template with the following code:

    using Microsoft.Azure.WebJobs;
    using Microsoft.Extensions.Logging;
    
    namespace WebJobsSDKSample
    {
        public class Functions
        {
            public static void ProcessQueueMessage([QueueTrigger("queue")] string message, ILogger logger)
            {
                logger.LogInformation(message);
            }
        }
    }
    

    QueueTrigger 特性告知运行时,在名为 queue 的 Azure 存储队列中写入新消息时,应调用此函数。The QueueTrigger attribute tells the runtime to call this function when a new message is written on an Azure Storage queue called queue. 队列消息的内容将提供给 message 参数中的方法代码。The contents of the queue message are provided to the method code in the message parameter. 在方法的正文中处理触发器数据。The body of the method is where you process the trigger data. 在此示例中,代码只是记录消息。In this example, the code just logs the message.

    message 参数不一定要是字符串。The message parameter doesn't have to be a string. 也可以绑定到 JSON 对象、字节数组或 CloudQueueMessage 对象。You can also bind to a JSON object, a byte array, or a CloudQueueMessage object. 参阅队列触发器用法See Queue trigger usage. 每个绑定类型(例如队列、Blob 或表)具有一组可以绑定到的不同参数类型。Each binding type (such as queues, blobs, or tables) has a different set of parameter types that you can bind to.

创建存储帐户Create a storage account

本地运行的 Azure 存储模拟器没有 WebJobs SDK 所需的部分功能。The Azure Storage Emulator that runs locally doesn't have all of the features that the WebJobs SDK needs. 因此,在本部分,我们应在 Azure 中创建一个存储帐户,并将项目配置为使用该帐户。So in this section you create a storage account in Azure and configure the project to use it. 如果已有一个存储帐户,请跳到步骤 6。If you already have a storage account, skip down to step 6.

  1. 在 Visual Studio 中打开“服务器资源管理器”并登录 Azure。Open Server Explorer in Visual studio and sign in to Azure. 右键单击“Azure”节点,选择“连接到 Microsoft Azure 订阅”。 Right-click the Azure node, and then select Connect to Microsoft Azure Subscription .

    登录 Azure

  2. 在“服务器资源管理器”中的“Azure”节点下,右键单击“存储”并选择“创建存储帐户”。 Under the Azure node in Server Explorer , right-click Storage , and then select Create Storage account .

    “创建存储帐户”菜单

  3. 在“创建存储帐户”对话框中,输入存储帐户的唯一名称。In the Create Storage Account dialog box, enter a unique name for the storage account.

  4. 选择在其中创建了应用服务应用的同一 区域 或者靠近的区域。Choose the same Region that you created your App Service app in, or a region close to you.

  5. 选择“创建” 。Select Create .

    创建存储帐户

  6. 在“服务器资源管理器”中的“存储”节点下,选择新存储帐户。 Under the Storage node in Server Explorer , select the new Storage account. 在“属性”窗口中,选择“连接字符串”值字段右侧的省略号 ( ... )。 In the Properties window, select the ellipsis ( ... ) at the right of the Connection String value field.

    “连接字符串”右侧的省略号

  7. 复制连接字符串并将此值保存在某处,以方便再次复制。Copy the connection string, and save this value somewhere that you can copy it again readily.

    复制连接字符串

将存储配置为在本地运行Configure storage to run locally

WebJobs SDK 在 Azure 的“应用程序设置”中查找存储连接字符串。The WebJobs SDK looks for the storage connection string in the Application Settings in Azure. 在本地运行时,它会在本地配置文件或环境变量中查找此值。When you run locally, it looks for this value in the local configuration file or in environment variables.

  1. 右键单击项目,选择“添加” > “新建项...”,选择“JavaScript JSON 配置文件”,将新文件命名为 appsettings.json ,然后选择“添加”。 Right-click the project, select Add > New Item... , choose JavaScript JSON configuration file , name the new file appsettings.json file, and select Add .

  2. 在新文件中添加 AzureWebJobsStorage 字段,如以下示例所示:In the new file, add a AzureWebJobsStorage field, as in the following example:

    {
        "AzureWebJobsStorage": "{storage connection string}"
    }
    
  3. {storage connection string} 替换为先前复制的连接字符串。Replace {storage connection string} with the connection string that you copied earlier.

  4. 在解决方案资源管理器中选择“appsettings.json”文件,在“属性”窗口中,将“复制到输出目录”设置为“如果较新则复制”。 Select the appsettings.json file in Solution Explorer and in the Properties window, set Copy to Output Directory to Copy if newer .

稍后,你将在 Azure 应用服务中的应用中添加相同的连接字符串应用设置。Later, you'll add the same connection string app setting in your app in Azure App Service.

本地测试Test locally

在本部分,我们将生成并在本地运行项目,然后通过创建队列消息来触发函数。In this section, you build and run the project locally and trigger the function by creating a queue message.

  1. Ctrl+F5 运行项目。Press Ctrl+F5 to run the project.

    控制台显示运行时已找到函数,并等待队列消息触发该函数。The console shows that the runtime found your function and is waiting for queue messages to trigger it. v3.x 主机生成以下输出:The following output is generated by the v3.x host:

     info: Microsoft.Azure.WebJobs.Hosting.JobHostService[0]
           Starting JobHost
     info: Host.Startup[0]
           Found the following functions:
           WebJobsSDKSample.Functions.ProcessQueueMessage
    
     info: Host.Startup[0]
           Job host started
     Application started. Press Ctrl+C to shut down.
     Hosting environment: Development
     Content root path: C:\WebJobsSDKSample\WebJobsSDKSample\bin\Debug\netcoreapp2.1\
    
  2. 关闭控制台窗口。Close the console window.

  3. 在 Visual Studio 的“服务器资源管理器”中,展开新存储帐户所在的节点,然后右键单击“队列”。 In Server Explorer in Visual Studio, expand the node for your new storage account, and then right-click Queues .

  4. 选择“创建队列”。Select Create Queue .

  5. 输入 queue 作为队列名称,然后选择“确定”。Enter queue as the name for the queue, and then select OK .

    显示创建队列的位置并将其命名为“队列”的屏幕截图。Screenshot that shows where you create the queue and name it "queue".

  6. 右键单击新队列所在的节点,然后选择“查看队列”。Right-click the node for the new queue, and then select View Queue .

  7. 选择“添加消息”图标。Select the Add Message icon.

    突出显示“添加消息”图标的屏幕截图。

  8. 在“添加消息”对话框中,输入 Hello World! In the Add Message dialog, enter Hello World! 作为 消息正文 ,然后选择“确定”。as the Message text , and then select OK . 现在,队列中会出现一条消息。There is now a message in the queue.

    创建队列

  9. 再次运行该项目。Run the project again.

    由于在 ProcessQueueMessage 函数中使用了 QueueTrigger 特性,因此 WeJobs SDK 运行时会在启动时侦听队列消息。Because you used the QueueTrigger attribute in the ProcessQueueMessage function, the WeJobs SDK runtime listens for queue messages when it starts up. 它会在名为 queue 的队列中查找新队列消息,并调用函数。It finds a new queue message in the queue named queue and calls the function.

    由于队列轮询指数退让,运行时最长可能需要花费 2 分钟才能找到消息并调用函数。Due to queue polling exponential backoff, it might take as long as 2 minutes for the runtime to find the message and invoke the function. 开发模式运行可以缩减此等待时间。This wait time can be reduced by running in development mode.

    控制台输出如下所示:The console output looks like this:

     info: Function.ProcessQueueMessage[0]
           Executing 'Functions.ProcessQueueMessage' (Reason='New queue message detected on 'queue'.', Id=2c319369-d381-43f3-aedf-ff538a4209b8)
     info: Function.ProcessQueueMessage[0]
           Trigger Details: MessageId: b00a86dc-298d-4cd2-811f-98ec39545539, DequeueCount: 1, InsertionTime: 1/18/2019 3:28:51 AM +00:00
     info: Function.ProcessQueueMessage.User[0]
           Hello World!
     info: Function.ProcessQueueMessage[0]
           Executed 'Functions.ProcessQueueMessage' (Succeeded, Id=2c319369-d381-43f3-aedf-ff538a4209b8)
    
  10. 关闭控制台窗口。Close the console window.

  11. 返回“队列”窗口并刷新。Go back to the Queue window and refresh it. 消息已消失,因为已由本地运行的函数处理了。The message is gone, since it has been processed by your function running locally.

添加 Application Insights 日志记录Add Application Insights logging

在 Azure 中运行项目时,无法通过查看控制台输出来监视函数执行。When the project runs in Azure, you can't monitor function execution by viewing console output. 我们建议的监视解决方案是 Application InsightsThe monitoring solution we recommend is Application Insights. 有关详细信息,请参阅监视 Azure FunctionsFor more information, see Monitor Azure Functions.

在本部分,我们将执行以下任务来设置 Application Insights 日志记录,然后部署到 Azure:In this section, you do the following tasks to set up Application Insights logging before you deploy to Azure:

  • 请确保已准备好要使用的应用服务应用和 Application Insights 实例。Make sure you have an App Service app and an Application Insights instance to work with.
  • 将应用服务应用配置为使用前面创建的 Application Insights 实例和存储帐户。Configure the App Service app to use the Application Insights instance and the storage account that you created earlier.
  • 设置项目,以便将日志记录到 Application Insights。Set up the project for logging to Application Insights.

创建应用服务应用和 Application Insights 实例Create App Service app and Application Insights instance

  1. 如果没有可用的应用服务应用,请创建一个If you don't already have an App Service app that you can use, create one. 创建应用时,还可以创建已连接的 Application Insights 资源。When you create your app, you can also create a connected Application Insights resource. 执行此操作时,系统会在应用中为你设置 APPINSIGHTS_INSTRUMENTATIONKEYWhen you do this, the APPINSIGHTS_INSTRUMENTATIONKEY is set for you in your app.

  2. 如果没有可用的 Application Insights 资源,请创建一个If you don't already have an Application Insights resource that you can use, create one. 将“应用程序类型”设置为“常规”,并跳过“复制检测密钥”后面的部分。 Set Application type to General , and skip the sections that follow Copy the instrumentation key .

  3. 如果已有可用的 Application Insights 资源,请复制检测密钥If you already have an Application Insights resource that you want to use, copy the instrumentation key.

配置应用设置Configure app settings

  1. 在 Visual Studio 的“服务器资源管理器”中,展开“Azure”下面的“应用服务”节点。 In Server Explorer in Visual Studio, expand the App Service node under Azure .

  2. 展开应用服务应用所在的资源组,然后右键单击应用服务应用。Expand the resource group that your App Service app is in, and then right-click your App Service app.

  3. 选择“查看设置”。Select View Settings .

  4. 在“连接字符串”框中添加以下条目。In the Connection Strings box, add the following entry.

    名称Name 连接字符串connection String 数据库类型Database Type
    AzureWebJobsStorageAzureWebJobsStorage {前面复制的存储连接字符串}{the Storage connection string that you copied earlier} 自定义Custom
  5. 如果“应用程序设置”框中没有 Application Insights 检测密钥,请添加前面复制的检测密钥。If the Application Settings box doesn't have an Application Insights instrumentation key, add the one that you copied earlier. (根据应用服务应用的创建方式,该框中可能已包含检测密钥。)(The instrumentation key may already be there, depending on how you created the App Service app.)

    名称Name Value
    APPINSIGHTS_INSTRUMENTATIONKEYAPPINSIGHTS_INSTRUMENTATIONKEY {instrumentation key}{instrumentation key}
  6. {instrumentation key} 替换为所用 Application Insights 资源中的检测密钥。Replace {instrumentation key} with the instrumentation key from the Application Insights resource that you're using.

  7. 选择“保存” 。Select Save .

  8. 向项目添加 Application Insights 连接,以便在本地运行。Add the Application Insights connection to the project so that you can run it locally. 在“appsettings.json”文件中,添加 APPINSIGHTS_INSTRUMENTATIONKEY 字段,如下例所示:In the appsettings.json file, add an APPINSIGHTS_INSTRUMENTATIONKEY field, as in the following example:

    {
        "AzureWebJobsStorage": "{storage connection string}",
        "APPINSIGHTS_INSTRUMENTATIONKEY": "{instrumentation key}"
    }
    

    {instrumentation key} 替换为所用 Application Insights 资源中的检测密钥。Replace {instrumentation key} with the instrumentation key from the Application Insights resource that you're using.

  9. 保存所做更改。Save your changes.

添加 Application Insights 日志记录提供程序Add Application Insights logging provider

若要利用 Application Insights 日志记录,请更新日志记录代码以执行以下操作:To take advantage of Application Insights logging, update your logging code to do the following:

  • 使用默认筛选功能添加 Application Insights 日志记录提供程序。Add an Application Insights logging provider with default filtering. 在本地运行时,所有信息和更高级别日志都会同时写入控制台和 Application Insights。When running locally, all Information and higher-level logs are written to both the console and Application Insights.
  • LoggerFactory 对象放在 using 块中,以确保在主机退出时刷新日志输出。Put the LoggerFactory object in a using block to ensure that log output is flushed when the host exits.
  1. 安装 Microsoft.Azure.WebJobs.Logging.ApplicationInsights NuGet 包 的最新稳定 3.x 版本。Install the latest stable 3.x version of the Microsoft.Azure.WebJobs.Logging.ApplicationInsights NuGet package.

    下面是包管理器控制台命令:Here's the Package Manager Console command:

    Install-Package Microsoft.Azure.WebJobs.Logging.ApplicationInsights -Version <3_X_VERSION>
    

    在此命令中,将 <3_X_VERSION> 替换为包的受支持版本。In this command, replace <3_X_VERSION> with a supported version of the package.

  2. 打开“Program.cs”并使用以下代码替换 Main 方法中的代码:Open Program.cs and replace the code in the Main method with the following code:

    static async Task Main()
    {
        var builder = new HostBuilder();
        builder.UseEnvironment(EnvironmentName.Development);
        builder.ConfigureWebJobs(b =>
                {
                    b.AddAzureStorageCoreServices();
                    b.AddAzureStorage();
                });
        builder.ConfigureLogging((context, b) =>
                {
                    b.AddConsole();
    
                    // If the key exists in settings, use it to enable Application Insights.
                    string instrumentationKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
                    if (!string.IsNullOrEmpty(instrumentationKey))
                    {
                        b.AddApplicationInsightsWebJobs(o => o.InstrumentationKey = instrumentationKey);
                    }
                });
        var host = builder.Build();
        using (host)
        {
            await host.RunAsync();
        }
    }
    

    这会使用之前添加到应用设置中的密钥将 Application Insights 提供程序添加到日志记录中。This adds the Application Insights provider to the logging, using the key you added earlier to your app settings.

测试 Application Insights 日志记录Test Application Insights logging

在本部分,我们将再次在本地运行,以验证日志记录数据现在是否转到 Application Insights 和控制台。In this section, you run locally again to verify that logging data is now going to Application Insights as well as to the console.

  1. 使用 Visual Studio 中的 服务器资源管理器 创建队列消息,就像你 之前所做的那样,但这次输入“Hello App Insights!”Use Server Explorer in Visual Studio to create a queue message like you did earlier, except enter Hello App Insights! 作为消息文本。as the message text.

  2. 运行该项目。Run the project.

    WebJobs SDK 将处理队列消息,控制台窗口中会显示日志。The WebJobs SDK processes the queue message, and you see the logs in the console window.

  3. 关闭控制台窗口。Close the console window.

  4. 转到 Azure 门户以查看 Application Insights 资源。Go to the Azure portal to view your Application Insights resource. 搜索并选择“Application Insights”。Search for and select Application Insights .

  5. 选择 Application Insights 实例。Choose your Application Insights instance.

  6. 选择“搜索”。Select Search .

    选择“搜索”

  7. 如果未看到“Hello App Insights!”If you don't see the Hello App Insights! 消息,请定期选择“刷新”几分钟。message, select Refresh periodically for several minutes. (日志不会立即显示,因为 Application Insights 客户端需要一段时间来刷新它处理的日志。)(Logs don't appear immediately, because it takes a while for the Application Insights client to flush the logs it processes.)

    Application Insights 中的日志

  8. 关闭控制台窗口。Close the console window.

部署到 AzureDeploy to Azure

在部署期间,可以创建一个要在其中运行函数的应用服务实例。During deployment, you create an app service instance in which to run your functions. 将 .NET Core 控制台应用发布到 Azure 中的应用服务时,该应用会自动以 WebJob 的形式运行。When you publish a .NET Core console app to App Service in Azure, it automatically gets run as a WebJob. 若要详细了解发布过程,请参阅使用 Visual Studio 开发和部署 WebJobTo learn more about publishing, see Develop and deploy WebJobs using Visual Studio.

  1. 在“解决方案资源管理器” 中,右键单击该项目并选择“发布” 。In Solution Explorer, right-click the project and select Publish.

  2. 在“发布”对话框中,依次选择“Microsoft Azure 应用服务”和“新建”,然后选择“发布”。 In the Publish dialog, select Microsoft Azure App Service, choose Create New, and then select Publish.

    选取发布目标

  3. 在“创建应用服务” 对话框中,使用图片下方的表中指定的托管设置:In the Create App Service dialog, use the hosting settings as specified in the table below the image:

    “创建应用服务”对话框

    设置Setting 建议的值Suggested value 说明Description
    应用名称App Name 全局唯一名称Globally unique name 用于唯一标识新 Function App 的名称。Name that uniquely identifies your new function app.
    订阅Subscription 选择自己的订阅Choose your subscription 要使用的 Azure 订阅。The Azure subscription to use.
    资源组Resource Group MyResourceGroupmyResourceGroup 要在其中创建 Function App 的资源组的名称。Name of the resource group in which to create your function app. 选择“新建” 创建新的资源组。Choose New to create a new resource group.
    托管计划Hosting Plan 应用服务计划App Service plan 应用服务计划指定托管应用的 Web 服务器场的位置、大小和功能。An App Service plan specifies the location, size, and features of the web server farm that hosts your app. 可以在托管多个应用时节省资金,方法是将多个 Web 应用配置为共用单个应用服务计划。You can save money when hosting multiple apps by configuring the web apps to share a single App Service plan. 应用服务计划定义区域、实例大小、规模计数和 SKU(免费、共享、基本、标准或高级)。App Service plans define the region, instance size, scale count, and SKU (Free, Shared, Basic, Standard, or Premium). 然后,选择“新建” 以创建一个新的应用服务计划。Choose New to create a new App Service plan.
  4. 单击“创建” 以使用这些设置在 Azure 中创建 Web 作业和相关资源,并部署项目代码。Click Create to create a WebJob and related resources in Azure with these settings and deploy your project code.

触发 Azure 中的函数Trigger the function in Azure

  1. 确保不是在本地运行(如果控制台窗口仍旧打开,请将其关闭)。Make sure you're not running locally (close the console window if it's still open). 否则,本地实例可能是处理所创建的任何队列消息的第一个实例。Otherwise the local instance might be the first to process any queue messages you create.

  2. 在 Visual Studio 的“队列”页中,像以前一样向队列添加消息。In the Queue page in Visual Studio, add a message to the queue as before.

  3. 刷新“队列”页后新消息消失,因为它已由 Azure 中运行的函数处理。Refresh the Queue page, and the new message disappears because it has been processed by the function running in Azure.

    提示

    若要在 Azure 中进行测试,请使用开发模式来确保立即调用队列触发函数,并避免队列轮询指数退让导致的延迟。When you're testing in Azure, use development mode to ensure that a queue trigger function is invoked right away and avoid delays due to queue polling exponential backoff.

在 Application Insights 中查看日志View logs in Application Insights

  1. 打开 Azure 门户并转到 Application Insights 资源。Open the Azure portal, and go to your Application Insights resource.

  2. 选择“搜索”。Select Search .

  3. 如果未看到“Hello Azure!”If you don't see the Hello Azure! 消息,请定期选择“刷新”几分钟。message, select Refresh periodically for several minutes.

    查看 WebJob 中运行的函数发出的日志,包括在上一部分中输入的 Hello Azure!You see the logs from the function running in a WebJob, including the Hello Azure! 文本。text that you entered in the preceding section.

添加输入绑定Add an input binding

输入绑定可以简化读取数据的代码。Input bindings simplify code that reads data. 在本示例中,队列消息是 Blob 名称,我们将使用该 Blob 名称来查找和读取 Azure 存储中的 Blob。For this example, the queue message will be a blob name and you'll use the blob name to find and read a blob in Azure Storage.

  1. Functions.cs 中,将 ProcessQueueMessage 方法替换为以下代码:In Functions.cs , replace the ProcessQueueMessage method with the following code:

    public static void ProcessQueueMessage(
        [QueueTrigger("queue")] string message,
        [Blob("container/{queueTrigger}", FileAccess.Read)] Stream myBlob,
        ILogger logger)
    {
        logger.LogInformation($"Blob name:{message} \n Size: {myBlob.Length} bytes");
    }
    

    在此代码中,queueTrigger绑定表达式,意味着它将在运行时解析为不同的值。In this code, queueTrigger is a binding expression, which means it resolves to a different value at runtime. 在运行时,它具有队列消息的内容。At runtime, it has the contents of the queue message.

  2. 添加 usingAdd a using:

    using System.IO;
    
  3. 在存储帐户中创建 Blob 容器。Create a blob container in your storage account.

    a.a. 在 Visual Studio 的“服务器资源管理器”中,展开你的存储帐户所在的节点,右键单击“Blob”,并选择“创建 Blob 容器”。 In Server Explorer in Visual Studio, expand the node for your storage account, right-click Blobs , and then select Create Blob Container .

    b.b. 在“创建 Blob 容器”对话框中,输入 container 作为容器名称,然后单击“确定”。 In the Create Blob Container dialog, enter container as the container name, and then click OK .

  4. Program.cs 文件上传到 Blob 容器。Upload the Program.cs file to the blob container. (此处使用的文件用作示例;可以上传任何文本文件,并使用该文件的名称创建队列消息。)(This file is used here as an example; you could upload any text file and create a queue message with the file's name.)

    a.a. 在“服务器资源管理器”中,双击创建的容器所在的节点。In Server Explorer , double-click the node for the container you created.

    b.b. 在“容器”窗口中,选择“上传”按钮 。In the Container window, select the Upload button.

    Blob 上传按钮

    c.c. 找到并选择“Program.cs”,然后选择“确定”。Find and select Program.cs , and then select OK .

  5. 在前面创建的队列中创建队列消息,并使用 Program.cs 作为消息的文本。Create a queue message in the queue you created earlier, with Program.cs as the text of the message.

    队列消息 Program.cs

  6. 在本地运行项目Run the project locally.

    该队列消息会触发函数,而该函数又会读取 Blob 并记录其长度。The queue message triggers the function, which then reads the blob and logs its length. 控制台输出如下所示:The console output looks like this:

    Found the following functions:
    ConsoleApp1.Functions.ProcessQueueMessage
    Job host started
    Executing 'Functions.ProcessQueueMessage' (Reason='New queue message detected on 'queue'.', Id=5a2ac479-de13-4f41-aae9-1361f291ff88)
    Blob name:Program.cs
    Size: 532 bytes
    Executed 'Functions.ProcessQueueMessage' (Succeeded, Id=5a2ac479-de13-4f41-aae9-1361f291ff88)
    

添加输出绑定Add an output binding

输出绑定可以简化写入数据的代码。Output bindings simplify code that writes data. 本示例在前一个示例的基础上做了修改,它会写入 Blob 的副本,而不是记录其大小。This example modifies the previous one by writing a copy of the blob instead of logging its size. Blob 存储绑定包含在我们之前安装的 Azure 存储扩展包中。Blob storage bindings are included in the Azure Storage extension package that we installed previously.

  1. ProcessQueueMessage 方法替换为以下代码:Replace the ProcessQueueMessage method with the following code:

    public static void ProcessQueueMessage(
        [QueueTrigger("queue")] string message,
        [Blob("container/{queueTrigger}", FileAccess.Read)] Stream myBlob,
        [Blob("container/copy-{queueTrigger}", FileAccess.Write)] Stream outputBlob,
        ILogger logger)
    {
        logger.LogInformation($"Blob name:{message} \n Size: {myBlob.Length} bytes");
        myBlob.CopyTo(outputBlob);
    }
    
  2. 创建另一个队列消息,并使用 Program.cs 作为消息的文本。Create another queue message with Program.cs as the text of the message.

  3. 在本地运行项目Run the project locally.

    该队列消息会触发函数,而该函数又会读取 Blob、记录其长度并创建新 Blob。The queue message triggers the function, which then reads the blob, logs its length, and creates a new blob. 控制台输出相同,但在转到 Blob 容器窗口并选择“刷新”时,会看到名为 copy-Program.cs 的新 Blob。The console output is the same, but when you go to the blob container window and select Refresh , you see a new blob named copy-Program.cs.

将更新重新发布到 AzureRepublish the updates to Azure

  1. 在“解决方案资源管理器” 中,右键单击该项目并选择“发布”。In Solution Explorer , right-click the project and select Publish .

  2. 在“发布”对话框中,确保当前配置文件已选中,然后选择“发布”。 In the Publish dialog, make sure that the current profile is selected and then choose Publish . “输出”窗口中会详细显示发布结果。Results of the publish are detailed in the Output window.

  3. 通过再次将某个文件上传到 Blob 容器,并将一条消息添加到与所上传文件同名的队列,来验证 Azure 中的函数。Verify the function in Azure by again uploading a file to the blob container and adding a message to the queue that is the name of the uploaded file. 将会看到,该消息已从队列中删除,并且 Blob 容器中创建了该文件的副本。You see the message get removed from the queue and a copy of the file created in the blob container.

后续步骤Next steps

本文介绍了如何创建、运行和部署 WebJobs SDK 3.x 项目。This article showed you how to create, run, and deploy a WebJobs SDK 3.x project.