快速入门:在 Azure 中创建用于响应 HTTP 请求的函数Quickstart: Create a function in Azure that responds to HTTP requests

在本文中,我们使用命令行工具创建一个响应 HTTP 请求的基于 C# 类库的函数。In this article, you use command-line tools to create a C# class library-based function that responds to HTTP requests. 在本地测试代码后,将代码部署到 Azure Functions 的无服务器环境。After testing the code locally, you deploy it to the serverless environment of Azure Functions.

在本文中,我们使用命令行工具创建一个响应 HTTP 请求的 JavaScript 函数。In this article, you use command-line tools to create a JavaScript function that responds to HTTP requests. 在本地测试代码后,将代码部署到 Azure Functions 的无服务器环境。After testing the code locally, you deploy it to the serverless environment of Azure Functions.

在本文中,我们使用命令行工具创建一个响应 HTTP 请求的 TypeScript 函数。In this article, you use command-line tools to create a TypeScript function that responds to HTTP requests. 在本地测试代码后,将代码部署到 Azure Functions 的无服务器环境。After testing the code locally, you deploy it to the serverless environment of Azure Functions.

在本文中,我们使用命令行工具创建一个响应 HTTP 请求的 PowerShell 函数。In this article, you use command-line tools to create a PowerShell function that responds to HTTP requests. 在本地测试代码后,将代码部署到 Azure Functions 的无服务器环境。After testing the code locally, you deploy it to the serverless environment of Azure Functions.

在本文中,我们使用命令行工具创建一个响应 HTTP 请求的 Java 函数。In this article, you use command-line tools to create a Java function that responds to HTTP requests. 在本地测试代码后,将代码部署到 Azure Functions 的无服务器环境。After testing the code locally, you deploy it to the serverless environment of Azure Functions.

完成本快速入门会从你的 Azure 帐户中扣取最多几美分的费用。Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.

本文还提供了基于 Visual Studio 代码的版本There is also a Visual Studio Code-based version of this article.

备注

如果 Maven 不是你的首选开发工具,请查看面向使用 GradleIntelliJ IDEAVisual Studio Code 的 Java 开发人员的类似教程。If Maven is not your prefered development tool, check out our similar tutorials for Java developers using Gradle, IntelliJ IDEA and Visual Studio Code.

配置本地环境Configure your local environment

在开始之前,必须满足以下条件:Before you begin, you must have the following:

  • Node.js,活动 LTS 和维护 LTS 版本(建议使用 8.11.1 和 10.14.1)。Node.js, Active LTS and Maintenance LTS versions (8.11.1 and 10.14.1 recommended).

先决条件检查Prerequisite check

  • 在终端或命令窗口中,运行 func --version 检查 Azure Functions Core Tools 的版本是否为 2.7.1846 或以上。In a terminal or command window, run func --version to check that the Azure Functions Core Tools are version 2.7.1846 or later.

  • 运行 az --version 检查 Azure CLI 版本是否为 2.0.76 或以上。Run az --version to check that the Azure CLI version is 2.0.76 or later.

  • 运行 az login 登录到 Azure 并验证活动订阅。Run az login to sign in to Azure and verify an active subscription.

创建本地函数项目Create a local function project

在 Azure Functions 中,有一个函数项目是一个或多个单独函数(每个函数响应特定的触发器)的容器。In Azure Functions, a function project is a container for one or more individual functions that each responds to a specific trigger. 项目中的所有函数共享相同的本地和宿主配置。All functions in a project share the same local and hosting configurations. 在本部分,你将创建包含单个函数的函数项目。In this section, you create a function project that contains a single function.

按如下所示运行 func init 命令,在名为 LocalFunctionProj 的文件夹中创建使用指定运行时的函数项目:Run the func init command, as follows, to create a functions project in a folder named LocalFunctionProj with the specified runtime:

func init LocalFunctionProj --dotnet
func init LocalFunctionProj --javascript
func init LocalFunctionProj --typescript
func init LocalFunctionProj --powershell

