快速入门:在 Azure 中通过命令行创建 Java 函数Quickstart: Create a Java function in Azure from the command line

在本文中,我们使用命令行工具创建一个响应 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.

备注

如果 Maven 不是你的首选开发工具,请查看面向使用 GradleIntelliJ IDEAVisual Studio Code 的 Java 开发人员的类似教程。If Maven is not your preferred 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:

先决条件检查Prerequisite check

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

  • 运行 az --version 以检查 Azure CLI 版本是否为 2.4 或更高版本。Run az --version to check that the Azure CLI version is 2.4 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.

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

    mvn archetype:generate -DarchetypeGroupId=com.microsoft.azure -DarchetypeArtifactId=azure-functions-archetype -DjavaVersion=8
    

    重要

    • 如果希望函数在 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.
  2. 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.
  3. 键入 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.

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

    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.

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

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

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, linux or docker-->
                        <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 中创建资源的方式,可以更改这些设置,例如,在初始部署之前将 runtime.oswindows 更改为 linuxYou can change these settings to control how resources are created in Azure, such as by changing runtime.os from windows to linux before initial deployment. 有关 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.

在本地运行函数Run the function locally

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

    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.

  2. 将此输出中 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.

  3. 完成后,请按 Ctrl+C 并选择 y 以停止函数主机 。When you're done, use Ctrl+C and choose y to stop the functions host.

将函数项目部署到 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.

提示

若要创建在 Linux 而不是 Windows 上运行的函数应用,请将 pom.xml 文件中的 runtime.os 元素从 windows 更改为 linuxTo create a function app running on Linux instead of Windows, change the runtime.os element in the pom.xml file from windows to linux. 这些区域支持在消耗计划中运行 Linux。Running Linux in a consumption plan is supported in these regions. 不能在同一个资源组中同时创建在 Linux 上运行的应用和在 Windows 上运行的应用。You can't have apps that run on Linux and apps that run on Windows in the same resource group.

  1. 在部署之前,请使用 Azure CLI 或 Azure PowerShell 登录到 Azure 订阅。Before you can deploy, sign in to your Azure subscription using either Azure CLI or Azure PowerShell.

    az login
    

    使用 az login 命令登录到 Azure 帐户。The az login command signs you into your Azure account.

  2. 使用以下命令将项目部署到新的函数应用。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.

将 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.

运行以下命令以查看准实时流式处理日志Run the following command to view near real-time streaming logs:

func azure functionapp logstream <APP_NAME> 

在单独的终端窗口或浏览器中,再次调用远程函数。In a separate terminal window or in the browser, call the remote function again. 终端中显示了 Azure 中函数执行的详细日志。A verbose log of the function execution in Azure is shown in the terminal.

清理资源Clean up resources

若要继续执行下一步并添加 Azure 存储队列输出绑定,请保留所有资源,以备将来使用。If you continue to the next step and 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 java-functions-group

后续步骤Next steps