你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:从命令行在 Azure 中创建函数

本文使用本地命令行工具创建响应 HTTP 请求的函数。 在本地验证代码后,将其部署到 Azure Functions 中的无服务器 Flex Consumption 托管计划。

完成本快速入门时会从你的 Azure 帐户中扣取小额费用,大约几美分或者更少。

确保在文章顶部选择喜欢的开发语言。

Important

Azure Functions 对 Go 的支持目前处于公共预览阶段。 在预览期间,Go 函数应用仅在 Flex Consumption 计划中受支持。

Prerequisites

  • 使用 rustup的 Rust 工具链。 可以使用 rustc --version 命令检查你的版本。

安装 Azure Functions Core Tools

建议的 Core Tools 安装方法取决于本地开发计算机的操作系统。

以下步骤使用 Windows 安装程序 (MSI) 安装 Core Tools v4.x。 若要详细了解其他基于包的安装程序,请参阅 Core Tools 自述文件

基于Windows 版本下载并运行 Core Tools 安装程序:

如果之前使用 Windows 安装程序 (MSI) 在 Windows 上安装 Core Tools,则应在安装最新版本之前从“添加/移除程序”中卸载旧版本。

小窍门

若要在 适用于 Linux 的 Windows 子系统上安装 Core Tools(WSL),请按照 Linux 选项卡上的说明进行作。

创建并激活虚拟环境

在适当的文件夹中,运行以下命令以创建并激活一个名为 .venv 的虚拟环境。 确保使用 Azure Functions 支持的 Python 版本之一。

python -m venv .venv
source .venv/bin/activate

如果 Python 未在 Linux 分发版中安装 venv 包,请运行以下命令:

sudo apt-get install python3-venv

所有后续命令将在这个已激活的虚拟环境中运行。

创建本地代码项目和函数