在空的文件夹中,运行以下命令以从 Maven archetype 生成 Functions 项目。In an empty folder, run the following command to generate the Functions project from a Maven archetype.

重要

  • 如果希望函数在 Java 11 上运行,请使用 -DjavaVersion=11Use -DjavaVersion=11 if you want to your functions to run on Java 11. 若要了解详细信息,请参阅 Java 版本To learn more, see Java versions.
  • 要完成本文中的步骤,JAVA_HOME 环境变量必须设置为正确版本的 JDK 的安装位置。The JAVA_HOME environment variable must be set to the install location of the correct version of the JDK to complete this article.
mvn archetype:generate -DarchetypeGroupId=com.microsoft.azure -DarchetypeArtifactId=azure-functions-archetype -DjavaVersion=8

Maven 会请求你提供所需的值,以在部署上完成项目的生成。Maven asks you for values needed to finish generating the project on deployment.
系统提示时提供以下值:Provide the following values when prompted:

PromptPrompt Value 说明Description
groupIdgroupId com.fabrikam 一个值,用于按照 Java 的包命名规则在所有项目中标识你的项目。A value that uniquely identifies your project across all projects, following the package naming rules for Java.
artifactIdartifactId fabrikam-functions 一个值,该值是 jar 的名称,没有版本号。A value that is the name of the jar, without a version number.
versionversion 1.0-SNAPSHOT 选择默认值。Choose the default value.
packagepackage com.fabrikam 一个值,该值是所生成函数代码的 Java 包。A value that is the Java package for the generated function code. 使用默认值。Use the default.

键入 Y 或按 Enter 进行确认。Type Y or press Enter to confirm.

Maven 在名为 artifactId 的新文件夹(在此示例中为 fabrikam-functions)中创建项目文件。Maven creates the project files in a new folder with a name of artifactId , which in this example is fabrikam-functions.

导航到项目文件夹:Navigate into the project folder:

cd LocalFunctionProj
cd fabrikam-functions

此文件夹包含项目的各个文件,其中包括名为 local.settings.jsonhost.json 的配置文件。This folder contains various files for the project, including configurations files named local.settings.json and host.json. 由于 local.settings.json 可以包含从 Azure 下载的机密,因此,默认情况下,该文件会从 .gitignore 文件的源代码管理中排除。Because local.settings.json can contain secrets downloaded from Azure, the file is excluded from source control by default in the .gitignore file.

使用以下命令将一个函数添加到项目,其中,--name 参数是该函数 (HttpExample) 的唯一名称,--template 参数指定该函数的触发器 (HTTP)。Add a function to your project by using the following command, where the --name argument is the unique name of your function (HttpExample) and the --template argument specifies the function's trigger (HTTP).

func new --name HttpExample --template "HTTP trigger"

func new 创建 HttpExample.cs 代码文件。func new creates a HttpExample.cs code file.

func new 创建一个与函数名称匹配的、包含项目所选语言适用的代码文件的子文件夹,以及一个名为 function.json 的配置文件。func new creates a subfolder matching the function name that contains a code file appropriate to the project's chosen language and a configuration file named function.json.

(可选)检查文件内容(Optional) Examine the file contents

如果需要,可以跳到在本地运行函数并稍后再检查文件内容。If desired, you can skip to Run the function locally and examine the file contents later.

HttpExample.csHttpExample.cs

HttpExample.cs 包含一个接收 req 变量中的请求数据的 Run 方法,该变量是使用 HttpTriggerAttribute 修饰的 HttpRequest ,用于定义触发器行为。HttpExample.cs contains a Run method that receives request data in the req variable is an HttpRequest that's decorated with the HttpTriggerAttribute , which defines the trigger behavior.

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace LocalFunctionProj
{
    public static class HttpExample
    {
        [FunctionName("HttpExample")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }
    }
}

返回对象是 ActionResult,它将响应消息作为 OkObjectResult (200) 或 BadRequestObjectResult (400) 返回。The return object is an ActionResult that returns a response message as either an OkObjectResult (200) or a BadRequestObjectResult (400). 要了解详细信息,请参阅 Azure Functions HTTP 触发器和绑定To learn more, see Azure Functions HTTP triggers and bindings.

