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.

所有的開發環境中都會自動賦予此繫結的支援。Support for this binding is automatically provided in all development environments. 您不需要手動安裝套件或註冊擴充功能。You don't have to manually install the package or register the extension.

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

在 Functions 1.x 中,儲存體觸發程序和繫結會使用 Azure 儲存體 SDK 7.2.1 版 (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#、Java 和 PythonLocal development - C# script, JavaScript, F#, Java and Python 註冊擴充功能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

Functions 預期有 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

下列範例所示範的 C# 函式會輪詢 myqueue-items 佇列,並在每次處理佇列項目時寫入記錄。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}");
}

使用方式章節會說明 myQueueItem (由 function.json 中的name 屬性命名)。The 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.

注意

名稱參數會在 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();
};

使用方式章節會說明 myQueueItem (由 function.json 中的name 屬性命名)。The 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);
}

觸發程序 - Python 範例Trigger - Python example

下列範例示範如何讀取透過觸發程式傳遞至函式的佇列訊息。The following example demonstrates how to read a queue message passed to a function via a trigger.

儲存體佇列觸發程式定義于函式 . json中, 其中類型設定queueTrigger為。A Storage queue trigger is defined in function.json where type is set to queueTrigger.

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "msg",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "messages",
      "connection": "AzureStorageQueuesConnectionString"
    }
  ]
}

程式 代碼_ .py會宣告參數,讓您能夠讀取函式中的佇列訊息。_ func.ServiceBusMessageThe code _init_.py declares a parameter as func.ServiceBusMessage which allows you to read the queue message in your function.

import logging
import json

import azure.functions as func

def main(msg: func.QueueMessage):
    logging.info('Python queue trigger function processed a queue item.')

    result = json.dumps({
        'id': msg.id,
        'body': msg.get_body().decode('utf-8'),
        'expiration_time': (msg.expiration_time.isoformat()
                            if msg.expiration_time else None),
        'insertion_time': (msg.insertion_time.isoformat()
                           if msg.insertion_time else None),
        'time_next_visible': (msg.time_next_visible.isoformat()
                              if msg.time_next_visible else None),
        'pop_receipt': msg.pop_receipt,
        'dequeue_count': msg.dequeue_count
    })

    logging.info(result)

觸發程序 - 屬性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.
  • StorageAccount 屬性套用至與 QueueTrigger 屬性相同的參數。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 property 描述Description
typetype n/an/a 必須設為 queueTriggerMust be set to queueTrigger. 當您在 Azure 入口網站中建立觸發程序時,會自動設定此屬性。This property is set automatically when you create the trigger in the Azure portal.
directiondirection n/an/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/an/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 連接Connection 應用程式設定的名稱包含要用於此繫結的儲存體連接字串。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# 指令碼中,paramNamefunction.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 TypeType 描述Description
QueueTrigger string 佇列承載 (如果為有效字串)。Queue payload (if a valid string). 如果佇列承載為字串,QueueTrigger 具有相同於 function.json 中由 name 屬性命名之變數的值。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 佇列訊息識別碼。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 訊息的離開通知。The message's pop receipt.

觸發程序 - 有害訊息Trigger - poison messages

當佇列觸發程序函數失敗時,Azure Functions 會針對指定的佇列訊息重試該函數最多五次,包括第一次嘗試。When a queue trigger function fails, Azure Functions retries the function up to five times for a given queue message, including the first try. 如果五次嘗試全都失敗,Functions 執行階段會將訊息新增至名為 <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. 連續嘗試取得佇列訊息失敗後,等候時間會持續增加,直到它到達等待時間上限 (預設值為一分鐘)。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.

OutputOutput

使用 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

下列範例所示範的 C# 函式會為每個收到的 HTTP 要求建立佇列訊息。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 是任何原生 Java 類型的 POJO。The parameter type should be OutputBinding<T>, where T is any native Java type of a POJO.

輸出 - Python 範例Output - Python example

下列範例示範如何將單一和多個值輸出到儲存體佇列。The following example demonstrates how to output single and multiple values to storage queues. 函數. json所需的設定也是相同的方式。The configuration needed for function.json is the same either way.

儲存體佇列系結定義于function. json中, 其中type設為queueA Storage queue binding is defined in function.json where type is set to queue.

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    },
    {
      "type": "queue",
      "direction": "out",
      "name": "msg",
      "queueName": "outqueue",
      "connection": "AzureStorageQueuesConnectionString"
    }
  ]
}

若要在佇列上設定個別訊息, 請將單一值傳遞給set方法。To set a individual message on the queue, you pass a single value to the set method.

import azure.functions as func

def main(req: func.HttpRequest, msg: func.Out[str]) -> func.HttpResponse:

    input_msg = req.params.get('message')

    msg.set(input_msg)

    return 'OK'

若要在佇列上建立多個訊息, 請將參數宣告為適當的清單類型, 並將值陣列 (符合清單類型) 傳遞給set方法。To create multiple messages on the queue, declare a parameter as the appropriate list type and pass an array of values (that match the list type) to the set method.

import azure.functions as func
import typing

def main(req: func.HttpRequest, msg: func.Out[typing.List[str]]) -> func.HttpResponse:

    msg.set(['one', 'two'])

    return 'OK'

輸出 - 屬性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 property 描述Description
typetype n/an/a 必須設為 queueMust be set to queue. 當您在 Azure 入口網站中建立觸發程序時,會自動設定此屬性。This property is set automatically when you create the trigger in the Azure portal.
directiondirection n/an/a 必須設為 outMust be set to out. 當您在 Azure 入口網站中建立觸發程序時,會自動設定此屬性。This property is set automatically when you create the trigger in the Azure portal.
namename n/an/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 連接Connection 應用程式設定的名稱包含要用於此繫結的儲存體連接字串。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# 指令碼中,paramNamefunction.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
Bob、資料表、佇列Blob, Table, Queue 儲存體錯誤碼Storage Error Codes
Bob、資料表、佇列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.

注意

有關 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).
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