适用于 Azure Functions 的 Azure 服务总线输出绑定Azure Service Bus output binding for Azure Functions

使用 Azure 服务总线输出绑定发送队列或主题消息。Use Azure Service Bus output binding to send queue or topic messages.

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

示例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;
}

特性和注释Attributes and annotations

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 name of an app setting that contains the Service Bus connection string to use, as shown in the following example:

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

有关完整示例,请参阅输出 - 示例For a complete example, see Output - 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.

配置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.
namename 不适用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. 仅在发送队列消息的情况下设置,不为主题设置。Set only if sending queue messages, not for a topic.
topicNametopicName TopicNameTopicName 主题名称。Name of the topic. 仅在发送主题消息的情况下设置,不为队列设置。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”,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.
accessRights(仅限 v1)accessRights (v1 only) 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.

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

使用情况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 and higher, the queue or topic must already exist; if you specify a queue or topic that doesn't exist, the function will fail.

对输出绑定使用以下参数类型: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 不创建消息(适用于 Functions 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,Functions 不创建消息(适用于 Functions 2.x 及更高版本)out Message - If the parameter value is null when the function exits, Functions does not create a message (for Functions 2.x and higher)
  • ICollector<T>IAsyncCollector<T>(适用于异步方法)- 用于创建多条消息。ICollector<T> or IAsyncCollector<T> (for async methods) - 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.

  • 若要访问会话 ID,请绑定到 Message 类型并使用 sessionId 属性。To access the session ID, bind to a Message type and use the sessionId property.

异常和返回代码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 versions 2.x and higher. 下面的示例 host.json 文件仅包含此绑定的设置。The example host.json file below contains only the settings for this binding. 有关全局配置设置的详细信息,请参阅 Azure Functions 版本的 host.json 参考For more information about global configuration settings, see host.json reference for Azure Functions version.

备注

有关 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": true,
                "maxConcurrentCalls": 32,
                "maxAutoRenewDuration": "00:05:00"
            },
            "sessionHandlerOptions": {
                "autoComplete": false,
                "messageWaitTimeout": "00:00:30",
                "maxAutoRenewDuration": "00:55:00",
                "maxConcurrentSessions": 16
            }
        }
    }
}

如果将 isSessionsEnabled 设置为 true,则将采用 sessionHandlerOptionsIf you have isSessionsEnabled set to true, the sessionHandlerOptions will be honored. 如果将 isSessionsEnabled 设置为 false,则将采用 messageHandlerOptionsIf you have isSessionsEnabled set to false, the messageHandlerOptions will be honored.

属性Property 默认Default 说明Description
prefetchCountprefetchCount 00 获取或设置消息接收方可以同时请求的消息数。Gets or sets the number of messages that the message receiver can simultaneously request.
maxAutoRenewDurationmaxAutoRenewDuration 00:05:0000:05:00 自动续订消息锁的最长持续时间。The maximum duration within which the message lock will be renewed automatically.
autoCompleteautoComplete true 是触发器在处理后自动调用 complete,还是函数代码手动调用 complete。Whether the trigger should automatically call complete after processing, or if the function code will manually call complete.

仅在 C# 中支持将其设置为 falseSetting to false is only supported in C#.

如果设置为 true,则触发器会在函数执行成功完成时自动完成该消息,否则会放弃该消息。If set to true, the trigger completes the message automatically if the function execution completes successfully, and abandons the message otherwise.

设置为 false 时,你负责调用 MessageReceiver 方法来完成、放弃消息或将消息放入死信队列。When set to false, you are responsible for calling MessageReceiver methods to complete, abandon, or deadletter the message. 如果引发了异常(并且未调用任何 MessageReceiver 方法),则锁仍然存在。If an exception is thrown (and none of the MessageReceiver methods are called), then the lock remains. 锁到期后,消息会重新排队,同时 DeliveryCount 会递增,并且锁会自动续订。Once the lock expires, the message is re-queued with the DeliveryCount incremented and the lock is automatically renewed.

在非 C# 函数中,函数中的异常会导致运行时在后台调用 abandonAsyncIn non-C# functions, exceptions in the function results in the runtime calls abandonAsync in the background. 如果未发生异常,则在后台调用 completeAsyncIf no exception occurs, then completeAsync is called in the background.
maxConcurrentCallsmaxConcurrentCalls 1616 对于每个缩放实例,消息泵应对回调发起的最大并发调用数。The maximum number of concurrent calls to the callback that the message pump should initiate per scaled instance. 默认情况下,Functions 运行时同时处理多条消息。By default, the Functions runtime processes multiple messages concurrently.
maxConcurrentSessionsmaxConcurrentSessions 20002000 每个缩放实例可以并发处理的最大会话数。The maximum number of sessions that can be handled concurrently per scaled instance.

后续步骤Next steps