Function.javaFunction.java

Function.java 包含一个接收 request 变量中的请求数据的 run 方法,该变量是使用 HttpTrigger 注释修饰的 HttpRequestMessage,用于定义触发器行为。Function.java contains a run method that receives request data in the request variable is an HttpRequestMessage that's decorated with the HttpTrigger annotation, which defines the trigger behavior.

/**
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 */

package com.functions;

import com.microsoft.azure.functions.ExecutionContext;
import com.microsoft.azure.functions.HttpMethod;
import com.microsoft.azure.functions.HttpRequestMessage;
import com.microsoft.azure.functions.HttpResponseMessage;
import com.microsoft.azure.functions.HttpStatus;
import com.microsoft.azure.functions.annotation.AuthorizationLevel;
import com.microsoft.azure.functions.annotation.FunctionName;
import com.microsoft.azure.functions.annotation.HttpTrigger;

import java.util.Optional;

/**
 * Azure Functions with HTTP Trigger.
 */
public class Function {
    /**
     * This function listens at endpoint "/api/HttpExample". Two ways to invoke it using "curl" command in bash:
     * 1. curl -d "HTTP Body" {your host}/api/HttpExample
     * 2. curl "{your host}/api/HttpExample?name=HTTP%20Query"
     */
    @FunctionName("HttpExample")
    public HttpResponseMessage run(
            @HttpTrigger(
                name = "req",
                methods = {HttpMethod.GET, HttpMethod.POST},
                authLevel = AuthorizationLevel.ANONYMOUS)
                HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {
        context.getLogger().info("Java HTTP trigger processed a request.");

        // Parse query parameter
        final String query = request.getQueryParameters().get("name");
        final String name = request.getBody().orElse(query);

        if (name == null) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("Please pass a name on the query string or in the request body").build();
        } else {
            return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();
        }
    }
}

响应消息由 HttpResponseMessage.Builder API 生成。The response message is generated by the HttpResponseMessage.Builder API.

pom.xmlpom.xml

为托管应用而创建的 Azure 资源的设置在插件的 configuration 元素中使用生成的 pom.xml 文件中 com.microsoft.azure 的 groupId 定义。Settings for the Azure resources created to host your app are defined in the configuration element of the plugin with a groupId of com.microsoft.azure in the generated pom.xml file. 例如,以下 configuration 元素指示基于 Maven 的部署在 chinanorth2 区域中的 java-functions-group 资源组内创建一个函数应用。For example, the configuration element below instructs a Maven-based deployment to create a function app in the java-functions-group resource group in the chinanorth2 region. 该函数应用本身在 Windows 上运行,后者托管在 java-functions-app-service-plan 计划(默认情况下是一个无服务器消耗计划)中。The function app itself runs on Windows hosted in the java-functions-app-service-plan plan, which by default is a serverless Consumption plan.

            <plugin>
                <groupId>com.microsoft.azure</groupId>
                <artifactId>azure-functions-maven-plugin</artifactId>
                <version>${azure.functions.maven.plugin.version}</version>
                <configuration>
                    <!-- function app name -->
                    <appName>${functionAppName}</appName>
                    <!-- function app resource group -->
                    <resourceGroup>${functionResourceGroup}</resourceGroup>
                    <!-- function app service plan name -->
                    <appServicePlanName>java-functions-app-service-plan</appServicePlanName>
                    <!-- function app region-->
                    <!-- refers https://github.com/microsoft/azure-maven-plugins/wiki/Azure-Functions:-Configuration-Details#supported-regions for all valid values -->
                    <region>${functionAppRegion}</region>
                    <!-- function pricingTier, default to be consumption if not specified -->
                    <!-- refers https://github.com/microsoft/azure-maven-plugins/wiki/Azure-Functions:-Configuration-Details#supported-pricing-tiers for all valid values -->
                    <!-- <pricingTier></pricingTier> -->

                    <!-- Whether to disable application insights, default is false -->
                    <!-- refers https://github.com/microsoft/azure-maven-plugins/wiki/Azure-Functions:-Configuration-Details for all valid configurations for application insights-->
                    <!-- <disableAppInsights></disableAppInsights> -->
                    <runtime>
                        <!-- runtime os, could be windows->
                        <os>windows</os>
                        <javaVersion>8</javaVersion>
                        <!-- for docker function, please set the following parameters -->
                        <!-- <image>[hub-user/]repo-name[:tag]</image> -->
                        <!-- <serverId></serverId> -->
                        <!-- <registryUrl></registryUrl>  -->
                    </runtime>
                    <appSettings>
                        <property>
                            <name>FUNCTIONS_EXTENSION_VERSION</name>
                            <value>~3</value>
                        </property>
                    </appSettings>
                </configuration>
                <executions>
                    <execution>
                        <id>package-functions</id>
                        <goals>

