Azure Functions 的 Azure 队列存储绑定Azure Queue storage bindings for Azure Functions

本文介绍如何在 Azure Functions 中使用 Azure 队列存储绑定。This article explains how to work with Azure Queue storage bindings in Azure Functions. Azure Functions 支持对队列使用触发器和输出绑定。Azure Functions supports trigger and output bindings for queues.

此参考信息面向 Azure Functions 开发人员。This is reference information for Azure Functions developers. Azure Functions 的新手请从以下资源入手:If you're new to Azure Functions, start with the following resources:

包 - Functions 1.xPackages - Functions 1.x

Microsoft.Azure.WebJobs NuGet 包 2.x 版中提供了队列存储绑定。The Queue storage bindings are provided in the Microsoft.Azure.WebJobs NuGet package, version 2.x. azure-webjobs-sdk GitHub 存储库中提供了此包的源代码。Source code for the package is in the azure-webjobs-sdk GitHub repository.

C# 类库C# class library

对于 C# 类库开发,自动在项目中安装该包。For C# class library development, the package is automatically installed in the project.

Functions 2.x 中的绑定扩展Binding extensions in Functions 2.x

对于 Azure Functions 2.x 版中的本地开发,该包自动注册为绑定扩展For local development in Azure Functions version 2.x, the package is automatically registered as a binding extension.

Functions 1.x 中的 Azure 存储 SDK 版本Azure Storage SDK version in Functions 1.x

在 Functions 1.x 中,存储触发器和绑定使用 7.2.1 版的 Azure 存储 SDK(WindowsAzure.Storage NuGet 包)。In Functions 1.x, the Storage triggers and bindings use version 7.2.1 of the Azure Storage SDK (WindowsAzure.Storage NuGet package). 如果引用另一版本的存储 SDK,而且在函数签名中绑定到某个存储 SDK 类型,则 Functions 运行时可能会报告它不能绑定到该类型。If you reference a different version of the Storage SDK, and you bind to a Storage SDK type in your function signature, the Functions runtime may report that it can't bind to that type. 此解决方案是为了确保项目引用 WindowsAzure.Storage 7.2.1The solution is to make sure your project references WindowsAzure.Storage 7.2.1.

包 - Functions 2.xPackages - Functions 2.x

Microsoft.Azure.WebJobs.Extensions.Storage NuGet 包 3.x 版中提供了队列存储绑定。The Queue storage bindings are provided in the Microsoft.Azure.WebJobs.Extensions.Storage NuGet package, version 3.x. azure-webjobs-sdk GitHub 存储库中提供了此包的源代码。Source code for the package is in the azure-webjobs-sdk GitHub repository.

下表说明了如何在每个开发环境中添加对此绑定的支持。The following table tells how to add support for this binding in each development environment.

开发环境Development environment 添加支持To add support in
Functions 2.xFunctions 2.x
本地开发 - C# 类库Local development - C# class library 安装包Install the package
本地开发 - C# 脚本、JavaScript、F#、JavaLocal development - C# script, JavaScript, F#, Java 注册扩展Register the extension
门户开发Portal development 添加输出绑定时安装Install when adding output binding

若要了解如何更新门户中的现有绑定扩展而不必重新发布函数应用项目,请参阅更新扩展To learn how to update existing binding extensions in the portal without having to republish your function app project, see Update your extensions.

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

触发器Trigger

在队列中收到新项时,可以使用队列触发器启动一个函数。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.

触发器 - 示例Trigger - example

参阅语言特定的示例:See the language-specific example:

触发器 - C# 示例Trigger - C# example

以下示例演示可在每次处理某个队列项之后轮询 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}");
    }
}

触发器 - C# 脚本示例Trigger - C# script example

以下示例演示 function.json 文件中的一个队列触发器绑定以及使用该绑定的 C# 脚本 (.csx) 代码 。The following example shows a queue trigger binding in a function.json file and C# script (.csx) code that uses the binding. 每次处理某个队列项之后,该函数会轮询 myqueue-items 队列并写入日志。The function polls the myqueue-items queue and writes a log each time a queue item is processed.

function.json 文件如下所示:Here's the function.json file:

{
    "disabled": false,
    "bindings": [
        {
            "type": "queueTrigger",
            "direction": "in",
            "name": "myQueueItem",
            "queueName": "myqueue-items",
            "connection":"MyStorageConnectionAppSetting"
        }
    ]
}

