Azure Functions 开发人员指南Azure Functions developer guide

在 Azure Functions 中,特定函数共享一些核心技术概念和组件,不受所用语言或绑定限制。In Azure Functions, specific functions share a few core technical concepts and components, regardless of the language or binding you use. 跳转学习某个特定语言或绑定的详细信息之前,请务必通读此通用概述。Before you jump into learning details specific to a given language or binding, be sure to read through this overview that applies to all of them.

本文假定你已阅读 Azure Functions 概述This article assumes that you've already read the Azure Functions overview.

函数代码Function code

函数是 Azure Functions 的基本概念。A function is the primary concept in Azure Functions. 函数包含两个重要部分,即可以用各种语言编写的代码,以及一些配置,function.json 文件。A function contains two important pieces - your code, which can be written in a variety of languages, and some config, the function.json file. 对于编译语言,此配置文件是从代码中的注释自动生成的。For compiled languages, this config file is generated automatically from annotations in your code. 对于脚本语言,必须自己提供配置文件。For scripting languages, you must provide the config file yourself.

Function.json 文件定义函数触发器、绑定和其他配置设置。The function.json file defines the function's trigger, bindings, and other configuration settings. 每个函数有且只有一个触发器。Every function has one and only one trigger. 运行时使用此配置文件确定要监视的事件,以及如何将数据传入函数执行和从函数执行返回数据。The runtime uses this config file to determine the events to monitor and how to pass data into and return data from a function execution. 下面是一个示例 function.json 文件。The following is an example function.json file.

{
    "disabled":false,
    "bindings":[
        // ... bindings here
        {
            "type": "bindingType",
            "direction": "in",
            "name": "myParamName",
            // ... more depending on binding
        }
    ]
}

有关详细信息,请参阅 Azure Functions 触发器和绑定概念For more information, see Azure Functions triggers and bindings concepts.

bindings 属性配置两个触发器和绑定。The bindings property is where you configure both triggers and bindings. 每个绑定共享一些通用设置和一些特定于个别类型的绑定的设置。Each binding shares a few common settings and some settings which are specific to a particular type of binding. 每个绑定都需要以下设置:Every binding requires the following settings:

属性Property Values 类型Type 注释Comments
typetype 绑定名称。Name of binding.

例如,queueTriggerFor example, queueTrigger.
stringstring
directiondirection in, outin, out stringstring 表示绑定是用于接收数据到函数中或是从函数发送数据。Indicates whether the binding is for receiving data into the function or sending data from the function.
namename 函数标识符。Function identifier.

例如,myQueueFor example, myQueue.
stringstring 将用于函数中绑定数据的名称。The name that is used for the bound data in the function. 对于 C#,它将是参数名称;对于 JavaScript,它是键/值列表中的键。For C#, this is an argument name; for JavaScript, it's the key in a key/value list.

函数应用Function app

函数应用在 Azure 中提供用于运行函数的执行上下文。A function app provides an execution context in Azure in which your functions run. 因此,它是函数的部署和管理单元。As such, it is the unit of deployment and management for your functions. 函数应用由一个或多个共同管理、部署和缩放的独立函数组成。A function app is comprised of one or more individual functions that are managed, deployed, and scaled together. 函数应用中的所有函数共享相同的定价计划、部署方法和运行时版本。All of the functions in a function app share the same pricing plan, deployment method, and runtime version. 将函数应用视为组织和共同管理函数的一种方法。Think of a function app as a way to organize and collectively manage your functions. 若要了解详细信息,请参阅如何管理函数应用To learn more, see How to manage a function app.

备注

函数应用中的所有函数必须使用相同的语言编写。All functions in a function app must be authored in the same language. 在 Azure Functions 运行时的先前版本中,这不是必需的。In previous versions of the Azure Functions runtime, this wasn't required.

文件夹结构Folder structure

特定函数应用中所有函数的代码均位于根项目文件夹中,其中包含主机配置文件和一个或多个子文件夹。The code for all the functions in a specific function app is located in a root project folder that contains a host configuration file and one or more subfolders. 每个子文件夹包含单独函数的代码。Each subfolder contains the code for a separate function. 文件夹结构如下图所示:The folder structure is shown in the following representation:

FunctionApp
 | - host.json
 | - MyFirstFunction
 | | - function.json
 | | - ...  
 | - MySecondFunction
 | | - function.json
 | | - ...  
 | - SharedCode
 | - bin

在 2.x 版及更高版本的 Functions 运行时中,函数应用中的所有函数必须共享同一语言堆栈。In version 2.x and higher of the Functions runtime, all functions in the function app must share the same language stack.

