使用 Java 和 Maven 创建你的第一个函数Create your first function with Java and Maven

本文将指导你使用 Maven 命令行工具生成 Java 函数并将该函数发布到 Azure Functions。This article guides you through using the Maven command line tool to build and publish a Java function to Azure Functions. 完成后,你的函数代码将在 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 trial account before you begin.

先决条件Prerequisites

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

Important

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 

Note

如果在运行命令时遇到问题,请看看使用了什么 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': com.fabrikam.functions
Define value for property 'artifactId' : 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:
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 a simple HTTP triggered function that echoes the body of the request:

public class Function {
    /**
     * This function listens at endpoint "/api/hello". Two ways to invoke it using "curl" command in bash:
     * 1. curl -d "HTTP Body" {your host}/api/hello
     * 2. curl {your host}/api/hello?name=HTTP%20Query
     */
    @FunctionName("hello")
    public HttpResponseMessage<String> hello(
            @HttpTrigger(name = "req", methods = {"get", "post"}, authLevel = AuthorizationLevel.ANONYMOUS) 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.createResponse(400, "Please pass a name on the query string or in the request body");
        } else {
            return request.createResponse(200, "Hello, " + name);
        }
    }
}

在本地运行函数Run the function locally

将目录更改为新创建的项目文件夹,并通过 Maven 生成和运行此函数:Change directory to the newly created project folder and build and run the function with Maven:

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

Note

如果在使用 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/hello

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

curl -w '\n' -d LocalFunction http://localhost:7071/api/hello
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 登录Log 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.

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.chinacloudsites.cn
[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.

Note

确保将“访问权限”设置为 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.chinacloudsites.cn/api/hello -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.createResponse(200, "Hello, " + name);

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

return request.createResponse(200, "Hi, " + name);

保存更改,如以前一样通过从终端运行 azure-functions:deploy 进行重新部署。Save the changes 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.chinacloudsites.cn/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.