配置部分解释了这些属性。The configuration section explains these properties.

C# 脚本代码如下所示:Here's the C# script code:

#r "Microsoft.WindowsAzure.Storage"

using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Queue;
using System;

public static void Run(CloudQueueMessage myQueueItem, 
    DateTimeOffset expirationTime, 
    DateTimeOffset insertionTime, 
    DateTimeOffset nextVisibleTime,
    string queueTrigger,
    string id,
    string popReceipt,
    int dequeueCount,
    ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem.AsString}\n" +
        $"queueTrigger={queueTrigger}\n" +
        $"expirationTime={expirationTime}\n" +
        $"insertionTime={insertionTime}\n" +
        $"nextVisibleTime={nextVisibleTime}\n" +
        $"id={id}\n" +
        $"popReceipt={popReceipt}\n" + 
        $"dequeueCount={dequeueCount}");
}

用法部分解释了 function.json 中的 name 属性命名的 myQueueItemThe usage section explains myQueueItem, which is named by the name property in function.json. 消息元数据部分解释了所有其他所示变量。The message metadata section explains all of the other variables shown.

触发器 - JavaScript 示例Trigger - JavaScript example

以下示例演示 function.json 文件中的一个队列触发器绑定以及使用该绑定的 JavaScript 函数The following example shows a queue trigger binding in a function.json file and a JavaScript function that uses the binding. 每次处理某个队列项之后,该函数会轮询 myqueue-items 队列并写入日志。The function polls the myqueue-items queue and writes a log each time a queue item is processed.

function.json 文件如下所示:Here's the function.json file:

{
    "disabled": false,
    "bindings": [
        {
            "type": "queueTrigger",
            "direction": "in",
            "name": "myQueueItem",
            "queueName": "myqueue-items",
            "connection":"MyStorageConnectionAppSetting"
        }
    ]
}

配置部分解释了这些属性。The configuration section explains these properties.

Note

name 参数在 JavaScript 代码中反映为 context.bindings.<name>,其中包含队列项有效负载。The name parameter reflects as context.bindings.<name> in the JavaScript code which contains the queue item payload. 此有效负载也作为第二个参数传递给函数。This payload is also passed as the second parameter to the function.

JavaScript 代码如下所示:Here's the JavaScript code:

module.exports = async function (context, message) {
    context.log('Node.js queue trigger function processed work item', message);
    // OR access using context.bindings.<name>
    // context.log('Node.js queue trigger function processed work item', context.bindings.myQueueItem);
    context.log('expirationTime =', context.bindingData.expirationTime);
    context.log('insertionTime =', context.bindingData.insertionTime);
    context.log('nextVisibleTime =', context.bindingData.nextVisibleTime);
    context.log('id =', context.bindingData.id);
    context.log('popReceipt =', context.bindingData.popReceipt);
    context.log('dequeueCount =', context.bindingData.dequeueCount);
    context.done();
};

用法部分解释了 function.json 中的 name 属性命名的 myQueueItemThe usage section explains myQueueItem, which is named by the name property in function.json. 消息元数据部分解释了所有其他所示变量。The message metadata section explains all of the other variables shown.

触发器 - Java 示例Trigger - Java example

以下 Java 示例显示了一个存储队列触发器函数,该函数用于记录放入队列 myqueuename 的触发消息。The following Java example shows a storage queue trigger functions which logs the triggered message placed into queue myqueuename.

@FunctionName("queueprocessor")
public void run(
   @QueueTrigger(name = "msg",
                  queueName = "myqueuename",
                  connection = "myconnvarname") String message,
    final ExecutionContext context
) {
    context.getLogger().info(message);
}

触发器 - 特性Trigger - attributes

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 storage account to use, as shown in the following example:

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

    有关完整示例,请参阅触发器 - C# 示例For a complete example, see Trigger - C# 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.

触发器 - 配置Trigger - 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
类型 type 不适用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”,函数运行时将会查找名为“AzureWebJobsMyStorage”的应用设置。For example, if you set connection to "MyStorage", the Functions runtime looks for an app setting that is named "AzureWebJobsMyStorage." 如果将 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.

触发器 - 用法Trigger - usage

在 C# 和 C# 脚本中,可以使用 string paramName 等方法参数访问消息数据。In C# and C# script, access the message data by using a method parameter such as string paramName. 在 C# 脚本中,paramName 是在 function.jsonname 属性中指定的值。In C# script, paramName is the value specified in the name property of function.json. 可以绑定到以下任何类型: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.

