Azure Functions 的 Azure 服務匯流排繫結Azure Service Bus bindings for Azure Functions

本文說明如何在 Azure Functions 中使用 Azure 服務匯流排繫結。This article explains how to work with Azure Service Bus bindings in Azure Functions. Azure Functions 支援服務匯流排佇列和主題的觸發程序和輸出繫結。Azure Functions supports trigger and output bindings for Service Bus queues and topics.

這是 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.ServiceBus NuGet 套件 2.x 版中會提供服務匯流排繫結。The Service Bus bindings are provided in the Microsoft.Azure.WebJobs.ServiceBus NuGet package, version 2.x.

下表說明如何在每個開發環境中為此繫結新增支援。The following table tells how to add support for this binding in each development environment.

開發環境Development environment 若要新增支援To add support in
Functions 1.xFunctions 1.x
本機開發 - C# 類別庫Local development - C# class library 安裝套件Install the package
本機開發 - C# 指令碼、JavaScript、F#Local development - C# script, JavaScript, F# 自動Automatic
入口網站開發Portal development 自動Automatic

套件 - Functions 2.xPackages - Functions 2.x

Microsoft.Azure.WebJobs.Extensions.ServiceBus NuGet 套件 3.x 版會提供服務匯流排繫結。The Service Bus bindings are provided in the Microsoft.Azure.WebJobs.Extensions.ServiceBus 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.

觸發程序Trigger

使用服務匯流排觸發程序來回應來自服務匯流排佇列或主題的訊息。Use the Service Bus trigger to respond to messages from a Service Bus queue or topic.

觸發程序 - 範例Trigger - example

請參閱特定語言的範例:See the language-specific example:

觸發程序 - C# 範例Trigger - C# example

下列範例示範的 C# 函式可讀取訊息中繼資料和記錄服務匯流排佇列訊息:The following example shows a C# function that reads message metadata and logs a Service Bus queue message:

[FunctionName("ServiceBusQueueTriggerCSharp")]                    
public static void Run(
    [ServiceBusTrigger("myqueue", AccessRights.Manage, Connection = "ServiceBusConnection")] 
    string myQueueItem,
    Int32 deliveryCount,
    DateTime enqueuedTimeUtc,
    string messageId,
    ILogger log)
{
    log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
    log.LogInformation($"EnqueuedTimeUtc={enqueuedTimeUtc}");
    log.LogInformation($"DeliveryCount={deliveryCount}");
    log.LogInformation($"MessageId={messageId}");
}

此範例適用於 Azure Functions 1.x 版。This example is for Azure Functions version 1.x. 若要讓此程式碼適用於 2.x:To make this code work for 2.x:

觸發程序 - C# 指令碼範例Trigger - C# script example

下列範例示範 function.json 檔案中的服務匯流排觸發程序繫結,以及使用此繫結的 C# 指令碼函式The following example shows a Service Bus trigger binding in a function.json file and a C# script function that uses the binding. 此函式可讀取訊息中繼資料和記錄服務匯流排佇列訊息。The function reads message metadata and logs a Service Bus queue message.

以下是 function.json 檔案中的繫結資料:Here's the binding data in the function.json file:

{
"bindings": [
    {
    "queueName": "testqueue",
    "connection": "MyServiceBusConnection",
    "name": "myQueueItem",
    "type": "serviceBusTrigger",
    "direction": "in"
    }
],
"disabled": false
}

以下是 C# 指令碼程式碼:Here's the C# script code:

using System;

public static void Run(string myQueueItem,
    Int32 deliveryCount,
    DateTime enqueuedTimeUtc,
    string messageId,
    TraceWriter log)
{
    log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");

    log.Info($"EnqueuedTimeUtc={enqueuedTimeUtc}");
    log.Info($"DeliveryCount={deliveryCount}");
    log.Info($"MessageId={messageId}");
}

觸發程序 - F# 範例Trigger - F# example

下列範例示範 function.json 檔案中的服務匯流排觸發程序繫結,以及使用此繫結的 F# 函式The following example shows a Service Bus trigger binding in a function.json file and an F# function that uses the binding. 此函式可記錄服務匯流排佇列訊息。The function logs a Service Bus queue message.

以下是 function.json 檔案中的繫結資料:Here's the binding data in the function.json file:

{
"bindings": [
    {
    "queueName": "testqueue",
    "connection": "MyServiceBusConnection",
    "name": "myQueueItem",
    "type": "serviceBusTrigger",
    "direction": "in"
    }
],
"disabled": false
}

以下是 F# 指令碼程式碼:Here's the F# script code:

let Run(myQueueItem: string, log: ILogger) =
    log.LogInformation(sprintf "F# ServiceBus queue trigger function processed message: %s" myQueueItem)

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

下列 java 函式會使用@ServiceBusQueueTrigger java 函式運行時間程式庫中的注釋來描述服務匯流排佇列觸發程式的設定。The following Java function uses the @ServiceBusQueueTrigger annotation from the Java functions runtime library to describe the configuration for a Service Bus queue trigger. 函式會抓取放在佇列上的訊息, 並將它新增至記錄。The function grabs the message placed on the queue and adds it to the logs.

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

當訊息新增至服務匯流排主題時, 也會觸發 JAVA 函式。Java functions can also be triggered when a message is added to a Service Bus topic. 下列範例會使用@ServiceBusTopicTrigger批註來描述觸發程式設定。The following example uses the @ServiceBusTopicTrigger annotation to describe the trigger configuration.

@FunctionName("sbtopicprocessor")
    public void run(
        @ServiceBusTopicTrigger(
            name = "message",
            topicName = "mytopicname",
            subscriptionName = "mysubscription",
            connection = "ServiceBusConnection"
        ) String message,
        final ExecutionContext context
    ) {
        context.getLogger().info(message);
    }

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

下列範例示範 function.json 檔案中的服務匯流排觸發程序繫結,以及使用此繫結的 JavaScript 函式The following example shows a Service Bus trigger binding in a function.json file and a JavaScript function that uses the binding. 此函式可讀取訊息中繼資料和記錄服務匯流排佇列訊息。The function reads message metadata and logs a Service Bus queue message.

以下是 function.json 檔案中的繫結資料:Here's the binding data in the function.json file:

{
"bindings": [
    {
    "queueName": "testqueue",
    "connection": "MyServiceBusConnection",
    "name": "myQueueItem",
    "type": "serviceBusTrigger",
    "direction": "in"
    }
],
"disabled": false
}

以下是 JavaScript 指令碼程式碼:Here's the JavaScript script code:

module.exports = function(context, myQueueItem) {
    context.log('Node.js ServiceBus queue trigger function processed message', myQueueItem);
    context.log('EnqueuedTimeUtc =', context.bindingData.enqueuedTimeUtc);
    context.log('DeliveryCount =', context.bindingData.deliveryCount);
    context.log('MessageId =', context.bindingData.messageId);
    context.done();
};

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

下列範例示範如何透過觸發程式來讀取「執行匯流排佇列」訊息。The following example demonstrates how to read a ServiceBus queue message via a trigger.

在函式中定義了 「匯流排系結」, 其中類型設定為serviceBusTriggerA ServiceBus binding is defined in function.json where type is set to serviceBusTrigger.

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "msg",
      "type": "serviceBusTrigger",
      "direction": "in",
      "queueName": "inputqueue",
      "connection": "AzureServiceBusConnectionString"
    }
  ]
}

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

import azure.functions as func

import logging
import json

def main(msg: func.ServiceBusMessage):
    logging.info('Python ServiceBus queue trigger processed message.')

    result = json.dumps({
        'message_id': msg.message_id,
        'body': msg.get_body().decode('utf-8'),
        'content_type': msg.content_type,
        'expiration_time': msg.expiration_time,
        'label': msg.label,
        'partition_key': msg.partition_key,
        'reply_to': msg.reply_to,
        'reply_to_session_id': msg.reply_to_session_id,
        'scheduled_enqueue_time': msg.scheduled_enqueue_time,
        'session_id': msg.session_id,
        'time_to_live': msg.time_to_live,
        'to': msg.to,
        'user_properties': msg.user_properties,
    })

    logging.info(result)

觸發程序 - 屬性Trigger - attributes

C# 類別庫中,使用下列屬性以設定服務匯流排觸發程序:In C# class libraries, use the following attributes to configure a Service Bus trigger:

  • ServiceBusTriggerAttributeServiceBusTriggerAttribute

    該屬性的建構函式會採用佇列名稱或標題和訂用帳戶。The attribute's constructor takes the name of the queue or the topic and subscription. 在 Azure Functions 第 1.x 版中,您也可以指定連線的存取權限。In Azure Functions version 1.x, you can also specify the connection's access rights. 如果您未指定存取權限,則預設值為 ManageIf you don't specify access rights, the default is Manage. 如需詳細資訊,請參閱觸發程序 - 組態一節。For more information, see the Trigger - configuration section.

    以下範例顯示搭配字串參數使用的屬性:Here's an example that shows the attribute used with a string parameter:

    [FunctionName("ServiceBusQueueTriggerCSharp")]                    
    public static void Run(
        [ServiceBusTrigger("myqueue")] string myQueueItem, ILogger log)
    {
        ...
    }
    

    您可以設定 Connection 屬性來指定要使用的服務匯流排帳戶,如下列範例所示:You can set the Connection property to specify the Service Bus account to use, as shown in the following example:

    [FunctionName("ServiceBusQueueTriggerCSharp")]                    
    public static void Run(
        [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] 
        string myQueueItem, ILogger log)
    {
        ...
    }
    

    如需完整範例,請參閱觸發程序 - C# 範例For a complete example, see Trigger - C# example.

  • ServiceBusAccountAttributeServiceBusAccountAttribute

    提供另一種方式來指定要使用的服務匯流排帳戶。Provides another way to specify the Service Bus account to use. 建構函式會採用內含服務匯流排連接字串的應用程式設定名稱。The constructor takes the name of an app setting that contains a Service Bus connection string. 屬性可以套用在參數、方法或類別層級。The attribute can be applied at the parameter, method, or class level. 下列範例所示範的是類別層級與方法層級:The following example shows class level and method level:

    [ServiceBusAccount("ClassLevelServiceBusAppSetting")]
    public static class AzureFunctions
    {
        [ServiceBusAccount("MethodLevelServiceBusAppSetting")]
        [FunctionName("ServiceBusQueueTriggerCSharp")]
        public static void Run(
            [ServiceBusTrigger("myqueue", AccessRights.Manage)] 
            string myQueueItem, ILogger log)
    {
        ...
    }
    

要使用的服務匯流排帳戶按以下順序決定:The Service Bus account to use is determined in the following order:

  • ServiceBusTrigger 屬性的 Connection 內容。The ServiceBusTrigger attribute's Connection property.
  • ServiceBusAccount 屬性套用至與 ServiceBusTrigger 屬性相同的參數。The ServiceBusAccount attribute applied to the same parameter as the ServiceBusTrigger attribute.
  • ServiceBusAccount 屬性套用至該函式。The ServiceBusAccount attribute applied to the function.
  • ServiceBusAccount 屬性套用至該類別。The ServiceBusAccount attribute applied to the class.
  • "AzureWebJobsServiceBus" 應用程式設定。The "AzureWebJobsServiceBus" app setting.

觸發程式 - 設定Trigger - configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 ServiceBusTrigger 屬性。The following table explains the binding configuration properties that you set in the function.json file and the ServiceBusTrigger attribute.

function.json 屬性function.json property 屬性內容Attribute property 描述Description
typetype n/an/a 必須設定為 "serviceBusTrigger"。Must be set to "serviceBusTrigger". 當您在 Azure 入口網站中建立觸發程序時,會自動設定此屬性。This property is set automatically when you create the trigger in the Azure portal.
directiondirection n/an/a 必須設定為 "in"。Must 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 represents the queue or topic message in function code. 設為 "$return" 以參考函式傳回值。Set to "$return" to reference the function return value.
queueNamequeueName QueueNameQueueName 要監視的佇列名稱。Name of the queue to monitor. 只有在監視佇列時設定 (不適用於主題)。Set only if monitoring a queue, not for a topic.
topicNametopicName TopicNameTopicName 要監視的主題名稱。Name of the topic to monitor. 只有在監視主題時設定 (不適用於佇列)。Set only if monitoring a topic, not for a queue.
subscriptionNamesubscriptionName SubscriptionNameSubscriptionName 要監視的訂用帳戶名稱。Name of the subscription to monitor. 只有在監視主題時設定 (不適用於佇列)。Set only if monitoring a topic, not for a queue.
連接connection 連接Connection 應用程式設定的名稱包含要用於此繫結的服務匯流排連接字串。The name of an app setting that contains the Service Bus 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. 例如,如果您將 connection 設定為 "MyServiceBus",則 Functions 執行階段會尋找名稱為 "AzureWebJobsMyServiceBus" 的應用程式設定。For example, if you set connection to "MyServiceBus", the Functions runtime looks for an app setting that is named "AzureWebJobsMyServiceBus." 如果您將 connection 保留空白,則 Functions 執行階段會使用應用程式設定中名稱為 "AzureWebJobsServiceBus" 的預設服務匯流排連接字串。If you leave connection empty, the Functions runtime uses the default Service Bus connection string in the app setting that is named "AzureWebJobsServiceBus".

若要取得連接字串,請遵循取得管理認證所示的步驟。To obtain a connection string, follow the steps shown at Get the management credentials. 連接字串必須是用於服務匯流排命名空間,而不限於特定佇列或主題。The connection string must be for a Service Bus namespace, not limited to a specific queue or topic.
accessRightsaccessRights AccessAccess 連接字串的存取權限。Access rights for the connection string. 可用值為 managelistenAvailable values are manage and listen. 預設值是 manage,這表示 connection 已具備管理權限。The default is manage, which indicates that the connection has the Manage permission. 如果您使用沒有管理權限的連接字串,請將 accessRights 設定為 "listen"。If you use a connection string that does not have the Manage permission, set accessRights to "listen". 否則,Functions 執行階段在嘗試執行需要管理權限的作業時可能會失敗。Otherwise, the Functions runtime might fail trying to do operations that require manage rights. 在 Azure Functions 第 2.x 版中,這個屬性無法使用,因為最新版的儲存體 SDK 不支援管理作業。In Azure Functions version 2.x, this property is not available because the latest version of the Storage SDK doesn't support manage operations.

當您要在本機開發時,應用程式設定會進入 local.settings.json 檔案When you're developing locally, app settings go into the local.settings.json file.

觸發程序 - 使用方式Trigger - usage

在 C# 和 C# 指令碼中,您可以針對佇列或主題訊息使用下列參數類型:In C# and C# script, you can use the following parameter types for the queue or topic message:

  • string - 如果訊息是文字。string - If the message is text.
  • byte[] - 適用於二進位資料。byte[] - Useful for binary data.
  • 自訂類型 - 如果訊息包含 JSON,Azure Functions 會嘗試將 JSON 資料還原序列化。A custom type - If the message contains JSON, Azure Functions tries to deserialize the JSON data.
  • BrokeredMessage-提供您使用BrokeredMessage. GetBody<T > ()方法還原序列化的訊息。BrokeredMessage - Gives you the deserialized message with the BrokeredMessage.GetBody<T>() method.

這些參數適用於 Azure Functions 版本 1.x;針對 2.x,請使用 Message,而不是使用 BrokeredMessageThese parameters are for Azure Functions version 1.x; for 2.x, use Message instead of BrokeredMessage.

在 JavaScript 中,使用 context.bindings.<name from function.json> 來存取佇列或主題訊息。In JavaScript, access the queue or topic message by using context.bindings.<name from function.json>. 服務匯流排訊息會以字串或 JSON 物件的形式傳遞至函式。The Service Bus message is passed into the function as either a string or JSON object.

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

無法在 Azure Functions 中控制或設定有害訊息處理。Poison message handling can't be controlled or configured in Azure Functions. 服務匯流排會自行處理有害訊息。Service Bus handles poison messages itself.

觸發程序 - PeekLock 行為Trigger - PeekLock behavior

Functions 執行階段會在 PeekLock 模式中收到訊息。The Functions runtime receives a message in PeekLock mode. 它會在函數成功完成時,於訊息中呼叫 Complete,或是在函數失敗時呼叫 AbandonIt calls Complete on the message if the function finishes successfully, or calls Abandon if the function fails. 如果函式執行時間較 PeekLock 逾時還長,只要函式正在執行中,就會自動更新鎖定。If the function runs longer than the PeekLock timeout, the lock is automatically renewed as long as the function is running.

maxAutoRenewDurationhost.json 中是可設定的,其對應至 OnMessageOptions.MaxAutoRenewDurationThe maxAutoRenewDuration is configurable in host.json, which maps to OnMessageOptions.MaxAutoRenewDuration. 根據服務匯流排文件,此設定允許的上限為 5 分鐘,而您可以將 Functions 時間限制從預設的 5 分鐘增加至 10 分鐘。The maximum allowed for this setting is 5 minutes according to the Service Bus documentation, whereas you can increase the Functions time limit from the default of 5 minutes to 10 minutes. 您不會想對服務匯流排函式這麼做,因為您會超過服務匯流排更新限制。For Service Bus functions you wouldn’t want to do that then, because you’d exceed the Service Bus renewal limit.

觸發程序 - 訊息中繼資料Trigger - message metadata

服務匯流排觸發程序提供數個中繼資料屬性The Service Bus trigger provides several metadata properties. 這些屬性可作為其他繫結中繫結運算式的一部分或程式碼中的參數使用。These properties can be used as part of binding expressions in other bindings or as parameters in your code. 這些是 BrokeredMessage 類別的屬性。These are properties of the BrokeredMessage class.

屬性Property 類型Type 描述Description
DeliveryCount Int32 傳遞數目。The number of deliveries.
DeadLetterSource string 無效信件來源。The dead letter source.
ExpiresAtUtc DateTime 到期時間 (UTC)。The expiration time in UTC.
EnqueuedTimeUtc DateTime 加入佇列的時間 (UTC)。The enqueued time in UTC.
MessageId string 服務匯流排可用來識別重複訊息的使用者定義值 (如果已啟用)。A user-defined value that Service Bus can use to identify duplicate messages, if enabled.
ContentType string 由傳送者和接收者使用於應用程式特定邏輯的內容類型識別碼。A content type identifier utilized by the sender and receiver for application specific logic.
ReplyTo string 回覆佇列位址。The reply to queue address.
SequenceNumber Int64 由服務匯流排指派給訊息的唯一編號。The unique number assigned to a message by the Service Bus.
To string 傳送位址。The send to address.
Label string 應用程式專用標籤。The application specific label.
CorrelationId string 相互關連識別碼。The correlation ID.

注意

目前, 服務匯流排觸發程式適用于已啟用會話的佇列和訂用帳戶。Currently, Service bus trigger that works with session enabled queues and subscriptions is in preview. 請追蹤此專案, 以取得與此相關的任何進一步更新。Please track this item for any further updates regarding this.

請參閱稍早在本文中使用這些屬性的程式碼範例See code examples that use these properties earlier in this article.

觸發程序 - host.json 屬性Trigger - host.json properties

host.json 檔案包含可控制服務匯流排觸發程序行為的設定。The host.json file contains settings that control Service Bus trigger behavior.

{
    "serviceBus": {
      "maxConcurrentCalls": 16,
      "prefetchCount": 100,
      "maxAutoRenewDuration": "00:05:00"
    }
}
屬性Property 預設Default 描述Description
maxConcurrentCallsmaxConcurrentCalls 1616 訊息幫浦應該起始之回呼的並行呼叫數上限。The maximum number of concurrent calls to the callback that the message pump should initiate. Functions 執行階段預設會並行處理多個訊息。By default, the Functions runtime processes multiple messages concurrently. 若要指示執行階段一次只處理一個佇列或主題訊息,請將 maxConcurrentCalls 設定為 1。To direct the runtime to process only a single queue or topic message at a time, set maxConcurrentCalls to 1.
prefetchCountprefetchCount n/an/a 基礎 MessageReceiver 將使用的預設 PrefetchCount。The default PrefetchCount that will be used by the underlying MessageReceiver.
maxAutoRenewDurationmaxAutoRenewDuration 00:05:0000:05:00 將自動更新訊息鎖定的最大持續時間。The maximum duration within which the message lock will be renewed automatically.

OutputOutput

使用 Azure 服務匯流排輸出繫結來傳送佇列或主題訊息。Use Azure Service Bus output binding to send queue or topic messages.

輸出 - 範例Output - example

請參閱特定語言的範例:See the language-specific example:

輸出 - C# 範例Output - C# example

下列範例示範的 C# 函式可記錄服務匯流排佇列訊息:The following example shows a C# function that sends a Service Bus queue message:

[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue", Connection = "ServiceBusConnection")]
public static string ServiceBusOutput([HttpTrigger] dynamic input, ILogger log)
{
    log.LogInformation($"C# function processed: {input.Text}");
    return input.Text;
}

輸出 - C# 指令碼範例Output - C# script example

下列範例示範 function.json 檔案中的服務匯流排輸出繫結,以及使用此繫結的 C# 指令碼函式The following example shows a Service Bus output binding in a function.json file and a C# script function that uses the binding. 此函式會使用計時器觸發程序,每隔 15 秒傳送一則佇列訊息。The function uses a timer trigger to send a queue message every 15 seconds.

以下是 function.json 檔案中的繫結資料:Here's the binding data in the function.json file:

{
    "bindings": [
        {
            "schedule": "0/15 * * * * *",
            "name": "myTimer",
            "runsOnStartup": true,
            "type": "timerTrigger",
            "direction": "in"
        },
        {
            "name": "outputSbQueue",
            "type": "serviceBus",
            "queueName": "testqueue",
            "connection": "MyServiceBusConnection",
            "direction": "out"
        }
    ],
    "disabled": false
}

以下是可建立單一訊息的 C# 指令碼程式碼:Here's C# script code that creates a single message:

public static void Run(TimerInfo myTimer, ILogger log, out string outputSbQueue)
{
    string message = $"Service Bus queue message created at: {DateTime.Now}";
    log.LogInformation(message); 
    outputSbQueue = message;
}

以下是可建立多則訊息的 C# 指令碼程式碼:Here's C# script code that creates multiple messages:

public static void Run(TimerInfo myTimer, ILogger log, ICollector<string> outputSbQueue)
{
    string message = $"Service Bus queue messages created at: {DateTime.Now}";
    log.LogInformation(message); 
    outputSbQueue.Add("1 " + message);
    outputSbQueue.Add("2 " + message);
}

輸出 - F# 範例Output - F# example

下列範例示範 function.json 檔案中的服務匯流排觸發程序繫結,以及使用此繫結的 F# 指令碼函式The following example shows a Service Bus output binding in a function.json file and an F# script function that uses the binding. 此函式會使用計時器觸發程序,每隔 15 秒傳送一則佇列訊息。The function uses a timer trigger to send a queue message every 15 seconds.

以下是 function.json 檔案中的繫結資料:Here's the binding data in the function.json file:

{
    "bindings": [
        {
            "schedule": "0/15 * * * * *",
            "name": "myTimer",
            "runsOnStartup": true,
            "type": "timerTrigger",
            "direction": "in"
        },
        {
            "name": "outputSbQueue",
            "type": "serviceBus",
            "queueName": "testqueue",
            "connection": "MyServiceBusConnection",
            "direction": "out"
        }
    ],
    "disabled": false
}

以下是可建立單一訊息的 F# 指令碼程式碼:Here's F# script code that creates a single message:

let Run(myTimer: TimerInfo, log: ILogger, outputSbQueue: byref<string>) =
    let message = sprintf "Service Bus queue message created at: %s" (DateTime.Now.ToString())
    log.LogInformation(message)
    outputSbQueue = message

輸出 - Java 範例Output - Java example

下列範例所示範的 Java 函式,會在經由 HTTP 要求觸發時,傳送訊息給服務匯流排佇列 myqueueThe following example shows a Java function that sends a message to a Service Bus queue myqueue when triggered by a HTTP request.

@FunctionName("httpToServiceBusQueue")
@ServiceBusQueueOutput(name = "message", queueName = "myqueue", connection = "AzureServiceBusConnection")
public String pushToQueue(
  @HttpTrigger(name = "request", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
  final String message,
  @HttpOutput(name = "response") final OutputBinding<T> result ) {
      result.setValue(message + " has been sent.");
      return message;
 }

Java 函式執行階段程式庫中,對其值要寫入至服務匯流排佇列的函式參數使用 @QueueOutput 註釋。In the Java functions runtime library, use the @QueueOutput annotation on function parameters whose value would be written to a Service Bus queue. 參數類型應為 OutputBinding<T>,其中 T 是任何原生 Java 類型的 POJO。The parameter type should be OutputBinding<T>, where T is any native Java type of a POJO.

JAVA 函數也可以寫入服務匯流排主題。Java functions can also write to a Service Bus topic. 下列範例會使用@ServiceBusTopicOutput批註來描述輸出系結的設定。The following example uses the @ServiceBusTopicOutput annotation to describe the configuration for the output binding.

@FunctionName("sbtopicsend")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
            @ServiceBusTopicOutput(name = "message", topicName = "mytopicname", subscriptionName = "mysubscription", connection = "ServiceBusConnection") OutputBinding<String> message,
            final ExecutionContext context) {
        
        String name = request.getBody().orElse("Azure Functions");

        message.setValue(name);
        return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();
        
    }

輸出 - JavaScript 範例Output - JavaScript example

下列範例示範 function.json 檔案中的服務匯流排觸發程序繫結,以及使用此繫結的 JavaScript 函式The following example shows a Service Bus output binding in a function.json file and a JavaScript function that uses the binding. 此函式會使用計時器觸發程序,每隔 15 秒傳送一則佇列訊息。The function uses a timer trigger to send a queue message every 15 seconds.

以下是 function.json 檔案中的繫結資料:Here's the binding data in the function.json file:

{
    "bindings": [
        {
            "schedule": "0/15 * * * * *",
            "name": "myTimer",
            "runsOnStartup": true,
            "type": "timerTrigger",
            "direction": "in"
        },
        {
            "name": "outputSbQueue",
            "type": "serviceBus",
            "queueName": "testqueue",
            "connection": "MyServiceBusConnection",
            "direction": "out"
        }
    ],
    "disabled": false
}

以下是可建立單一訊息的 JavaScript 指令碼程式碼:Here's JavaScript script code that creates a single message:

module.exports = function (context, myTimer) {
    var message = 'Service Bus queue message created at ' + timeStamp;
    context.log(message);   
    context.bindings.outputSbQueue = message;
    context.done();
};

以下是可建立多則訊息的 JavaScript 指令碼程式碼:Here's JavaScript script code that creates multiple messages:

module.exports = function (context, myTimer) {
    var message = 'Service Bus queue message created at ' + timeStamp;
    context.log(message);   
    context.bindings.outputSbQueue = [];
    context.bindings.outputSbQueue.push("1 " + message);
    context.bindings.outputSbQueue.push("2 " + message);
    context.done();
};

輸出 - Python 範例Output - Python example

下列範例示範如何寫出 Python 中的執行匯流排佇列。The following example demonstrates how to write out to a ServiceBus queue in Python.

ServiceBue 系結定義定義于function json中, 其中type設為serviceBusA ServiceBue binding definition is defined in function.json where type is set to serviceBus.

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

.py _ 中, 您可以藉由將值傳遞給方法, 將訊息寫出至佇列。_ setIn _init_.py, you can write out a message to the queue by passing a 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'

輸出 - 屬性Output - attributes

C# 類別程式庫中,使用 ServiceBusAttributeIn C# class libraries, use the ServiceBusAttribute.

該屬性的建構函式會採用佇列名稱或標題和訂用帳戶。The attribute's constructor takes the name of the queue or the topic and subscription. 您也可以指定連線的存取權限。You can also specify the connection's access rights. 輸出 - 組態一節說明如何選擇存取權限設定。How to choose the access rights setting is explained in the Output - configuration section. 以下範例顯示套用至函式傳回值的屬性:Here's an example that shows the attribute applied to the return value of the function:

[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue")]
public static string Run([HttpTrigger] dynamic input, ILogger log)
{
    ...
}

您可以設定 Connection 屬性來指定要使用的服務匯流排帳戶,如下列範例所示:You can set the Connection property to specify the Service Bus account to use, as shown in the following example:

[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue", Connection = "ServiceBusConnection")]
public static string Run([HttpTrigger] dynamic input, ILogger log)
{
    ...
}

如需完整範例,請參閱輸出 - C# 範例For a complete example, see Output - C# example.

您可以使用 ServiceBusAccount 屬性來指定要在類別、方法或參數層級使用的服務匯流排帳戶。You can use the ServiceBusAccount attribute to specify the Service Bus account to use at class, method, or parameter level. 如需詳細資訊,請參閱觸發程序 - 屬性For more information, see Trigger - attributes.

輸出 - 設定Output - configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 ServiceBus 屬性。The following table explains the binding configuration properties that you set in the function.json file and the ServiceBus attribute.

function.json 屬性function.json property 屬性內容Attribute property 描述Description
typetype n/an/a 必須設為 "serviceBus"。Must be set to "serviceBus". 當您在 Azure 入口網站中建立觸發程序時,會自動設定此屬性。This property is set automatically when you create the trigger in the Azure portal.
directiondirection n/an/a 必須設定為 "out"。Must 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 or topic in function code. 設為 "$return" 以參考函式傳回值。Set to "$return" to reference the function return value.
queueNamequeueName QueueNameQueueName 佇列的名稱。Name of the queue. 只有在傳送佇列訊息時設定 (不適用於主題)。Set only if sending queue messages, not for a topic.
topicNametopicName TopicNameTopicName 要監視的主題名稱。Name of the topic to monitor. 只有在傳送主題訊息時設定 (不適用於佇列)。Set only if sending topic messages, not for a queue.
連接connection 連接Connection 應用程式設定的名稱包含要用於此繫結的服務匯流排連接字串。The name of an app setting that contains the Service Bus 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. 例如,如果您將 connection 設定為 "MyServiceBus",則 Functions 執行階段會尋找名稱為 "AzureWebJobsMyServiceBus" 的應用程式設定。For example, if you set connection to "MyServiceBus", the Functions runtime looks for an app setting that is named "AzureWebJobsMyServiceBus." 如果您將 connection 保留空白,則 Functions 執行階段會使用應用程式設定中名稱為 "AzureWebJobsServiceBus" 的預設服務匯流排連接字串。If you leave connection empty, the Functions runtime uses the default Service Bus connection string in the app setting that is named "AzureWebJobsServiceBus".

若要取得連接字串,請遵循取得管理認證所示的步驟。To obtain a connection string, follow the steps shown at Get the management credentials. 連接字串必須是用於服務匯流排命名空間,而不限於特定佇列或主題。The connection string must be for a Service Bus namespace, not limited to a specific queue or topic.
accessRightsaccessRights AccessAccess 連接字串的存取權限。Access rights for the connection string. 可用值為 managelistenAvailable values are manage and listen. 預設值是 manage,這表示 connection 已具備管理權限。The default is manage, which indicates that the connection has the Manage permission. 如果您使用沒有管理權限的連接字串,請將 accessRights 設定為 "listen"。If you use a connection string that does not have the Manage permission, set accessRights to "listen". 否則,Functions 執行階段在嘗試執行需要管理權限的作業時可能會失敗。Otherwise, the Functions runtime might fail trying to do operations that require manage rights. 在 Azure Functions 第 2.x 版中,這個屬性無法使用,因為最新版的儲存體 SDK 不支援管理作業。In Azure Functions version 2.x, this property is not available because the latest version of the Storage SDK doesn't support manage operations.

當您要在本機開發時,應用程式設定會進入 local.settings.json 檔案When you're developing locally, app settings go into the local.settings.json file.

輸出 - 使用方式Output - usage

在 Azure Functions 1.x 中,執行階段會建立佇列 (如果佇列不存在),且您已將 accessRights 設為 manageIn Azure Functions 1.x, the runtime creates the queue if it doesn't exist and you have set accessRights to manage. 在 Functions 第 2.x 版中,佇列或主題必須已經存在;如果您指定的佇列或主題不存在,此函式就會失敗。In Functions version 2.x, the queue or topic must already exist; if you specify a queue or topic that doesn't exist, the function will fail.

在 C# 和 C# 指令碼中,您可以針對輸出繫結使用下列參數類型:In C# and C# script, you can use the following parameter types for the output binding:

  • out T paramName - T 可以是任何可序列化 JSON 的類型。out T paramName - T can be any JSON-serializable type. 當函式結束時,如果參數值為 Null,則 Functions 會使用 Null 物件建立訊息。If the parameter value is null when the function exits, Functions creates the message with a null object.
  • out string - 當函式結束時,如果參數值為 Null,則 Functions 不會建立一則訊息。out string - If the parameter value is null when the function exits, Functions does not create a message.
  • out byte[] - 當函式結束時,如果參數值為 Null,則 Functions 不會建立一則訊息。out byte[] - If the parameter value is null when the function exits, Functions does not create a message.
  • out BrokeredMessage-如果函式結束時, 參數值為 null, 函數不會建立訊息 (針對函式 1.x)out BrokeredMessage - If the parameter value is null when the function exits, Functions does not create a message (for Functions 1.x)
  • out Message-如果函式結束時, 參數值為 null, 函數不會建立訊息 (針對函式 2.x)out Message - If the parameter value is null when the function exits, Functions does not create a message (for Functions 2.x)
  • ICollector<T>IAsyncCollector<T> - 適用於建立多個訊息。ICollector<T> or IAsyncCollector<T> - For creating multiple messages. 當您呼叫 Add 方法時,就會建立一則訊息。A message is created when you call the Add method.

使用C#函數時:When working with C# functions:

  • 非同步函數需要傳回值或IAsyncCollector , 而不out是參數。Async functions need a return value or IAsyncCollector instead of an out parameter.

  • 若要存取會話識別碼, 請系結Message至類型, 並sessionId使用屬性。To access the session ID, bind to a Message type and use the sessionId property.

在 JavaScript 中,使用 context.bindings.<name from function.json> 來存取佇列或主題。In JavaScript, access the queue or topic by using context.bindings.<name from function.json>. 您可以將字串、位元組陣列或 JavaScript 物件 (還原序列化為 JSON) 指派給context.binding.<name>You can assign a string, a byte array, or a JavaScript object (deserialized into JSON) to context.binding.<name>.

若要以非C#語言將訊息傳送至啟用會話的佇列, 請使用Azure 服務匯流排 SDK , 而不是內建的輸出系結。To send a message to a session-enabled queue in non-C# languages, use the Azure Service Bus SDK rather than the built-in output binding.

例外狀況和傳回碼Exceptions and return codes

繫結Binding 參考資料Reference
服務匯流排Service Bus 服務匯流排錯誤碼Service Bus Error Codes
服務匯流排Service Bus 服務匯流排限制Service Bus Limits

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": {
        "serviceBus": {
            "prefetchCount": 100,
            "messageHandlerOptions": {
                "autoComplete": false,
                "maxConcurrentCalls": 32,
                "maxAutoRenewDuration": "00:55:00"
            }
        }
    }
}
屬性Property 預設Default 描述Description
maxAutoRenewDurationmaxAutoRenewDuration 00:05:0000:05:00 將自動更新訊息鎖定的最大持續時間。The maximum duration within which the message lock will be renewed automatically.
autoCompleteautoComplete truetrue 無論觸發程序是否應立即標示為完成 (自動完成) 或等待呼叫完成處理。Whether the trigger should immediately mark as complete (autocomplete) or wait for processing to call complete.
maxConcurrentCallsmaxConcurrentCalls 1616 訊息幫浦應該起始之回呼的並行呼叫數上限。The maximum number of concurrent calls to the callback that the message pump should initiate. Functions 執行階段預設會並行處理多個訊息。By default, the Functions runtime processes multiple messages concurrently. 若要指示執行階段一次只處理一個佇列或主題訊息,請將 maxConcurrentCalls 設定為 1。To direct the runtime to process only a single queue or topic message at a time, set maxConcurrentCalls to 1.
prefetchCountprefetchCount n/an/a 基礎 MessageReceiver 將使用的預設 PrefetchCount。The default PrefetchCount that will be used by the underlying MessageReceiver.

後續步驟Next steps