你可以更改这些设置,以控制在 Azure 中创建资源的方式。You can change these settings to control how resources are created in Azure. 有关 Maven 插件支持的设置的完整列表,请参阅配置详细信息For a complete list of settings supported by the Maven plug-in, see the configuration details.

FunctionTest.javaFunctionTest.java

原型还会为函数生成单元测试。The archetype also generates a unit test for your function. 更改函数以便在项目中添加绑定或新函数时,也需要修改 FunctionTest.java 文件中的测试。When you change your function to add bindings or add new functions to the project, you'll also need to modify the tests in the FunctionTest.java file.

index.jsindex.js

index.js 导出一个根据 function.json 中的配置触发的函数。index.js exports a function that's triggered according to the configuration in function.json.

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? "Hello, " + name + ". This HTTP triggered function executed successfully."
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
}

对于 HTTP 触发器,该函数将接收 function.json 中定义的变量 req 中的请求数据。For an HTTP trigger, the function receives request data in the variable req as defined in function.json. function.json 中定义为 $return 的返回对象是响应。The return object, defined as $return in function.json , is the response. 要了解详细信息,请参阅 Azure Functions HTTP 触发器和绑定To learn more, see Azure Functions HTTP triggers and bindings.

index.tsindex.ts

index.ts 导出一个根据 function.json 中的配置触发的函数。index.ts exports a function that's triggered according to the configuration in function.json.

import { AzureFunction, Context, HttpRequest } from "@azure/functions"

const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    context.log('HTTP trigger function processed a request.');
    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? "Hello, " + name + ". This HTTP triggered function executed successfully."
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };

};

export default httpTrigger;

对于 HTTP 触发器,该函数将接收 function.json 中定义的 HttpRequest 类型的变量 req 中的请求数据。For an HTTP trigger, the function receives request data in the variable req of type HttpRequest as defined in function.json. function.json 中定义为 $return 的返回对象是响应。The return object, defined as $return in function.json , is the response.

run.ps1run.ps1

run.ps1 定义一个根据 function.json 中的配置触发的函数脚本。run.ps1 defines a function script that's triggered according to the configuration in function.json.

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."

# Interact with query parameters or the body of the request.
$name = $Request.Query.Name
if (-not $name) {
    $name = $Request.Body.Name
}

$body = "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."

if ($name) {
    $body = "Hello, $name. This HTTP triggered function executed successfully."
}

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = $body
})

对于 HTTP 触发器,该函数将接收传递给 function.json 中定义的 $Request 参数的请求数据。For an HTTP trigger, the function receives request data passed to the $Request param defined in function.json. function.json 中定义为 Response 的返回对象将作为响应传递给 Push-OutputBinding cmdlet。The return object, defined as Response in function.json , is passed to the Push-OutputBinding cmdlet as the response.

function.jsonfunction.json

function.json 是一个配置文件,其中定义了函数的输入和输出 bindings,包括触发器类型。function.json is a configuration file that defines the input and output bindings for the function, including the trigger type.