在 JavaScript 中,可以使用 context.bindings.<name> 访问队列项有效负载。In JavaScript, use context.bindings.<name> to access the queue item payload. 如果有效负载为 JSON,则会将它反序列化为对象。If the payload is JSON, it's deserialized into an object.

触发器 - 消息元数据Trigger - 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 类的属性。These are properties of the CloudQueueMessage class.

属性Property 类型Type 说明Description
QueueTrigger string 队列有效负载(如果是有效的字符串)。Queue payload (if a valid string). 如果队列消息有效负载是字符串,则 QueueTrigger 包含的值与 function.jsonname 属性命名的变量的值相同。If the queue message payload as 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.

触发器 - 有害消息Trigger - 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.

触发器 - 轮询算法Trigger - polling algorithm

队列触发器实现了随机指数退让算法,以降低空闲队列轮询对存储交易成本造成的影响。The queue trigger implements a random exponential back-off algorithm to reduce the effect of idle-queue polling on storage transaction costs. 当找到消息时,运行时将等待两秒钟,然后检查另一条消息;如果未找到消息,它将等待大约四秒,然后重试。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.

触发器 - 并发Trigger - 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; functions do not have to be written to be idempotent.

触发器 - host.json 属性Trigger - 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.

输出Output

使用 Azure 队列存储输出绑定可将消息写入队列。Use the Azure Queue storage output binding to write messages to a queue.

输出 - 示例Output - example

参阅语言特定的示例:See the language-specific example:

输出 - C# 示例Output - C# example

以下示例演示针对收到的每个 HTTP 请求创建队列消息的C# 函数The following example shows a C# function that creates a queue message for each HTTP request received.

[StorageAccount("AzureWebJobsStorage")]
public static class QueueFunctions
{
    [FunctionName("QueueOutput")]
    [return: Queue("myqueue-items")]
    public static string QueueOutput([HttpTrigger] dynamic input,  ILogger log)
    {
        log.LogInformation($"C# function processed: {input.Text}");
        return input.Text;
    }
}

输出 - C# 脚本示例Output - C# script example

以下示例演示 function.json 文件中的一个 HTTP 触发器绑定以及使用该绑定的 C# 脚本 (.csx) 代码 。The following example shows an HTTP trigger binding in a function.json file and C# script (.csx) code that uses the binding. 该函数针对收到的每个 HTTP 请求创建一个包含 CustomQueueMessage 对象有效负载的队列项 。The function creates a queue item with a CustomQueueMessage object payload for each HTTP request received.

function.json 文件如下所示:Here's the function.json file:

{
  "bindings": [
    {
      "type": "httpTrigger",
      "direction": "in",
      "authLevel": "function",
      "name": "input"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "return"
    },
    {
      "type": "queue",
      "direction": "out",
      "name": "$return",
      "queueName": "outqueue",
      "connection": "MyStorageConnectionAppSetting"
    }
  ]
}

配置部分解释了这些属性。The configuration section explains these properties.

下面是可创建一条队列消息的 C# 脚本代码:Here's C# script code that creates a single queue message:

public class CustomQueueMessage
{
    public string PersonName { get; set; }
    public string Title { get; set; }
}

public static CustomQueueMessage Run(CustomQueueMessage input, ILogger log)
{
    return input;
}

可以使用 ICollectorIAsyncCollector 参数一次性发送多条消息。You can send multiple messages at once by using an ICollector or IAsyncCollector parameter. 以下 C# 脚本代码发送多条消息,其中一条消息包含 HTTP 请求数据,另一条消息包含硬编码值:Here's C# script code that sends multiple messages, one with the HTTP request data and one with hard-coded values:

public static void Run(
    CustomQueueMessage input, 
    ICollector<CustomQueueMessage> myQueueItems, 
    ILogger log)
{
    myQueueItems.Add(input);
    myQueueItems.Add(new CustomQueueMessage { PersonName = "You", Title = "None" });
}

输出 - JavaScript 示例Output - JavaScript example

以下示例演示 function.json 文件中的一个 HTTP 触发器绑定以及使用该绑定的 JavaScript 函数The following example shows an HTTP trigger binding in a function.json file and a JavaScript function that uses the binding. 该函数针对收到的每个 HTTP 请求创建一个队列项。The function creates a queue item for each HTTP request received.

function.json 文件如下所示:Here's the function.json file:

