Azure Functions 的 Azure 服务总线触发器Azure Service Bus trigger for Azure Functions

使用服务总线触发器响应来自服务总线队列或主题的消息。Use the Service Bus trigger to respond to messages from a Service Bus queue or topic. 从扩展版本 3.1.0 开始,可以在启用会话的队列或主题上触发。Starting with extension version 3.1.0, you can trigger on a session-enabled queue or topic.

有关设置和配置详细信息,请参阅概述For information on setup and configuration details, see the overview.


以下示例演示了读取消息元数据并记录服务总线队列消息的 C# 函数The following example shows a C# function that reads message metadata and logs a Service Bus queue message:

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

特性和注释Attributes and annotations

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:

    public static void Run(
        [ServiceBusTrigger("myqueue")] string myQueueItem, ILogger log)

    由于未定义 Connection 属性,因此 Azure Functions 将查找名为 AzureWebJobsServiceBus 的应用设置,这是服务总线连接字符串的默认名称。Since the Connection property isn't defined, Functions looks for an app setting named AzureWebJobsServiceBus, which is the default name for the Service Bus connection string. 还可以设置 Connection 属性来指定应用程序设置(其中包含要使用的服务总线连接字符串)的名称,如以下示例中所示:You can also set the Connection property to specify the name of an application setting that contains the Service Bus connection string to use, as shown in the following example:

    public static void Run(
        [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] 
        string myQueueItem, ILogger log)

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

    public static class AzureFunctions
        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.


下表解释了在 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.
namename 不适用n/a 变量的名称,表示函数代码中的队列或主题消息。The name of the variable that represents the queue or topic message in function code.
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”,Functions 运行时会查找名为“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 and higher, this property is not available because the latest version of the Service Bus SDK doesn't support manage operations.
isSessionsEnabledisSessionsEnabled IsSessionsEnabledIsSessionsEnabled 如果连接到会话感知队列或订阅,则为 truetrue if connecting to a session-aware queue or subscription. 否则为 false(默认值)。false otherwise, which is the default value.

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


以下参数类型可用于队列或主题消息:The following parameter types are available 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.
  • MessageReceiver - 用于接收和确认来自消息容器的消息(当 autoComplete 设置为 false 时为必需)MessageReceiver - Used to receive and acknowledge messages from the message container (required when autoComplete is set to false)

这些参数类型适用于 Azure Functions 版本 1.x;对于 2.x 及更高版本,请使用 Message 而非 BrokeredMessageThese parameter types are for Azure Functions version 1.x; for 2.x and higher, use Message instead of BrokeredMessage.

有害消息Poison messages

无法在 Azure Functions 中控制或配置有害消息处理。Poison message handling can't be controlled or configured in Azure Functions. 服务总线处理有害消息本身。Service Bus handles poison messages itself.

PeekLock 行为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.

消息元数据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. 以下属性是 Message 类的成员。These properties are members of the Message class.

属性Property 类型Type 说明Description
ContentType string 发送方和接收方用于实现应用程序特定逻辑的内容类型标识符。A content type identifier utilized by the sender and receiver for application-specific logic.
CorrelationId string 相关 ID。The correlation ID.
DeadLetterSource string 死信源。The dead letter source.
DeliveryCount Int32 传递次数。The number of deliveries.
EnqueuedTimeUtc DateTime 排队时间 (UTC)。The enqueued time in UTC.
ExpiresAtUtc DateTime 到期时间 (UTC)。The expiration time in UTC.
Label string 应用程序特定的标签。The application-specific label.
MessageId string 服务总线可用于标识重复消息的用户定义值(如果启用)。A user-defined value that Service Bus can use to identify duplicate messages, if enabled.
MessageReceiver MessageReceiver 服务总线消息接收器。Service Bus message receiver. 可以用于放弃、完成消息或将消息放入死信队列。Can be used to abandon, complete, or deadletter the message.
MessageSession MessageSession 专用于已启用会话的队列和主题的消息接收器。A message receiver specifically for session-enabled queues and topics.
ReplyTo string 对队列地址的回复。The reply to queue address.
SequenceNumber long 服务总线分配给消息的唯一编号。The unique number assigned to a message by the Service Bus.
To string 发送到地址。The send to address.
UserProperties IDictionary<string, object> 由发送方设置的属性。Properties set by the sender.

请参阅在本文的前面部分使用这些属性的代码示例See code examples that use these properties earlier in this article.

后续步骤Next steps