在 Azure Functions 中,代码项目是一个应用程序,其中包含一个或多个各自响应特定触发器的独立函数。 项目中的所有函数共享相同的配置,并将其部署为单元到 Azure。 在本部分中,将创建一个包含单个函数的代码项目。

  1. func init运行命令以创建 Go 函数项目:

    func init MyGoFunctionApp --worker-runtime go
    

    此命令创建一 MyGoFunctionApp 个名为包含以下文件的项目文件夹:

    文件 Description
    host.json 函数应用的主机配置。
    local.settings.json 在本地运行时使用的设置。
    main.go 包含示例 HTTP 触发器函数的入口点。
    go.mod 用于依赖项管理的 Go 模块文件。
    go.sum Go 模块校验和文件。
  2. 导航到项目文件夹:

    cd MyGoFunctionApp
    
  3. 打开 main.go 以查看生成的代码。 它包含示例 HTTP 触发的函数:

    package main
    
    import (
        "log"
        "net/http"
    
        "github.com/azure/azure-functions-golang-worker/sdk"
        "github.com/azure/azure-functions-golang-worker/worker"
    )
    
    // HTTPTriggerHandler handles standard HTTP requests
    func HTTPTriggerHandler(w http.ResponseWriter, r *http.Request) {
        log.Printf("Processing HTTP Trigger for %s", r.URL.Path)
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("Hello from Go Worker!"))
    }
    
    func main() {
        app := sdk.FunctionApp()
        app.HTTP("hello", HTTPTriggerHandler,
            sdk.WithMethods("GET", "POST"),
            sdk.WithAuth("anonymous"),
        )
        worker.Start(app)
    }
    

    Go 函数对 HTTP 触发器使用标准 net/http 类型(http.ResponseWriter*http.Request)。 函数通过 Go worker SDK 和函数式选项在 main() 中注册,无需 function.json 文件。

  1. 在终端或命令提示符下,运行以下命令 func init 以在当前文件夹中创建函数应用项目:

    func init --worker-runtime dotnet-isolated 
    
  1. 在终端或命令提示符下,运行以下命令 func init 以在当前文件夹中创建函数应用项目:

    func init --worker-runtime node --language javascript 
    
  1. 在终端或命令提示符下,运行以下命令 func init 以在当前文件夹中创建函数应用项目:

    func init --worker-runtime powershell 
    
  1. 在终端或命令提示符下,运行以下命令 func init 以在当前文件夹中创建函数应用项目:

    func init --worker-runtime python 
    
  1. 在终端或命令提示符下,运行以下命令 func init 以在当前文件夹中创建函数应用项目:

    func init --worker-runtime node --language typescript 
    
  1. 在终端或命令提示符下,运行以下命令 func init 以在当前文件夹中创建函数应用项目:

    func init --worker-runtime custom 
    
  1. 在空文件夹中,运行以下命令 mvn ,从 Azure Functions Maven 原型生成代码项目:

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

    Important

    • 如果希望函数在 Java 11 上运行,请使用 -DjavaVersion=11。 若要了解详细信息,请参阅 Java 版本
    • JAVA_HOME 环境变量设置为 JDK 的正确版本的安装位置以完成本文。
  2. Maven 会请求你提供所需的值,以在部署上完成项目的生成。
    系统提示时提供以下值:

    Prompt Value Description
    groupId com.fabrikam 一个值,用于按照 Java 的包命名规则在所有项目中标识你的项目。
    artifactId fabrikam-functions 一个值,该值是 jar 的名称,没有版本号。
    version 1.0-SNAPSHOT 选择默认值。
    package com.fabrikam 一个值,该值是所生成函数代码的 Java 包。 使用默认值。
  3. 键入 Y 或按 Enter 进行确认。

    Maven 在一个名为artifactId的新文件夹中创建项目文件,在本示例中是fabrikam-functions

  4. 导航到项目文件夹:

    cd fabrikam-functions
    

    可以在 \src\main\java\com\fabrikam 项目目录中的 Function.java中查看新 HTTP 触发器函数的模板生成代码。

  1. func new使用此命令将函数添加到项目:

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

    新代码文件将添加到项目中。 在这种情况下,该 --name 参数是函数的唯一名称(HttpExample),参数 --template 指定 HTTP 触发器。

项目根文件夹包含项目的各种文件,包括名为 local.settings.jsonhost.json的配置文件。 由于 local.settings.json 可以包含从 Azure 下载的机密,因此该文件在 .gitignore 文件中默认从源代码管理中排除。

创建和生成函数

