适用于 Azure Functions 的 Azure 队列存储触发器Azure Queue storage trigger for Azure Functions

当消息添加到 Azure 队列存储时,队列存储触发器将运行函数。The queue storage trigger runs a function as messages are added to Azure Queue storage.

编码Encoding

函数需要 base64 编码字符串。Functions expect a base64 encoded string. 对编码类型进行的任何调整(若要将数据作为 base64 编码字符串进行准备)需要在调用服务中实现。Any adjustments to the encoding type (in order to prepare data as a base64 encoded string) need to be implemented in the calling service.

示例Example

在队列中收到新项时,可以使用队列触发器启动一个函数。Use the queue trigger to start a function when a new item is received on a queue. 队列消息作为输入提供给该函数。The queue message is provided as input to the function.

以下示例演示可在每次处理某个队列项之后轮询 myqueue-items 队列并写入日志的 C# 函数The following example shows a C# function that polls the myqueue-items queue and writes a log each time a queue item is processed.

public static class QueueFunctions
{
    [FunctionName("QueueTrigger")]
    public static void QueueTrigger(
        [QueueTrigger("myqueue-items")] string myQueueItem, 
        ILogger log)
    {
        log.LogInformation($"C# function processed: {myQueueItem}");
    }
}

特性和注释Attributes and annotations