{
    "bindings": [
        {
            "authLevel": "function",
            "type": "httpTrigger",
            "direction": "in",
            "name": "req",
            "methods": [
                "get",
                "post"
            ]
        },
        {
            "type": "http",
            "direction": "out",
            "name": "res"
        }
    ]
}
{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "Request",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "Response"
    }
  ]
}

每个绑定都需要一个方向、类型和唯一的名称。Each binding requires a direction, a type, and a unique name. HTTP 触发器具有类型为 httpTrigger 的输入绑定和类型为 http 的输出绑定。The HTTP trigger has an input binding of type httpTrigger and output binding of type http.

在本地运行函数Run the function locally

通过从 LocalFunctionProj 文件夹启动本地 Azure Functions 运行时主机来运行函数:Run your function by starting the local Azure Functions runtime host from the LocalFunctionProj folder:

func start
npm install
npm start
mvn clean package 
mvn azure-functions:run

在输出的末尾,应显示以下行:Toward the end of the output, the following lines should appear:

...

Now listening on: http://0.0.0.0:7071
Application started. Press Ctrl+C to shut down.

Http Functions:

        HttpExample: [GET,POST] http://localhost:7071/api/HttpExample
...

备注

如果 HttpExample 未按下面所示出现,则可能是在项目的根文件夹外启动了主机。If HttpExample doesn't appear as shown below, you likely started the host from outside the root folder of the project. 在这种情况下,请按 Ctrl+C 停止主机,导航到项目的根文件夹,然后重新运行上一命令。In that case, use Ctrl+C to stop the host, navigate to the project's root folder, and run the previous command again.

将此输出中 HttpExample 函数的 URL 复制到浏览器,并追加查询字符串 ?name=<your-name>,使完整 URL 类似于 http://localhost:7071/api/HttpExample?name=FunctionsCopy the URL of your HttpExample function from this output to a browser and append the query string ?name=<your-name>, making the full URL like http://localhost:7071/api/HttpExample?name=Functions. 浏览器应会显示类似于 Hello Functions 的消息:The browser should display a message like Hello Functions:

在浏览器中本地运行函数后的结果

当你发出请求时,启动项目时所在的终端还会显示日志输出。The terminal in which you started your project also shows log output as you make requests.

准备就绪后,按 Ctrl+C 并选择 y 停止函数主机。When you're ready, use Ctrl+C and choose y to stop the functions host.

创建函数的支持性 Azure 资源Create supporting Azure resources for your function

在将函数代码部署到 Azure 之前,需要创建三个资源:Before you can deploy your function code to Azure, you need to create three resources:

  • 一个资源组:相关资源的逻辑容器。A resource group, which is a logical container for related resources.
  • 一个存储帐户:维护有关项目的状态和其他信息。A Storage account, which maintains state and other information about your projects.
  • 一个函数应用:提供用于执行函数代码的环境。A function app, which provides the environment for executing your function code. 函数应用映射到本地函数项目,可让你将函数分组为一个逻辑单元,以便更轻松地管理、部署和共享资源。A function app maps to your local function project and lets you group functions as a logical unit for easier management, deployment, and sharing of resources.

使用以下 Azure CLI 命令创建这些项。Use the following Azure CLI commands to create these items. 完成后,每个命令将提供 JSON 输出。Each command provides JSON output upon completion.

使用 az login 命令登录到 Azure(如果尚未这样做):If you haven't done so already, sign in to Azure with the az login command:

az login

使用 az group create 命令创建资源组。Create a resource group with the az group create command. 以下示例在 chinanorth2 区域中创建名为 AzureFunctionsQuickstart-rg 的资源组。The following example creates a resource group named AzureFunctionsQuickstart-rg in the chinanorth2 region. (通常,你会在 az account list-locations 命令输出的、与你靠近的某个可用区域中创建资源组和资源。)(You generally create your resource group and resources in a region near you, using an available region from the az account list-locations command.)

az group create --name AzureFunctionsQuickstart-rg --location chinanorth2

