使用 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 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 原型 (英文) 產生 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 檔案的空目錄中執行命令,如果您從舊版升級 Maven,則可能會嘗試使用來自 ~/.m2/repository/org/apache/maven/plugins/maven-archetype-plugin 的舊版外掛程式。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. 如需 groupIdartifactIdversion 值,請參閱 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

Maven 會以 artifactId 名稱在新資料夾中建立專案檔案,在此例中為 fabrikam-functionsMaven 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.javaReplace 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/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 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
        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

將目錄變更為新建立的專案資料夾,並且使用 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

注意

如果您遇到下列例外狀況:使用 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" http://localhost:7071/api/hello -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/hello -d AzureFunctions
Hello AzureFunctions!

進行變更並重新部署Make changes and redeploy

在產生的專案中編輯 src/main.../Function.java 來源檔案,以改變您的 Function 應用程式所傳回的文字。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);

儲存變更。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/hello

將有經更新的輸出: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.