C# 类库,请使用以下属性来配置队列触发器:In C# class libraries, use the following attributes to configure a queue trigger:

  • QueueTriggerAttributeQueueTriggerAttribute

    该特性的构造函数采用要监视的队列的名称,如以下示例中所示:The attribute's constructor takes the name of the queue to monitor, as shown in the following example:

    [FunctionName("QueueTrigger")]
    public static void Run(
        [QueueTrigger("myqueue-items")] string myQueueItem, 
        ILogger log)
    {
        ...
    }
    

    可以设置 Connection 属性来指定要使用的存储帐户连接字符串,如以下示例中所示:You can set the Connection property to specify the app setting that contains the storage account connection string to use, as shown in the following example:

    [FunctionName("QueueTrigger")]
    public static void Run(
        [QueueTrigger("myqueue-items", Connection = "StorageConnectionAppSetting")] string myQueueItem, 
        ILogger log)
    {
        ....
    }
    

    有关完整示例,请参阅示例For a complete example, see example.

  • StorageAccountAttributeStorageAccountAttribute

    提供另一种方式来指定要使用的存储帐户。Provides another way to specify the storage account to use. 构造函数采用包含存储连接字符串的应用设置的名称。The constructor takes the name of an app setting that contains a storage connection string. 可以在参数、方法或类级别应用该特性。The attribute can be applied at the parameter, method, or class level. 以下示例演示类级别和方法级别:The following example shows class level and method level:

    [StorageAccount("ClassLevelStorageAppSetting")]
    public static class AzureFunctions
    {
        [FunctionName("QueueTrigger")]
        [StorageAccount("FunctionLevelStorageAppSetting")]
        public static void Run( //...
    {
        ...
    }
    

要使用的存储帐户按以下顺序确定:The storage account to use is determined in the following order:

  • QueueTrigger 特性的 Connection 属性。The QueueTrigger attribute's Connection property.
  • 作为 QueueTrigger 特性应用到同一参数的 StorageAccount 特性。The StorageAccount attribute applied to the same parameter as the QueueTrigger attribute.
  • 应用到函数的 StorageAccount 特性。The StorageAccount attribute applied to the function.
  • 应用到类的 StorageAccount 特性。The StorageAccount attribute applied to the class.
  • “AzureWebJobsStorage”应用设置。The "AzureWebJobsStorage" app setting.

配置Configuration

下表解释了在 function.json 文件和 QueueTrigger 特性中设置的绑定配置属性。The following table explains the binding configuration properties that you set in the function.json file and the QueueTrigger attribute.

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 不适用n/a 必须设置为 queueTriggerMust be set to queueTrigger. 在 Azure 门户中创建触发器时,会自动设置此属性。This property is set automatically when you create the trigger in the Azure portal.
directiondirection 不适用n/a 只能在 function.json 文件中设置。In the function.json file only. 必须设置为 inMust be set to in. 在 Azure 门户中创建触发器时,会自动设置此属性。This property is set automatically when you create the trigger in the Azure portal.
namename 不适用n/a 函数代码中包含队列项有效负载的变量的名称。The name of the variable that contains the queue item payload in the function code.
queueNamequeueName QueueNameQueueName 要轮询的队列的名称。The name of the queue to poll.
连接 connection ConnectionConnection 包含要用于此绑定的存储连接字符串的应用设置的名称。The name of an app setting that contains the Storage connection string to use for this binding. 如果应用设置名称以“AzureWebJobs”开始,则只能在此处指定该名称的余下部分。If the app setting name begins with "AzureWebJobs", you can specify only the remainder of the name here. 例如,如果将 connection 设置为“MyStorage”,Functions 运行时将会查找名为“MyStorage”的应用设置。For example, if you set connection to "MyStorage", the Functions runtime looks for an app setting that is named "MyStorage." 如果将 connection 留空,函数运行时将使用名为 AzureWebJobsStorage 的应用设置中的默认存储连接字符串。If you leave connection empty, the Functions runtime uses the default Storage connection string in the app setting that is named AzureWebJobsStorage.

在本地进行开发时,应用设置将取 local.settings.json 文件的值。When you're developing locally, app settings go into the local.settings.json file.

使用情况Usage

使用 string paramName 等方法参数访问消息数据。Access the message data by using a method parameter such as string paramName. 可以绑定到以下任何类型:You can bind to any of the following types:

  • 对象 - Functions 运行时将 JSON 负载反序列化为代码中定义的任意类的实例。Object - The Functions runtime deserializes a JSON payload into an instance of an arbitrary class defined in your code.
  • string
  • byte[]
  • CloudQueueMessageCloudQueueMessage

如果在尝试绑定到 CloudQueueMessage 时出现错误消息,请确保引用正确的存储 SDK 版本If you try to bind to CloudQueueMessage and get an error message, make sure that you have a reference to the correct Storage SDK version.

消息元数据Message metadata

队列触发器提供了数个元数据属性。The queue trigger provides several metadata properties. 这些属性可在其他绑定中用作绑定表达式的一部分,或者用作代码中的参数。These properties can be used as part of binding expressions in other bindings or as parameters in your code. 以下属性是 CloudQueueMessage 类的成员。The properties are members of the CloudQueueMessage class.

属性Property 类型Type 说明Description
QueueTrigger string 队列有效负载(如果是有效的字符串)。Queue payload (if a valid string). 如果队列消息有效负载是字符串,则 QueueTrigger 包含的值与 function.jsonname 属性命名的变量的值相同。If the queue message payload is a string, QueueTrigger has the same value as the variable named by the name property in function.json.
DequeueCount int 此消息取消排队的次数。The number of times this message has been dequeued.
ExpirationTime DateTimeOffset 消息过期的时间。The time that the message expires.
Id string 队列消息 ID。Queue message ID.
InsertionTime DateTimeOffset 消息添加到队列的时间。The time that the message was added to the queue.
NextVisibleTime DateTimeOffset 消息下一次可见的时间。The time that the message will next be visible.
PopReceipt string 消息的 pop 接收方。The message's pop receipt.

有害消息Poison messages

队列触发函数失败时,Azure Functions 会针对给定的队列消息重试该函数最多 5 次(包括第一次尝试)。When a queue trigger function fails, Azure Functions retries the function up to five times for a given queue message, including the first try. 如果 5 次尝试全部失败,函数运行时会将一条消息添加到名为 <originalqueuename>-poison 的队列。If all five attempts fail, the functions runtime adds a message to a queue named <originalqueuename>-poison. 可以编写一个函数来处理有害队列中的消息,并记录这些消息,或者发送需要注意的通知。You can write a function to process messages from the poison queue by logging them or sending a notification that manual attention is needed.

若要手动处理有害消息,请检查队列消息的 dequeueCountTo handle poison messages manually, check the dequeueCount of the queue message.

轮询算法Polling algorithm

队列触发器实现了随机指数退让算法,以降低空闲队列轮询对存储交易成本造成的影响。The queue trigger implements a random exponential back-off algorithm to reduce the effect of idle-queue polling on storage transaction costs.

该算法使用以下逻辑:The algorithm uses the following logic:

  • 找到消息后,运行时将等待两秒钟,然后检查是否有其他消息When a message is found, the runtime waits two seconds and then checks for another message
  • 如果未找到任何消息,它将等待大约四秒钟,然后重试。When no message is found, it waits about four seconds before trying again.
  • 如果后续尝试获取队列消息失败,则等待时间会继续增加,直到达到最长等待时间(默认为 1 分钟)。After subsequent failed attempts to get a queue message, the wait time continues to increase until it reaches the maximum wait time, which defaults to one minute.
  • 可以通过 host.json 文件中的 maxPollingInterval 属性配置最大等待时间。The maximum wait time is configurable via the maxPollingInterval property in the host.json file.

对于本地开发,最大轮询间隔默认为两秒。For local development the maximum polling interval defaults to two seconds.

在计费方面,运行时轮询所花时间是“免费的”,不会计入帐户。In regard to billing, time spent polling by the runtime is "free" and not counted against your account.

并发Concurrency

当有多个队列消息在等待时,队列触发器会检索一批消息并以并发方式调用函数实例来处理它们。When there are multiple queue messages waiting, the queue trigger retrieves a batch of messages and invokes function instances concurrently to process them. 默认情况下,批大小为 16。By default, the batch size is 16. 当处理的数量下降到 8 时,运行时可获取另一个批,并开始处理这些消息。When the number being processed gets down to 8, the runtime gets another batch and starts processing those messages. 因此,单个虚拟机 (VM) 上每个函数处理的最大并发消息数是 24。So the maximum number of concurrent messages being processed per function on one virtual machine (VM) is 24. 此限制分别应用于每个 VM 上各个队列触发的函数。This limit applies separately to each queue-triggered function on each VM. 如果你的函数应用横向扩展到多个 VM,则每个 VM 将等待触发器并尝试运行函数。If your function app scales out to multiple VMs, each VM will wait for triggers and attempt to run functions. 例如,如果某个函数应用横向扩展到 3 个 VM,则每个队列触发的函数的默认最大并发实例数是 72。For example, if a function app scales out to 3 VMs, the default maximum number of concurrent instances of one queue-triggered function is 72.

可以在 host.json 文件中配置用于获取新批的批大小和阈值。The batch size and the threshold for getting a new batch are configurable in the host.json file. 如果希望在函数应用中最大程度地降低查询触发的函数的并行执行,可以将批大小设置为 1。If you want to minimize parallel execution for queue-triggered functions in a function app, you can set the batch size to 1. 只有当函数在单个虚拟机 (VM) 上运行时,此设置才可消除并发。This setting eliminates concurrency only so long as your function app runs on a single virtual machine (VM).

队列触发器会自动阻止函数同时多次处理队列消息。The queue trigger automatically prevents a function from processing a queue message multiple times simultaneously.

host.json 属性host.json properties

host.json 文件包含控制队列触发器行为的设置。The host.json file contains settings that control queue trigger behavior. 有关可用设置的详细信息,请参阅 host.json 设置部分。See the host.json settings section for details regarding available settings.

后续步骤Next steps