host.json 文件包含特定于运行时的配置,并位于函数应用的根文件夹中。The host.json file contains runtime-specific configurations and is in the root folder of the function app. bin 文件夹包含函数应用所需的包和其他库文件。A bin folder contains packages and other library files that the function app requires. 查看函数应用项目的语言特定要求:See the language-specific requirements for a function app project:

以上是 Function app 的默认(和推荐)文件夹结构。The above is the default (and recommended) folder structure for a Function app. 如果要更改函数代码的文件位置,请修改 function.json 文件的 scriptFile 部分。If you wish to change the file location of a function's code, modify the scriptFile section of the function.json file. 我们还建议使用包部署将项目部署到 Azure 中的函数应用。We also recommend using package deployment to deploy your project to your function app in Azure.

备注

如果手动部署包,请确保将 host.json 文件和函数文件夹直接部署到 wwwroot 文件夹。If deploying a package manually, make sure to deploy your host.json file and function folders directly to the wwwroot folder. 请勿在部署中包含 wwwroot 文件夹。Do not include the wwwroot folder in your deployments. 否则,最后将得到 wwwroot\wwwroot 文件夹。Otherwise, you end up with wwwroot\wwwroot folders.

使用本地工具和发布Use local tools and publishing

可以使用各种工具创作和发布各种函数应用,包括 Visual StudioVisual Studio CodeIntelliJEclipseAzure Functions Core ToolsFunction apps can be authored and published using a variety of tools, including Visual Studio, Visual Studio Code, IntelliJ, Eclipse, and the Azure Functions Core Tools. 有关详细信息,请参阅在本地对 Azure Functions 进行编码和测试For more information, see Code and test Azure Functions locally.

如何编辑 Azure 门户中的函数How to edit functions in the Azure portal

通过 Azure 门户中内置的函数编辑器可直接内联更新代码和 function.json 文件。The Functions editor built into the Azure portal lets you update your code and your function.json file directly inline. 建议仅用于小的更改或概念证明 - 最佳做法是使用 VS Code 等本地开发工具。This is recommended only for small changes or proofs of concept - best practice is to use a local development tool like VS Code.

并行执行Parallel execution

多个触发事件发生的速度超过了单线程函数运行的处理速度时,运行时可并行多次调用函数。When multiple triggering events occur faster than a single-threaded function runtime can process them, the runtime may invoke the function multiple times in parallel. 如果 Function App 正在使用消耗量托管计划,则 Function App 可自动扩大。If a function app is using the Consumption hosting plan, the function app could scale out automatically. 无论应用是在消耗量托管计划还是常规应用服务托管计划上运行,每个 Function App 实例都可能使用多个线程并行处理并发函数调用。Each instance of the function app, whether the app runs on the Consumption hosting plan or a regular App Service hosting plan, might process concurrent function invocations in parallel using multiple threads. 每个 Function App 实例中并发函数的最大调用数根据所用触发器类型以及 Function App 中其他函数所用资源而有所不同。The maximum number of concurrent function invocations in each function app instance varies based on the type of trigger being used as well as the resources used by other functions within the function app.

Functions 运行时版本控制Functions runtime versioning

可使用 FUNCTIONS_EXTENSION_VERSION 应用设置配置 Functions 运行时的版本。You can configure the version of the Functions runtime using the FUNCTIONS_EXTENSION_VERSION app setting. 例如,值“~3”表示函数应用将使用 3.x 作为其主版本。For example, the value "~3" indicates that your function app will use 3.x as its major version. 函数应用在发布后,将升级到各个新的次要版本。Function apps are upgraded to each new minor version as they are released. 有关详细信息(包括如何查看函数应用的确切版本),请参阅如何针对 Azure Functions 运行时版本For more information, including how to view the exact version of your function app, see How to target Azure Functions runtime versions.

存储库Repositories

Azure Functions 代码为开放源,位于 GitHub 存储库:The code for Azure Functions is open source and stored in GitHub repositories:

绑定Bindings

下面是所有受支持的绑定表。Here is a table of all supported bindings.

下表显示了 Azure Functions 运行时的主版本支持的绑定:This table shows the bindings that are supported in the major versions of the Azure Functions runtime:

类型Type 1.x1.x 2.x 及更高版本12.x and higher1 触发器Trigger 输入Input 输出Output
Blob 存储Blob storage
Azure Cosmos DBAzure Cosmos DB
Dapr3Dapr3
事件网格Event Grid
事件中心Event Hubs
HTTP 和 WebhookHTTP & webhooks
IoT 中心IoT Hub
Kafka2Kafka2
移动应用Mobile Apps
通知中心Notification Hubs
队列存储Queue storage
RabbitMQ2RabbitMQ2
SendGridSendGrid
服务总线Service Bus
SignalRSignalR
表存储Table storage
计时器Timer

