通过 C# 设置 Azure 函数服务总线主题和订阅输出绑定

Setting Azure Function Service Bus Topic and Subscription Output Binding via C#

我有一个带有多个服务总线输出绑定的简单 HTTP 触发器 Azure 函数。所有绑定都指向同一个主题,但它们有不同的订阅。如果我要通过 function.json 设置此功能应用程序,那将非常简单:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "serviceBus",
      "connection": "SERVICEBUS",
      "name": "output",
      "topicName": "outtopic",
      "subscriptionName": "sub",
      "direction": "out"
    },
    {
      "type": "serviceBus",
      "connection": "SERVICEBUS",
      "name": "output",
      "topicName": "outtopic",
      "subscriptionName": "sub2",
      "direction": "out"
    }
  ],
  "disabled": false
}

但是我通过 Visual Studio 发布我的函数,因此我的 Azure Functions 在门户中是只读的,function.json 是在发布时由 VS 自动生成的。 问题是我不知道如何设置指向不同订阅的多个输出绑定。目前我有这样的东西:

[FunctionName("Function2")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
    [ServiceBus("outtopic", entityType:EntityType.Topic)] IAsyncCollector<string> output,
    [ServiceBus("outtopic", entityType: EntityType.Topic)] IAsyncCollector<string> output2,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

    await output.AddAsync(requestBody);

    return new OkObjectResult("OK");
}

如您所见,output 和 output2 指向同一个主题,但没有指定订阅的选项。 在这一点上,我非常有信心这还没有实现。但我希望有解决方法吗?

试试这个,在定义中添加连接 属性,根据这个例子 - 如果通过订阅你的意思是在 azure 订阅上:

public static void Run([BlobTrigger("inputvideo/{customername}/{date}/{filename}", Connection = "AzureWebJobsStorage")]Stream myBlob, 
                                string customername, 
                                string date, 
                                string filename,
                                [ServiceBus("detectobjectsqueue",EntityType.Queue, Connection="ServiceBusConnectionString")] IAsyncCollector<string> output,
                                ILogger log)

更新 根据您的评论,我了解到您所说的订阅是指主题订阅。在这种情况下,主题的想法是所有订阅者都收到消息。因此,您有一个发布者,订阅该主题的任何人都会收到消息。如果您想确保特定订阅者收到消息,请在接收端点上实施消息过滤(例如,按类型)或为每个订阅者使用专用队列。

另外,从概念上讲,发布者不应该知道谁是订阅者,订阅者也不应该知道谁是发布者。如果您知道订阅​​者是谁,为什么不使用 REST 调用来接收端点?

直接将消息放入主题订阅是不可能的,而是每条消息都必须通过主题。

要确保只有特定的订阅才能收到消息,您需要配置主题订阅规则。您可以在 blog post here.

中阅读有关规则的更多信息