HttpExample 文件夹中的 function.json 文件声明 HTTP 触发器函数 。 可以通过添加处理程序并将其编译为可执行文件来完成该函数。

  1. Ctrl + Shift + ` 或在“终端”菜单中选择“新建终端”,在 VS Code 中打开新的集成终端 。

  2. 在函数应用根文件夹(host.json 所在的文件夹)中,初始化名为 的 Rust 项目handler

    cargo init --name handler
    
  3. 在 Cargo.toml 中,添加完成本快速入门所需的以下依赖关系。 该示例使用 warp Web 服务器框架。

    [dependencies]
    warp = "0.3"
    tokio = { version = "1", features = ["rt", "macros", "rt-multi-thread"] }
    
  4. 在 src/main.rs 中,添加以下代码并保存文件。 这就是 Rust 自定义处理程序。

    use std::collections::HashMap;
    use std::env;
    use std::net::Ipv4Addr;
    use warp::{http::Response, Filter};
    
    #[tokio::main]
    async fn main() {
        let example1 = warp::get()
            .and(warp::path("api"))
            .and(warp::path("HttpExample"))
            .and(warp::query::<HashMap<String, String>>())
            .map(|p: HashMap<String, String>| match p.get("name") {
                Some(name) => Response::builder().body(format!("Hello, {}. This HTTP triggered function executed successfully.", name)),
                None => Response::builder().body(String::from("This HTTP triggered function executed successfully. Pass a name in the query string for a personalized response.")),
            });
    
        let port_key = "FUNCTIONS_CUSTOMHANDLER_PORT";
        let port: u16 = match env::var(port_key) {
            Ok(val) => val.parse().expect("Custom Handler port is not a number!"),
            Err(_) => 3000,
        };
    
        warp::serve(example1).run((Ipv4Addr::LOCALHOST, port)).await
    }
    
  5. 为自定义处理程序编译二进制文件。 函数应用的根文件夹中会输出名为 handler(对于 Windows,则为 handler.exe)的可执行文件。

    cargo build --release
    cp target/release/handler .
    

配置函数应用

函数主机需配置为在启动时运行自定义处理程序二进制文件。

  1. 打开 host.json

  2. customHandler.description 部分中,将 defaultExecutablePath 的值设置为 handler(对于 Windows,则将其设置为 handler.exe)。

  3. customHandler 部分中,添加名为 enableForwardingHttpRequest 的属性并将其值设置为 true。 对于仅包含 HTTP 触发器的函数,通过此设置可处理典型的 HTTP 请求(而不是自定义处理程序请求有效负载),从而简化编程。

  4. 确认 customHandler 部分是否如以下示例所示。 保存文件。

    "customHandler": {
      "description": {
        "defaultExecutablePath": "handler",
        "workingDirectory": "",
        "arguments": []
      },
      "enableForwardingHttpRequest": true
    }
    

将函数应用配置为启动自定义处理程序可执行文件。

在本地运行函数

在本地运行项目并调用函数终结点来验证新函数。

  1. 使用此命令启动项目文件夹根目录中的本地 Azure Functions 运行时主机:

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

    在输出末尾,将显示以下行:

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

    在输出结束时,将显示函数的 HTTP 终结点:

     Functions:
    
             hello: [GET,POST] http://localhost:7071/api/hello
     
  2. 调用函数终结点以验证其是否正常工作:

    HttpExample 函数的 URL 从此输出复制到浏览器,并浏览到此函数 URL。 你应该会收到一条包含“hello world”消息的成功响应。

    Note

    由于在本地运行时不会强制实施访问密钥授权,因此返回的函数 URL 不包括访问密钥值,并且不需要它调用函数。

    在本地运行函数后,打开浏览器并导航到以下 URL:

    http://localhost:7071/api/hello
    

    应会看到以下响应:

    Hello from Go Worker!
    
  3. 完成后,使用 Ctrl+C 并选择 y 停止函数主机。

创建函数的支持性 Azure 资源

在将函数代码部署到 Azure 之前,需要创建以下资源:

  • 一个资源组:相关资源的逻辑容器。
  • 函数宿主使用的默认 存储帐户,用于维护有关函数的状态和其他信息。
  • 用户分配的托管标识,Functions 主机使用该标识连接到默认存储帐户。
  • 一个函数应用:提供用于执行函数代码的环境。 函数应用映射到本地函数项目,可让你将函数分组为一个逻辑单元,以便更轻松地管理、部署和共享资源。

使用这些步骤中的 Azure CLI 命令创建所需的资源。

  1. 请登录到 Azure(如果尚未这样做):

    az login
    

    使用 az login 命令登录到 Azure 帐户。 在 Azure Cloud Shell 中运行时跳过此步骤。

  2. 如果尚未这样做,请使用 az extension add 此命令安装 Application Insights 扩展:

    az extension add --name application-insights
    
  3. 使用此 az group create 命令创建在所选区域中命名 AzureFunctionsQuickstart-rg 的资源组:

    az group create --name "AzureFunctionsQuickstart-rg" --location "<REGION>"
    

    在此示例中,将 <REGION> 替换为支持 Flex 消耗计划的附近区域。 使用 az functionapp list-flexconsumption-locations 命令查看当前支持的区域的列表。

  4. 使用此 az storage account create 命令在资源组和区域中创建常规用途存储帐户:

    az storage account create --name <STORAGE_NAME> --location "<REGION>" --resource-group "AzureFunctionsQuickstart-rg" \
    --sku "Standard_LRS" --allow-blob-public-access false --allow-shared-key-access false
    

    在此示例中,请将 <STORAGE_NAME> 替换为适合你且在 Azure 存储中唯一的名称。 名称只能包含 3 到 24 个数字和小写字母字符。 Standard_LRS 指定 Functions 支持的常规用途帐户。 只能通过使用已向特定资源授予权限的Microsoft Entra 身份验证标识来访问此新帐户。

  5. 使用此脚本创建一个用户分配的托管标识,解析jq对象返回的JSON属性,并在默认存储帐户中授予Storage Blob Data Owner权限:

    output=$(az identity create --name "func-host-storage-user" --resource-group "AzureFunctionsQuickstart-rg" --location <REGION> \
    --query "{userId:id, principalId: principalId, clientId: clientId}" -o json)
    
    userId=$(echo $output | jq -r '.userId')
    principalId=$(echo $output | jq -r '.principalId')
    clientId=$(echo $output | jq -r '.clientId')
    
    storageId=$(az storage account show --resource-group "AzureFunctionsQuickstart-rg" --name <STORAGE_NAME> --query 'id' -o tsv)
    az role assignment create --assignee-object-id $principalId --assignee-principal-type ServicePrincipal \
    --role "Storage Blob Data Owner" --scope $storageId
    

    如果本地 Bash shell 中没有该 jq 实用工具,则它在 Azure Cloud Shell 中可用。 在此示例中,将 <STORAGE_NAME> 替换为您的默认存储帐户名称,将 <REGION> 替换为您的默认区域。

    az identity create 命令创建一个名为 func-host-storage-user 的标识。 返回的权限 principalId 用于使用 az role assignment create 命令将权限分配给默认存储帐户中的此新标识。 该 az storage account show 命令用于获取存储帐户 ID。

  6. 使用此 az functionapp create 命令在 Azure 中创建函数应用:

    az functionapp create --resource-group "AzureFunctionsQuickstart-rg" --name <APP_NAME> --flexconsumption-location <REGION> \
    --runtime dotnet-isolated --runtime-version <LANGUAGE_VERSION> --storage-account <STORAGE_NAME> \
    --deployment-storage-auth-type UserAssignedIdentity --deployment-storage-auth-value "func-host-storage-user"
    
    az functionapp create --resource-group "AzureFunctionsQuickstart-rg" --name <APP_NAME> --flexconsumption-location <REGION> \
    --runtime java --runtime-version <LANGUAGE_VERSION> --storage-account <STORAGE_NAME> \
    --deployment-storage-auth-type UserAssignedIdentity --deployment-storage-auth-value "func-host-storage-user"
    
    az functionapp create --resource-group "AzureFunctionsQuickstart-rg" --name <APP_NAME> --flexconsumption-location <REGION> \
    --runtime node --runtime-version <LANGUAGE_VERSION> --storage-account <STORAGE_NAME> \
    --deployment-storage-auth-type UserAssignedIdentity --deployment-storage-auth-value "func-host-storage-user"
    
    az functionapp create --resource-group "AzureFunctionsQuickstart-rg" --name <APP_NAME> --flexconsumption-location <REGION> \
    --runtime python --runtime-version <LANGUAGE_VERSION> --storage-account <STORAGE_NAME> \
    --deployment-storage-auth-type UserAssignedIdentity --deployment-storage-auth-value "func-host-storage-user"
    
    az functionapp create --resource-group "AzureFunctionsQuickstart-rg" --name <APP_NAME> --flexconsumption-location <REGION> \
    --runtime python --runtime-version <LANGUAGE_VERSION> --storage-account <STORAGE_NAME> \
    --deployment-storage-auth-type UserAssignedIdentity --deployment-storage-auth-value "func-host-storage-user"
    
    az functionapp create --resource-group "AzureFunctionsQuickstart-rg" --name <APP_NAME> --flexconsumption-location <REGION> \
    --runtime other --storage-account <STORAGE_NAME> \
    --deployment-storage-auth-type UserAssignedIdentity --deployment-storage-auth-value "func-host-storage-user"
    

    在此示例中,将这些占位符替换为相应的值:

    • <APP_NAME>:适合你的全球唯一名称。 <APP_NAME> 也是函数应用的默认 DNS 域。
    • <STORAGE_NAME>:上一步中使用的帐户的名称。
    • <REGION>:当前区域。
    • <LANGUAGE_VERSION>:使用在本地验证的相同 支持的语言堆栈版本 (如果适用)。

    此命令创建一个函数应用,该应用在 Linux 上的 Flex 消耗计划中指定的语言运行时中运行,根据本教程产生的用量,此操作是免费的。 该命令还会在同一资源组中创建关联的 Azure 应用程序 Insights 实例,可用于监视函数应用执行和查看日志。 有关详细信息,请参阅监视 Azure Functions。 该实例在激活之前不会产生费用。

  7. 使用此脚本将用户分配的托管标识添加到 Application Insights 实例中的 “监视指标发布者 ”角色:

    appInsights=$(az monitor app-insights component show --resource-group "AzureFunctionsQuickstart-rg" \
        --app <APP_NAME> --query "id" --output tsv)
    principalId=$(az identity show --name "func-host-storage-user" --resource-group "AzureFunctionsQuickstart-rg" \
        --query principalId -o tsv)
    az role assignment create --role "Monitoring Metrics Publisher" --assignee $principalId --scope $appInsights
    

    在本例中,将 <APP_NAME> 替换为函数应用名称。 az role assignment create 命令将用户添加到该角色。 Application Insights 实例的资源 ID 和用户的主体 ID 分别通过 az monitor app-insights component showaz identity show 命令获取。

更新应用程序设置

若要使 Functions 主机能够使用共享机密连接到默认存储帐户,请将 AzureWebJobsStorage 连接字符串设置替换为几个以 AzureWebJobsStorage__ 为前缀的设置。 这些设置定义了一个复杂的设置,你的应用使用该设置通过用户分配的托管标识连接到存储和 Application Insights。

  1. 使用此脚本获取用户分配的托管标识的客户端 ID,并使用它定义与存储和 Application Insights 的托管标识连接:

    clientId=$(az identity show --name func-host-storage-user \
        --resource-group AzureFunctionsQuickstart-rg --query 'clientId' -o tsv)
    az functionapp config appsettings set --name <APP_NAME> --resource-group "AzureFunctionsQuickstart-rg" \
        --settings AzureWebJobsStorage__accountName=<STORAGE_NAME> \
        AzureWebJobsStorage__credential=managedidentity AzureWebJobsStorage__clientId=$clientId \
        APPLICATIONINSIGHTS_AUTHENTICATION_STRING="ClientId=$clientId;Authorization=AAD"
    

    在此脚本中,将<APP_NAME><STORAGE_NAME>分别替换为您的函数应用和存储帐户的名称。

  2. 运行 az functionapp config appsettings delete 命令以删除包含共享密钥的现有 AzureWebJobsStorage 连接字符串设置:

    az functionapp config appsettings delete --name <APP_NAME> --resource-group "AzureFunctionsQuickstart-rg" --setting-names AzureWebJobsStorage
    

    在此示例中,将<APP_NAME>替换为函数应用的名称。

此时,Functions 主机可以使用托管标识而不是共享机密安全地连接到存储帐户。 现在可以将项目代码部署到 Azure 资源。

创建函数的支持性 Azure 资源

在将函数代码部署到Azure之前,需要创建资源组、存储帐户和函数应用。 使用这些步骤中的 Azure CLI 命令创建所需的资源。

  1. 请登录到 Azure(如果尚未这样做):

    az login
    

    使用 az login 命令登录到 Azure 帐户。 在 Azure Cloud Shell 中运行时跳过此步骤。

  2. az group create使用命令创建在所选区域中命名AzureFunctionsQuickstart-rg的资源组:

    az group create --name AzureFunctionsQuickstart-rg --location <REGION>
    

    在此示例中,将 <REGION> 替换为支持 Flex 消耗计划的附近区域。 az functionapp list-flexconsumption-locations使用命令查看当前支持的区域的列表。

  3. 使用 az storage account create 命令在资源组和区域中创建常规用途存储帐户:

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

    在此示例中,请将 <STORAGE_NAME> 替换为全局唯一的名称。 名称必须包含三到 24 个字符,并且只有小写字母和数字。

  4. 在Azure中创建函数应用:

    az functionapp create --resource-group AzureFunctionsQuickstart-rg --name <APP_NAME> --storage-account <STORAGE_NAME> --flexconsumption-location <REGION> --runtime go --runtime-version 1.0 --functions-version 4
    

    <APP_NAME> 替换为全局唯一名称,并将 <STORAGE_NAME> 替换为您在上一步中使用的帐户名称。 此命令还会在同一资源组中创建关联的 Azure 应用程序 Insights 实例,可以使用该实例监视函数应用并查看日志。 有关详细信息,请参阅监视 Azure Functions

  5. 在 Go 公开预览版期间,必须在函数应用中禁用 HTTP/2:

    az resource update --resource-group AzureFunctionsQuickstart-rg --resource-type Microsoft.Web/sites --name <APP_NAME> --set properties.siteConfig.http20Enabled=false
    

将函数项目部署到 Azure

在 Azure 中成功创建函数应用后,便可以使用 func azure functionapp publish 命令部署本地函数项目。

  1. 在根项目文件夹中,运行此 func azure functionapp publish 命令:

    func azure functionapp publish <APP_NAME>
    

    在此示例中,使用应用名称替代 <APP_NAME>。 成功的部署显示类似于以下输出的结果(为简洁起见,示例中的结果已截断):

     ...
    
     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.azurewebsites.net/api/httpexample
     
  2. 在本地终端或命令提示符中,运行以下命令以获取 URL 终结点值,包括访问密钥:

    func azure functionapp list-functions <APP_NAME> --show-keys
    

    在本例中,再次将 <APP_NAME> 替换为应用的名称。

  3. 复制返回的终结点 URL 和密钥,用于调用函数终结点。

更新 pom.xml 文件

在 Azure 中成功创建函数应用后,更新 pom.xml 文件,以便 Maven 可以部署到新应用。 否则,Maven 会在部署期间创建新的 Azure 资源集。

  1. 在 Azure Cloud Shell 中,使用 az functionapp show 此命令获取新用户分配的托管标识的部署容器 URL 和 ID:

    az functionapp show --name <APP_NAME> --resource-group AzureFunctionsQuickstart-rg  \
        --query "{userAssignedIdentityResourceId: properties.functionAppConfig.deployment.storage.authentication.userAssignedIdentityResourceId, \
        containerUrl: properties.functionAppConfig.deployment.storage.value}"
    

    在此示例中,将<APP_NAME>替换为函数应用的名称。

  2. 在项目根目录中,在文本编辑器中打开 pom.xml 文件,找到 properties 元素并更新这些特定的属性值:

    属性名称 Value
    java.version 使用本地验证的相同 支持的语言堆栈版本 ,例如 17
    azure.functions.maven.plugin.version 1.37.1
    azure.functions.java.library.version 3.1.0
    functionAppName Azure 中函数应用的名称。
  3. 请找到configuration部分中的azure-functions-maven-plugin,并将其替换为以下 XML 片段:

    <configuration>
        <appName>${functionAppName}</appName>
        <resourceGroup>AzureFunctionsQuickstart-rg</resourceGroup>
        <pricingTier>Flex Consumption</pricingTier>
        <region>....</region>
        <runtime>
            <os>linux</os>
            <javaVersion>${java.version}</javaVersion>
        </runtime>
        <deploymentStorageAccount>...</deploymentStorageAccount>
        <deploymentStorageResourceGroup>AzureFunctionsQuickstart-rg</deploymentStorageResourceGroup>
        <deploymentStorageContainer>...</deploymentStorageContainer>
        <storageAuthenticationMethod>UserAssignedIdentity</storageAuthenticationMethod>
        <userAssignedIdentityResourceId>...</userAssignedIdentityResourceId>
        <appSettings>
            <property>
                <name>FUNCTIONS_EXTENSION_VERSION</name>
                <value>~4</value>
            </property>
        </appSettings>
    </configuration>
    
  4. 在新的 configuration 元素中,将这些省略号 (...) 值进行以下特定替换:

    Configuration Value
    region 现有函数应用的区域代码,例如 eastus
    deploymentStorageAccount 存储帐户的名称。
    deploymentStorageContainer 部署共享的名称,该共享位于你获得的 \ 值中的 containerUrl 之后。
    userAssignedIdentityResourceId 你获取的托管标识的完全限定的资源 ID。
  5. 保存对 pom.xml 文件的更改。

现在可以使用 Maven 将代码项目部署到现有应用。

将函数项目部署到 Azure

  1. 从命令提示符中,运行此命令:

    mvn clean package azure-functions:deploy
    
  2. 部署成功后,运行此 Core Tools 命令以获取 URL 终结点值,包括访问密钥:

    func azure functionapp list-functions <APP_NAME> --show-keys
    

    在本例中,再次将 <APP_NAME> 替换为应用的名称。

  3. 复制返回的终结点 URL 和密钥,用于调用函数终结点。

将函数项目部署到 Azure

在 Azure 中成功创建函数应用后,即可部署本地函数项目。 使用 func azure functionapp publish 命令将项目部署到Azure:

func azure functionapp publish <APP_NAME>

<APP_NAME> 替换为你的函数应用的名称。

在 Azure 上调用函数

由于函数使用 HTTP 触发器并支持 GET 请求,因此使用函数级访问密钥向其 URL 发出 HTTP 请求来调用它。 最简单的方法是在浏览器中执行 GET 请求。

将复制的 URL 和访问密钥粘贴到浏览器地址栏中。

终结点 URL 应类似于以下示例:

https://contoso-app.azurewebsites.net/api/httpexample?code=aabbccdd...

在这种情况下,在向终结点 URL 发出 GET 请求时,还必须在查询字符串中提供访问密钥。 建议使用访问密钥来限制来自随机客户端的访问。 使用 HTTP 客户端发出 POST 请求时,应改为在 x-functions-key 标头中提供访问密钥。

导航到此 URL 时,浏览器显示的输出应与在本地运行函数时显示的输出类似。

在 Azure 上调用函数

部署完成后,在浏览器中打开以下 URL 以验证函数是否在Azure中运行:

https://<APP_NAME>.azurewebsites.net/api/hello

应会看到在本地运行函数时看到的相同 Hello from Go Worker! 响应。

清理资源

若要继续执行下一步并添加 Azure 存储队列输出绑定,请保留所有资源,以备将来使用。

否则,请使用以下命令删除资源组及其包含的所有资源,以免产生额外的费用。

az group delete --name AzureFunctionsQuickstart-rg

清理资源

如果您继续执行下一步,请保留所有资源,以便在已创建的基础上进行构建。

否则,请使用以下命令删除资源组及其包含的所有资源,以免产生额外的费用。

az group delete --name AzureFunctionsQuickstart-rg