1 从版本 2.x 运行时开始,除了 HTTP 和 Timer 以外,所有绑定都必须注册。1 Starting with the version 2.x runtime, all bindings except HTTP and Timer must be registered. 请参阅注册绑定扩展See Register binding extensions.

2 消耗计划中不支持触发器。2 Triggers aren't supported in the Consumption plan. 需要运行时驱动的触发器Requires runtime-driven triggers.

3 仅支持 Kubernetes、IoT Edge 和其他自托管模式。3 Supported only in Kubernetes, IoT Edge, and other self-hosted modes only.

对来自绑定的错误怀有疑问?Having issues with errors coming from the bindings? 请查看 Azure Functions 绑定错误代码文档。Review the Azure Functions Binding Error Codes documentation.

连接Connections

函数项目从其配置提供程序按名称引用连接信息。Your function project references connection information by name from its configuration provider. 它不直接接受连接详细信息,而是允许跨环境对其进行更改。It does not directly accept the connection details, allowing them to be changed across environments. 例如,触发器定义可能包括 connection 属性。For example, a trigger definition might include a connection property. 这可能是指连接字符串,但不能直接在 function.json 中设置连接字符串。This might refer to a connection string, but you cannot set the connection string directly in a function.json. 相反,应将 connection 设置为包含连接字符串的环境变量的名称。Instead, you would set connection to the name of an environment variable that contains the connection string.

默认配置提供程序使用环境变量。The default configuration provider uses environment variables. 在 Azure Functions 服务中运行时,可以通过应用程序设置进行设置,而在本地开发时,可以通过本地设置文件进行设置。These might be set by Application Settings when running in the Azure Functions service, or from the local settings file when developing locally.

连接值Connection values

当连接名称解析为单个精确值时,运行时会将值标识为通常包含机密的连接字符串。When the connection name resolves to a single exact value, the runtime identifies the value as a connection string, which typically includes a secret. 连接字符串的详细信息由你要连接到的服务定义。The details of a connection string are defined by the service to which you wish to connect.

不过,连接名称还可以引用多个配置项目的集合。However, a connection name can also refer to a collection of multiple configuration items. 可以通过使用以双下划线 __ 结尾的共享前缀将环境变量视为集合。Environment variables can be treated as a collection by using a shared prefix that ends in double underscores __. 然后,可以通过将连接名称设置为此前缀来引用该组。The group can then be referenced by setting the connection name to this prefix.

例如,Azure Blob 触发器定义的 connection 属性可能是 Storage1For example, the connection property for a Azure Blob trigger definition might be Storage1. 只要没有名称配置为 Storage1 的单个字符串值,Storage1__serviceUri 就会用于连接的 serviceUri 属性。As long as there is no single string value configured with Storage1 as its name, Storage1__serviceUri would be used for the serviceUri property of the connection. 每个服务的连接属性各不相同。The connection properties are different for each service. 请参阅相关文档,了解使用连接的扩展。Refer to the documentation for the extension that uses the connection.

配置基于标识的连接Configure an identity-based connection

Azure Functions 中的某些连接配置为使用标识而不是机密。Some connections in Azure Functions are configured to use an identity instead of a secret. 支持取决于使用连接的扩展。Support depends on the extension using the connection. 在某些情况下,即使连接到的服务支持基于标识的连接,Functions 中仍可能需要连接字符串。In some cases, a connection string may still be required in Functions even though the service to which you are connecting supports identity-based connections.

重要

即使绑定扩展支持基于标识的连接,消耗计划中可能仍不支持该配置。Even if a binding extension supports identity-based connections, that configuration may not be supported yet in the Consumption plan. 请参阅下面的支持表。See the support table below.

以下触发器和绑定扩展支持基于标识的连接:Identity-based connections are supported by the following trigger and binding extensions:

扩展名称Extension name 扩展版本Extension version 在消耗计划中支持基于标识的连接Supports identity-based connections in the Consumption plan
Azure BlobAzure Blob 版本 5.0.0-beta1 或更高版本Version 5.0.0-beta1 or later No
Azure 队列Azure Queue 版本 5.0.0-beta1 或更高版本Version 5.0.0-beta1 or later No

备注

对于 Functions 运行时用于核心行为的存储连接,尚不支持基于标识的连接。Support for identity-based connections is not yet available for storage connections used by the Functions runtime for core behaviors. 这意味着 AzureWebJobsStorage 设置必须为连接字符串。This means that the AzureWebJobsStorage setting must be a connection string.

连接属性Connection properties