{
  "bindings": [
    {
      "type": "httpTrigger",
      "direction": "in",
      "authLevel": "function",
      "name": "input"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "return"
    },
    {
      "type": "queue",
      "direction": "out",
      "name": "$return",
      "queueName": "outqueue",
      "connection": "MyStorageConnectionAppSetting"
    }
  ]
}

配置部分解释了这些属性。The configuration section explains these properties.

JavaScript 代码如下所示:Here's the JavaScript code:

module.exports = function (context, input) {
    context.done(null, input.body);
};

可以通过定义 myQueueItem 输出绑定的消息数组,一次性发送多条消息。You can send multiple messages at once by defining a message array for the myQueueItem output binding. 以下 JavaScript 代码针对收到的每个 HTTP 请求发送两条包含硬编码值的队列消息。The following JavaScript code sends two queue messages with hard-coded values for each HTTP request received.

module.exports = function(context) {
    context.bindings.myQueueItem = ["message 1","message 2"];
    context.done();
};

输出 - Java 示例Output - Java example

以下示例演示一个 Java 函数,该函数在受到 HTTP 请求触发时创建一个队列消息。The following example shows a Java function that creates a queue message for when triggered by a HTTP request.

@FunctionName("httpToQueue")
@QueueOutput(name = "item", queueName = "myqueue-items", connection = "AzureWebJobsStorage")
 public String pushToQueue(
     @HttpTrigger(name = "request", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
     final String message,
     @HttpOutput(name = "response") final OutputBinding&lt;String&gt; result) {
       result.setValue(message + " has been added.");
       return message;
 }

Java 函数运行时库中,对其值将写入队列存储的参数使用 @QueueOutput 注释。In the Java functions runtime library, use the @QueueOutput annotation on parameters whose value would be written to Queue storage. 参数类型应为 OutputBinding<T>,其中 T 是 POJO 的任何本机 Java 类型。The parameter type should be OutputBinding<T>, where T is any native Java type of a POJO.

输出 - 特性Output - attributes

C# 类库中,使用 QueueAttributeIn C# class libraries, use the QueueAttribute.

该特性将应用到 out 参数,或应用到函数的返回值。The attribute applies to an out parameter or the return value of the function. 该特性的构造函数采用队列的名称,如以下示例中所示:The attribute's constructor takes the name of the queue, as shown in the following example:

[FunctionName("QueueOutput")]
[return: Queue("myqueue-items")]
public static string Run([HttpTrigger] dynamic input,  ILogger log)
{
    ...
}

可以设置 Connection 属性来指定要使用的存储帐户,如以下示例中所示:You can set the Connection property to specify the storage account to use, as shown in the following example:

[FunctionName("QueueOutput")]
[return: Queue("myqueue-items", Connection = "StorageConnectionAppSetting")]
public static string Run([HttpTrigger] dynamic input,  ILogger log)
{
    ...
}

有关完整示例,请参阅输出 - C# 示例For a complete example, see Output - C# example.

可以使用 StorageAccount 特性在类、方法或参数级别指定存储帐户。You can use the StorageAccount attribute to specify the storage account at class, method, or parameter level. 有关详细信息,请参阅“触发器 - 特性”。For more information, see Trigger - attributes.

输出 - 配置Output - configuration

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

function.json 属性function.json property Attribute 属性Attribute property 说明Description
类型 type 不适用n/a 必须设置为 queueMust be set to queue. 在 Azure 门户中创建触发器时,会自动设置此属性。This property is set automatically when you create the trigger in the Azure portal.
directiondirection 不适用n/a 必须设置为 outMust be set to out. 在 Azure 门户中创建触发器时,会自动设置此属性。This property is set automatically when you create the trigger in the Azure portal.
namename 不适用n/a 表示函数代码中的队列的变量的名称。The name of the variable that represents the queue in function code. 设置为 $return 可引用函数返回值。Set to $return to reference the function return value.
queueNamequeueName QueueNameQueueName 队列的名称。The name of the queue.
连接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”,函数运行时将会查找名为“AzureWebJobsMyStorage”的应用设置。For example, if you set connection to "MyStorage", the Functions runtime looks for an app setting that is named "AzureWebJobsMyStorage." 如果将 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.

输出 - 用法Output - usage

在 C# 和 C# 脚本中,可以使用 out T paramName 等方法参数编写一条队列消息。In C# and C# script, write a single queue message by using a method parameter such as out T paramName. 在 C# 脚本中,paramName 是在 function.jsonname 属性中指定的值。In C# script, paramName is the value specified in the name property of function.json. 可以使用方法返回类型而不使用 out 参数,T 可为以下任何类型:You can use the method return type instead of an out parameter, and T can be any of the following types:

如果在尝试绑定到 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.

在 C# 和 C# 脚本中,可使用以下类型之一编写多条队列消息:In C# and C# script, write multiple queue messages by using one of the following types:

在 JavaScript 函数中,可以使用 context.bindings.<name> 访问输出队列消息。In JavaScript functions, use context.bindings.<name> to access the output queue message. 可对队列项有效负载使用字符串或 JSON 可序列化对象。You can use a string or a JSON-serializable object for the queue item payload.

异常和返回代码Exceptions and return codes

绑定Binding 参考Reference
队列Queue 队列错误代码Queue Error Codes
Blob、表、队列Blob, Table, Queue 存储错误代码Storage Error Codes
Blob、表、队列Blob, Table, Queue 故障排除Troubleshooting

host.json 设置host.json settings

本部分介绍版本 2.x 中可用于此绑定的全局配置设置。This section describes the global configuration settings available for this binding in version 2.x. 下面的示例 host.json 文件仅包含此绑定的 2.x 版本设置。The example host.json file below contains only the version 2.x settings for this binding. 有关版本 2.x 中的全局配置设置的详细信息,请参阅 Azure Functions 版本 2.x 的 host.json 参考For more information about global configuration settings in version 2.x, see host.json reference for Azure Functions version 2.x.

Note

有关 Functions 1.x 中 host.json 的参考,请参阅 Azure Functions 1.x 的 host.json 参考For a reference of host.json in Functions 1.x, see host.json reference for Azure Functions 1.x.

{
    "version": "2.0",
    "extensions": {
        "queues": {
            "maxPollingInterval": "00:00:02",
            "visibilityTimeout" : "00:00:30",
            "batchSize": 16,
            "maxDequeueCount": 5,
            "newBatchThreshold": 8
        }
    }
}
属性Property 默认Default 说明Description
maxPollingIntervalmaxPollingInterval 00:00:0100:00:01 队列轮询的最大间隔时间。The maximum interval between queue polls. 最小值为 00:00:00.100(100 毫秒),可递增至 00:01:00(1 分钟)。Minimum is 00:00:00.100 (100 ms) and increments up to 00:01:00 (1 min). 在 1.x 中,数据类型是毫秒,在 2.x 中,数据类型是 TimeSpan。In 1.x the data type is milliseconds, and in 2.x it is a TimeSpan.
visibilityTimeoutvisibilityTimeout 00:00:0000:00:00 消息处理失败时的重试间隔时间。The time interval between retries when processing of a message fails.
batchSizebatchSize 1616 Functions 运行时同时检索并并行处理的队列消息数。The number of queue messages that the Functions runtime retrieves simultaneously and processes in parallel. 当处理的数量下降到 newBatchThreshold 时,运行时可获取另一个批,并开始处理这些消息。When the number being processed gets down to the newBatchThreshold, the runtime gets another batch and starts processing those messages. 因此,每个函数处理的最大并发消息数是 batchSize 加上 newBatchThresholdSo the maximum number of concurrent messages being processed per function is batchSize plus newBatchThreshold. 此限制分别应用于各个队列触发的函数。This limit applies separately to each queue-triggered function.

如果要避免对队列上收到的消息并行执行,可以将 batchSize 设置为 1。If you want to avoid parallel execution for messages received on one queue, you can set batchSize to 1. 但是,只有在函数于单个虚拟机 (VM) 上运行时,此设置才可消除并发。However, this setting eliminates concurrency only so long as your function app runs on a single virtual machine (VM). 如果函数应用横向扩展到多个 VM,每个 VM 可运行每个队列触发的函数的一个实例。If the function app scales out to multiple VMs, each VM could run one instance of each queue-triggered function.

batchSize 的最大值为 32。The maximum batchSize is 32.
maxDequeueCountmaxDequeueCount 55 在将某个消息移到有害队列之前,尝试处理该消息的次数。The number of times to try processing a message before moving it to the poison queue.
newBatchThresholdnewBatchThreshold batchSize/2batchSize/2 只要同时处理的消息数下降到此数值,运行时即检索另一个批次。Whenever the number of messages being processed concurrently gets down to this number, the runtime retrieves another batch.

后续步骤Next steps