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

快速入门:使用 Java 创建函数并将其发布到 Azure FunctionsQuickstart: Use Java to create and publish a function to Azure Functions

本文将介绍如何使用 Maven 命令行工具生成 Java 函数并将该函数发布到 Azure Functions。This article instructs you how to build and publish a Java function to Azure functions with the Maven command-line tool. 完成后,你的函数代码将在 Azure 中的使用计划上运行,并可使用 HTTP 请求触发。When you're done, your function code runs on the Consumption Plan in Azure and can be triggered using an HTTP request.

如果还没有 Azure 订阅,可以在开始前创建一个免费帐户If you don't have an Azure subscription, create a free account before you begin.

先决条件Prerequisites

若要使用 Java 开发函数,必须安装以下软件:To develop functions using Java, you must have the following installed:

重要

JAVA_HOME 环境变量必须设置为 JDK 的安装位置,以完成本快速入门。The JAVA_HOME environment variable must be set to the install location of the JDK to complete this quickstart.

生成新的 Functions 项目Generate a new Functions project

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

Linux/macOSLinux/macOS

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

备注

如果在运行命令时遇到问题,请看看使用了什么 maven-archetype-plugin 版本。If you're experiencing issues with running the command, take a look at what maven-archetype-plugin version is used. 由于你是在空的没有 .pom 文件的目录中运行该命令,因此它会尝试使用 ~/.m2/repository/org/apache/maven/plugins/maven-archetype-plugin 中的旧版插件(如果你从旧版升级了 Maven)。Because you are running the command in an empty directory with no .pom file, it might be attempting to use a plugin of the older version from ~/.m2/repository/org/apache/maven/plugins/maven-archetype-plugin if you upgraded your Maven from an older version. 如果是这样,请尝试删除 maven-archetype-plugin 目录并重新运行命令。If so, try deleting the maven-archetype-plugin directory and re-running the command.

WindowsWindows

mvn archetype:generate `
    "-DarchetypeGroupId=com.microsoft.azure" `
    "-DarchetypeArtifactId=azure-functions-archetype"
mvn archetype:generate ^
    "-DarchetypeGroupId=com.microsoft.azure" ^
    "-DarchetypeArtifactId=azure-functions-archetype"

Maven 会请求你提供所需的值以完成项目的生成。Maven will ask you for values needed to finish generating the project. 有关 groupId 、artifactId 和 version 值,请参阅 Maven 命名约定参考。For groupId, artifactId, and version values, see the Maven naming conventions reference. AppName 值在 Azure 中必须唯一,以便 Maven 基于以前输入的 artifactId 生成默认应用名称。The appName value must be unique across Azure, so Maven generates an app name based on the previously entered artifactId as a default. PackageName 值确定所生成函数代码的 Java 包。The packageName value determines the Java package for the generated function code.

下面的 com.fabrikam.functionsfabrikam-functions 标识符用作示例,目的是使本快速入门中后面的步骤更易读。The com.fabrikam.functions and fabrikam-functions identifiers below are used as an example and to make later steps in this quickstart easier to read. 建议你在此步骤中向 Maven 提供你自己的值。You are encouraged to supply your own values to Maven in this step.

Define value for property 'groupId' (should match expression '[A-Za-z0-9_\-\.]+'): com.fabrikam.functions
Define value for property 'artifactId' (should match expression '[A-Za-z0-9_\-\.]+'): fabrikam-functions
Define value for property 'version' 1.0-SNAPSHOT : 
Define value for property 'package': com.fabrikam.functions
Define value for property 'appName' fabrikam-functions-20170927220323382:
Define value for property 'appRegion' westus: :
Define value for property 'resourceGroup' java-functions-group: :
Confirm properties configuration: Y

在此示例 fabrikam-functions 中,Maven 在新文件夹中创建名为 artifactId 的项目文件Maven creates the project files in a new folder with a name of artifactId, in this example fabrikam-functions. 项目中生成的准备运行代码是一个 HTTP 触发的函数,该函数回显请求正文。The ready to run generated code in the project is an HTTP triggered function that echoes the body of the request. 将 src/main/java/com/fabrikam/functions/Function.java 替换为以下代码 :Replace src/main/java/com/fabrikam/functions/Function.java with the following code:

package com.fabrikam.functions;

import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;

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

        // Parse query parameter
        String query = request.getQueryParameters().get("name");
        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();
        }
    }
}

启用扩展捆绑包Enable extension bundles

安装绑定扩展的最简单方法是启用扩展捆绑包The easiest way to install binding extensions is to enable extension bundles. 启用捆绑包时,会自动安装一组预定义的扩展包。When you enable bundles, a predefined set of extension packages is automatically installed.

若要启用扩展捆绑包,请打开 host.json 文件并更新其内容以匹配以下代码:To enable extension bundles, open the host.json file and update its contents to match the following code:

{
    "version": "2.0",
    "extensionBundle": {
        "id": "Microsoft.Azure.Functions.ExtensionBundle",
        "version": "[1.*, 2.0.0)"
    }
}

在本地运行函数Run the function locally

将目录更改为新创建的项目文件夹(包含 host.json 和 pom.xml 文件的文件夹),并通过 Maven 生成并运行此函数:Change directory to the newly created project folder (the one containing your host.json and pom.xml files) and build and run the function with Maven:

cd fabrikam-function
mvn clean package 
mvn azure-functions:run

备注

如果在使用 Java 9 时遇到 javax.xml.bind.JAXBException 异常,请参阅 GitHub 上的解决方法。If you're experiencing this exception: javax.xml.bind.JAXBException with Java 9, see the workaround on GitHub.

当函数在本地系统上运行并且做好响应 HTTP 请求的准备时,将显示以下输出:You see this output when the function is running locally on your system and ready to respond to HTTP requests:

Listening on http://localhost:7071
Hit CTRL-C to exit...

Http Functions:

   hello: http://localhost:7071/api/HttpTrigger-Java

使用 curl 在新的终端窗口中从命令行触发函数:Trigger the function from the command line using curl in a new terminal window:

curl -w "\n" http://localhost:7071/api/HttpTrigger-Java -d LocalFunction
Hello LocalFunction!

在终端中使用 Ctrl-C 停止函数代码。Use Ctrl-C in the terminal to stop the function code.

将函数部署到 AzureDeploy the function to Azure

部署到 Azure Functions 的过程中会使用 Azure CLI 中的帐户凭据。The deploy process to Azure Functions uses account credentials from the Azure CLI. 在继续操作之前使用 Azure CLI 登录Sign in with the Azure CLI before continuing.

az login

使用 azure-functions:deploy Maven 目标将代码部署到新的函数应用。Deploy your code into a new Function app using the azure-functions:deploy Maven target. 这将执行一个启用了“从包运行”模式的 Zip 部署This performs a Zip Deploy with Run From Package mode enabled.

备注

使用 Visual Studio Code 来部署函数应用时,请记住选择非免费的订阅,否则会出现错误。When you use Visual Studio Code to deploy your Function app, remember to choose a non-free subscription, or you will get an error. 可以在 IDE 的左侧观察订阅。You can watch your subscription on the left side of the IDE.

mvn azure-functions:deploy

部署完成后,将显示可用于访问你的 Azure 函数应用的 URL:When the deploy is complete, you see the URL you can use to access your Azure function app:

[INFO] Successfully deployed Function App with package.
[INFO] Deleting deployment package from Azure Storage...
[INFO] Successfully deleted deployment package fabrikam-function-20170920120101928.20170920143621915.zip
[INFO] Successfully deployed Function App at https://fabrikam-function-20170920120101928.azurewebsites.net
[INFO] ------------------------------------------------------------------------

使用 cURL 测试在 Azure 上运行的函数应用。Test the function app running on Azure using cURL. 需更改以下示例中的 URL,使之与前一步骤中你自己的函数应用的已部署 URL 匹配。You'll need to change the URL from the sample below to match the deployed URL for your own function app from the previous step.

备注

确保将“访问权限” 设置为 AnonymousMake sure you set the Access rights to Anonymous. 选择默认级别 Function 时,需要在请求中提供函数密钥才能访问函数终结点。When you choose the default level of Function, you are required to present the function key in requests to access your function endpoint.

curl -w "\n" https://fabrikam-function-20170920120101928.azurewebsites.net/api/HttpTrigger-Java -d AzureFunctions
Hello AzureFunctions!

进行更改并重新部署Make changes and redeploy

编辑生成的项目中的 src/main.../Function.java 源文件来更改你的函数应用返回的文本。Edit the src/main.../Function.java source file in the generated project to alter the text returned by your Function app. 更改以下行:Change this line:

return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();

更改为以下内容:To the following:

return request.createResponseBuilder(HttpStatus.OK).body("Hi, " + name).build();

保存更改。Save the changes. 运行 mvn 清理包,如以前一样通过从终端运行 azure-functions:deploy 进行重新部署。Run mvn clean package and redeploy by running azure-functions:deploy from the terminal as before. 函数应用将更新,并且以下请求:The function app will be updated and this request:

curl -w '\n' -d AzureFunctionsTest https://fabrikam-functions-20170920120101928.azurewebsites.net/api/HttpTrigger-Java

将具有更新的输出:Will have updated output:

Hi, AzureFunctionsTest

后续步骤Next steps

你已使用简单的 HTTP 触发器创建 Java 函数应用,并将其部署到 Azure Functions。You have created a Java function app with a simple HTTP trigger and deployed it to Azure Functions.