Azure 服务的基于标识的连接接受以下属性:An identity-based connection for an Azure service accepts the following properties:

属性Property 环境变量Environment variable 是否必需Is Required 说明Description
服务 URIService URI <CONNECTION_NAME_PREFIX>__serviceUri Yes 要连接到的服务的数据平面 URI。The data plane URI of the service to which you are connecting.

给定的连接类型可能支持其他选项。Additional options may be supported for a given connection type. 请参阅相关文档,了解用于建立连接的组件。Please refer to the documentation for the component making the connection.

在 Azure Functions 服务中托管时,基于标识的连接将使用托管标识When hosted in the Azure Functions service, identity-based connections use a managed identity. 默认情况下,使用系统分配的标识。The system-assigned identity is used by default. 在其他上下文(如本地开发)中运行时,将改用开发人员标识,尽管可以使用其他连接参数对其进行自定义。When run in other contexts, such as local development, your developer identity is used instead, although this can be customized using alternative connection parameters.

本地开发Local development

在本地运行时,上述配置会告知运行时使用本地开发人员标识。When running locally, the above configuration tells the runtime to use your local developer identity. 连接将尝试从以下位置获取令牌,顺序如下:The connection will attempt to get a token from the following locations, in order:

  • Microsoft 应用程序之间共享的本地缓存A local cache shared between Microsoft applications
  • Visual Studio 中的当前用户上下文The current user context in Visual Studio
  • Visual Studio Code 中的当前用户上下文The current user context in Visual Studio Code
  • Azure CLI 中的当前用户上下文The current user context in the Azure CLI

如果这些选项都不成功,则会出现错误。If none of these options are successful, an error will occur.

在某些情况下,你可能希望指定使用其他标识。In some cases, you may wish to specify use of a different identity. 可以添加指向其他标识的连接的配置属性。You can add configuration properties for the connection that point to the alternate identity.

备注

在 Azure Functions 服务中托管时,不支持以下配置选项。The following configuration options are not supported when hosted in the Azure Functions service.

若要在 Azure Active Directory 服务主体中使用客户端 ID 和机密进行连接,请使用以下属性定义连接:To connect using an Azure Active Directory service principal with a client ID and secret, define the connection with the following properties:

属性Property 环境变量Environment variable 是否必需Is Required 说明Description
服务 URIService URI <CONNECTION_NAME_PREFIX>__serviceUri Yes 要连接到的服务的数据平面 URI。The data plane URI of the service to which you are connecting.
租户 IDTenant ID <CONNECTION_NAME_PREFIX>__tenantId Yes Azure Active Directory 租户(目录)ID。The Azure Active Directory tenant (directory) ID.
客户端 IDClient ID <CONNECTION_NAME_PREFIX>__clientId Yes 租户中应用注册的客户端(应用程序)ID。The client (application) ID of an app registration in the tenant.
客户端机密Client secret <CONNECTION_NAME_PREFIX>__clientSecret Yes 为应用注册生成的客户端密码。A client secret that was generated for the app registration.

向标识授予权限Grant permission to the identity

无论使用何种标识,都必须具有执行所需操作的权限。Whatever identity is being used must have permissions to perform the intended actions. 这通常是通过在 Azure RBAC 中分配角色或在访问策略中指定标识来完成的,具体取决于要连接到的服务。This is typically done by assigning a role in Azure RBAC or specifying the identity in an access policy, depending on the service to which you are connecting. 请参阅每个服务的相关文档,了解需要哪些权限以及如何设置这些权限。Refer to the documentation for each service on what permissions are needed and how they can be set.

重要

某些权限可能由并非所有上下文都需要的服务公开。Some permissions might be exposed by the service that are not necessary for all contexts. 尽可能遵循最低权限原则,仅授予标识所需的权限。Where possible, adhere to the principle of least privilege, granting the identity only required privileges. 例如,如果应用只需从 Blob 读取数据,请使用存储 Blob 数据读取者角色,因为存储 Blob 数据所有者包含过多的读取操作权限。For example, if the app just needs to read from a blob, use the Storage Blob Data Reader role as the Storage Blob Data Owner includes excessive permissions for a read operation.

报告问题Reporting Issues

项目Item 说明Description 链接Link
运行时Runtime 脚本主机、触发器和绑定及语言支持Script Host, Triggers & Bindings, Language Support 提出问题File an Issue
模板Templates 创建模板的代码问题Code Issues with Creation Template 提出问题File an Issue
门户Portal 用户界面或体验问题User Interface or Experience Issue 提出问题File an Issue

后续步骤Next steps

有关详细信息,请参阅以下资源:For more information, see the following resources: