您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

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 函数使用 Java 函数运行时库中的 @ServiceBusQueueTrigger 注释来说明服务总线队列触发器的配置。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.

在将类型设置为serviceBusTrigger函数 json中定义了一个 "//" 绑定。A 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.
  • 作为 ServiceBusTrigger 特性应用到同一参数的 ServiceBusAccount 特性。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 属性Attribute property 说明Description
typetype 不适用n/a 必须设置为“serviceBusTrigger”。Must be set to "serviceBusTrigger". 在 Azure 门户中创建触发器时,会自动设置此属性。This property is set automatically when you create the trigger in the Azure portal.
directiondirection 不适用n/a 必须设置为“in”。Must be set to "in". 在 Azure 门户中创建触发器时,会自动设置此属性。This property is set automatically when you create the trigger in the Azure portal.
名称name 不适用n/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 ConnectionConnection 应用设置的名称,包含要用于此绑定的服务总线连接字符串。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”,函数运行时将会查找名为“AzureWebJobsMyServiceBus”的应用设置。For example, if you set connection to "MyServiceBus", the Functions runtime looks for an app setting that is named "AzureWebJobsMyServiceBus." 如果将 connection 留空,函数运行时将使用名为“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.

maxAutoRenewDuration 可在 host.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 typeType 描述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 相关 ID。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/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 是 POJO 的任何本机 Java 类型。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 绑定定义在类型设置为serviceBus函数 json中定义。A 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 属性Attribute property 说明Description
typetype 不适用n/a 必须设置为“serviceBus”。Must be set to "serviceBus". 在 Azure 门户中创建触发器时,会自动设置此属性。This property is set automatically when you create the trigger in the Azure portal.
directiondirection 不适用n/a 必须设置为“out”。Must be set to "out". 在 Azure 门户中创建触发器时,会自动设置此属性。This property is set automatically when you create the trigger in the Azure portal.
名称name 不适用n/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 ConnectionConnection 应用设置的名称,包含要用于此绑定的服务总线连接字符串。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”,函数运行时将会查找名为“AzureWebJobsMyServiceBus”的应用设置。For example, if you set connection to "MyServiceBus", the Functions runtime looks for an app setting that is named "AzureWebJobsMyServiceBus." 如果将 connection 留空,函数运行时将使用名为“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 设置为 manage,则运行时会创建队列。In 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,Functions 不创建消息。out BrokeredMessage - If the parameter value is null when the function exits, Functions does not create a message.
  • ICollector<T>IAsyncCollector<T> - 用于创建多条消息。ICollector<T> or IAsyncCollector<T> - For creating multiple messages. 调用 Add 方法时创建了一条消息。A message is created when you call the Add method.

在异步函数中,请使用返回值或 IAsyncCollector 而非 out 参数。In async functions, use the return value or IAsyncCollector instead of an out parameter.

这些参数仅适用于 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 by using context.bindings.<name from function.json>. 可以向 context.binding.<name> 分配一个字符串、字节数组或 Javascript 对象(反序列化为 JSON)。You can assign a string, a byte array, or a Javascript object (deserialized into JSON) to context.binding.<name>.

异常和返回代码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 true 触发器应立即标记为已完成(自动完成),还是等待调用完成的处理。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/a 基础 MessageReceiver 将要使用的默认 PrefetchCount。The default PrefetchCount that will be used by the underlying MessageReceiver.

后续步骤Next steps