使用 az storage account create 命令在资源组和区域中创建常规用途存储帐户。Create a general-purpose storage account in your resource group and region by using the az storage account create command. 在以下示例中,请将 <STORAGE_NAME> 替换为适合自己的全局唯一名称。In the following example, replace <STORAGE_NAME> with a globally unique name appropriate to you. 名称只能包含 3 到 24 个数字和小写字母字符。Names must contain three to 24 characters numbers and lowercase letters only. Standard_LRS 指定 Functions 支持的常规用途帐户。Standard_LRS specifies a general-purpose account, which is supported by Functions.

az storage account create --name <STORAGE_NAME> --location chinanorth2 --resource-group AzureFunctionsQuickstart-rg --sku Standard_LRS

在本快速入门中使用的存储帐户只会产生几美分的费用。The storage account incurs only a few cents (USD) for this quickstart.

使用 az functionapp create 命令创建函数应用。Create the function app using the az functionapp create command. 在以下示例中,请将 <STORAGE_NAME> 替换为在上一步骤中使用的帐户的名称,并将 <APP_NAME> 替换为适合自己的全局唯一名称。In the following example, replace <STORAGE_NAME> with the name of the account you used in the previous step, and replace <APP_NAME> with a globally unique name appropriate to you. <APP_NAME> 也是函数应用的默认 DNS 域。The <APP_NAME> is also the default DNS domain for the function app.

如果使用 Node.js 8,请同时将 --runtime-version 更改为 8If you are using Node.js 8, also change --runtime-version to 8.

az functionapp create --resource-group AzureFunctionsQuickstart-rg --consumption-plan-location chinanorth2 --runtime node --runtime-version 10 --functions-version 2 --name <APP_NAME> --storage-account <STORAGE_NAME>
az functionapp create --resource-group AzureFunctionsQuickstart-rg --consumption-plan-location chinanorth2 --runtime dotnet --functions-version 2 --name <APP_NAME> --storage-account <STORAGE_NAME>
az functionapp create --resource-group AzureFunctionsQuickstart-rg --consumption-plan-location chinanorth2 --runtime powershell --functions-version 2 --name <APP_NAME> --storage-account <STORAGE_NAME>

此命令将创建一个函数应用,该应用在 Azure Functions 消耗计划下指定的语言运行时中运行,根据本教程产生的用量,此操作是免费的。This command creates a function app running in your specified language runtime under the Azure Functions Consumption Plan, which is free for the amount of usage you incur here. 该命令还会在同一资源组中预配关联的 Azure Application Insights 实例,可以使用它来监视函数应用和查看日志。The command also provisions an associated Azure Application Insights instance in the same resource group, with which you can monitor your function app and view logs. 有关详细信息,请参阅监视 Azure FunctionsFor more information, see Monitor Azure Functions. 该实例在激活之前不会产生费用。The instance incurs no costs until you activate it.

将函数项目部署到 AzureDeploy the function project to Azure

使用 Core Tools 将项目部署到 Azure 之前,请从 TypeScript 源文件创建一个生产就绪的 JavaScript 文件版本。Before you use Core Tools to deploy your project to Azure, you create a production-ready build of JavaScript files from the TypeScript source files.

以下命令可以准备要部署的 TypeScript 项目:The following command prepares your TypeScript project for deployment:

npm run build:production 

准备好所需的资源后,便可以使用 func azure functionapp publish 命令将本地函数项目部署到 Azure 中的函数应用。With the necessary resources in place, you're now ready to deploy your local functions project to the function app in Azure by using the func azure functionapp publish command. 在以下示例中,请将 <APP_NAME> 替换为你的应用的名称。In the following example, replace <APP_NAME> with the name of your app.

func azure functionapp publish <APP_NAME>

如果看到错误“找不到名为...的应用”,请等待几秒后重试,因为在执行上一 az functionapp create 命令后,Azure 可能尚未完全初始化该应用。If you see the error, "Can't find app with name ...", wait a few seconds and try again, as Azure may not have fully initialized the app after the previous az functionapp create command.

publish 命令显示类似于以下输出的结果(为简洁起见,示例中的结果已截断):The publish command shows results similar to the following output (truncated for simplicity):

...

Getting site publishing info...
Creating archive for current directory...
Performing remote build for functions project.

...

Deployment successful.
Remote build succeeded!
Syncing triggers...
Functions in msdocs-azurefunctions-qs:
    HttpExample - [httpTrigger]
        Invoke url: https://msdocs-azurefunctions-qs.chinacloudsites.cn/api/httpexample?code=KYHrydo4GFe9y0000000qRgRJ8NdLFKpkakGJQfC3izYVidzzDN4gQ==

将函数项目部署到 AzureDeploy the function project to Azure

首次部署函数项目时,会在 Azure 中创建一个函数应用和相关的资源。A function app and related resources are created in Azure when you first deploy your functions project. 为托管应用而创建的 Azure 资源的设置在 pom.xml 文件中定义。Settings for the Azure resources created to host your app are defined in the pom.xml file. 在本文中,我们将接受默认值。In this article, you'll accept the defaults.

在部署之前,必须使用 az login Azure CLI 命令登录到 Azure 订阅。Before you can deploy, use the az login Azure CLI command to sign in to your Azure subscription.

az login

使用以下命令将项目部署到新的函数应用。Use the following command to deploy your project to a new function app.

mvn azure-functions:deploy

这会在 Azure 中创建以下资源:This creates the following resources in Azure:

  • 资源组。Resource group. 命名为 java-functions-group。Named as java-functions-group.
  • 存储帐户。Storage account. Functions 所需。Required by Functions. 此名称根据存储帐户名称要求随机生成。The name is generated randomly based on Storage account name requirements.
  • 托管计划。Hosting plan. 在 chinanorth2 区域中为函数应用提供无服务器托管。Serverless hosting for your function app in the chinanorth2 region. 名称为 java-functions-app-service-plan。The name is java-functions-app-service-plan.
  • 函数应用。Function app. 函数应用是函数的部署和执行单元。A function app is the deployment and execution unit for your functions. 名称根据 artifactId 随机生成,其后面追加了一个随机生成的数字。The name is randomly generated based on your artifactId , appended with a randomly generated number.

部署会打包项目文件,并使用 zip 部署将其部署到新的函数应用。The deployment packages the project files and deploys them to the new function app using zip deployment. 此代码从 Azure 中的部署包运行。The code runs from the deployment package in Azure.

在 Azure 上调用函数Invoke the function on Azure

由于函数使用 HTTP 触发器,因此,可以通过在浏览器中或使用 curl 等工具,向此函数的 URL 发出 HTTP 请求来调用它。Because your function uses an HTTP trigger, you invoke it by making an HTTP request to its URL in the browser or with a tool like curl. 在这两种情况下,code URL 参数都是唯一的函数密钥,用于授权函数终结点的调用。In both instances, the code URL parameter is your unique function key that authorizes the invocation of your function endpoint.

将 publish 命令的输出中显示的完整“调用 URL”复制到浏览器的地址栏,并追加查询参数 &name=FunctionsCopy the complete Invoke URL shown in the output of the publish command into a browser address bar, appending the query parameter &name=Functions. 浏览器显示的输出应与本地运行函数时显示的输出类似。The browser should display similar output as when you ran the function locally.

在 Azure 上运行函数后浏览器中的输出

提示

若要查看已发布的函数应用的准实时日志,请使用 Application Insights 实时指标流To view near real-time logs for a published function app, use the Application Insights Live Metrics Stream.

运行以下命令,在浏览器中打开实时指标流。Run the following command to open the live metrics stream in a browser.

func azure functionapp logstream <APP_NAME> --browser

清理资源Clean up resources

若要继续执行下一步骤添加 Azure 存储队列输出绑定,请保留到目前为止构建的所有资源。If you continue to the next step, Add an Azure Storage queue output binding, keep all your resources in place as you'll build on what you've already done.

否则,请使用以下命令删除资源组及其包含的所有资源,以免产生额外的费用。Otherwise, use the following command to delete the resource group and all its contained resources to avoid incurring further costs.

az group delete --name AzureFunctionsQuickstart-rg
az group delete --name java-functions-group

后续步骤Next steps