简体   繁体   English

如何使用 Azure Functions 将数据发送到服务总线主题?

[英]How to send data to Service Bus Topic with Azure Functions?

I have default C# based HTTP Trigger here and I wish to send data "Hello Name" to Service Bus Topic (already created).我在这里有默认的基于 C# 的 HTTP 触发器,我希望将数据“Hello Name”发送到服务总线主题(已创建)。 I'm coding at portal.我在门户网站上编码。

How to do it Service Bus output binding?如何做到服务总线输出绑定?

This is not working.这是行不通的。 Any help available?任何可用的帮助?

-Reference missing for handling Service Bus? - 缺少处理服务总线的参考?

-How to define Connection of service bus? - 如何定义服务总线的连接? Where is Functions.json Functions.json 在哪里

-How to send a message to service bus? - 如何向服务总线发送消息?

//This FunctionApp get triggered by HTTP and send message to Azure Service Bus

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace Company.Function

{
    public static class HttpTriggerCSharp1
{
    [FunctionName("HttpTriggerCSharp1")]
    [return: ServiceBus("myqueue", Connection = "ServiceBusConnection")] // I added this for SB Output. Where to define.

    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log)

    {
        log.LogInformation("C# HTTP trigger function processed a request.");
        string name = req.Query["name"];
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;
        string responseMessage = string.IsNullOrEmpty(name)
            ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            : $"Hello, {name}. This HTTP triggered function executed successfully.";
        return new OkObjectResult(responseMessage);
        // I added this for SB Output
        return responseMessage;
    }
}

} }

Firstly, there are two bindings to send data to service bus.首先,有两个绑定可以将数据发送到服务总线。 Firstly is what you show, using the return binding, after install two packages Microsoft.Azure.WebJobs.Extensions.ServiceBus and WindowsAzure.ServiceBus , then you will be able to send data.首先是你显示的,使用return绑定,安装两个包Microsoft.Azure.WebJobs.Extensions.ServiceBusWindowsAzure.ServiceBus ,你就可以发送数据了。 And you could not do it cause your function type is IActionResult and you are trying to return string (responseMessage).你不能这样做,因为你的函数类型是IActionResult并且你试图返回string (responseMessage)。

So if you want to send the whole responseMessage , just return new OkObjectResult(responseMessage);所以如果你想发送整个responseMessage ,只需return new OkObjectResult(responseMessage); , it will work. ,它会起作用。 And the result would be like below pic.结果如下图所示。

在此处输入图片说明

And if you want to use return responseMessage;如果你想使用return responseMessage; should change your method type to string, it will be public static async Task<string> RunAsync and result will be below.应该将您的方法类型更改为字符串,它将是public static async Task<string> RunAsync并且结果将在下面。

在此处输入图片说明

Another binding you could refer to below code or this sample .您可以参考以下代码或此示例的另一种绑定。

[FunctionName("Function1")]
        [return: ServiceBus("myqueue", Connection = "ServiceBusConnection")]
        public static async Task RunAsync(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            [ServiceBus("myqueue", Connection = "ServiceBusConnection")] MessageSender messagesQueue,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            byte[] bytes = Encoding.ASCII.GetBytes(responseMessage);
            Message m1 = new Message(bytes);
            await messagesQueue.SendAsync(m1);

        }

How to define Connection of service bus?如何定义服务总线的连接? Where is Functions.json Functions.json 在哪里

In the local you should define the connection in the local.settings.jon , you could use any name with the connection, then in the binding Connection value should be the name you set in the json file.在本地,您应该在local.settings.jon定义连接,您可以对连接使用任何名称,然后在绑定中Connection值应该是您在 json 文件中设置的名称。 And cause you are using c# , so you could not modify the function.json file, there will be a function.json file in the debug folder.由于您使用的是c# ,因此您无法修改function.json文件,因此 debug 文件夹中会有一个 function.json 文件。 So you could only change the binding in the code.因此,您只能更改代码中的绑定。

Hope this could help you, if you still have other problem , please feel free to let me know.希望这可以帮助您,如果您还有其他问题,请随时告诉我。

Make sure you first install Microsoft.Azure.WebJobs.Extensions.ServiceBus NuGet package.确保首先安装Microsoft.Azure.WebJobs.Extensions.ServiceBus NuGet 包。 Then make sure you are using it in your project:然后确保您在项目中使用它:

using Microsoft.Azure.WebJobs.Extensions.ServiceBus;

Make sure you clean and build the project to make sure you have no errors.确保清理并构建项目以确保没有错误。

Then you need to make sure you have a "ServiceBusConnection" connection string inside your local.settings.json file:然后你需要确保你的local.settings.json文件中有一个"ServiceBusConnection"连接字符串:

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "ServiceBusConnection": "Endpoint=sb://...",
  }
}

Which you can get if you go to Azure portal -> Service bus namespace -> Shared access policies -> RootManageSharedAccessKey -> Primary Connection String .如果您转到Azure 门户 -> 服务总线命名空间 -> 共享访问策略 -> RootManageSharedAccessKey -> 主连接字符串,您可以获得它 Copy and paste this connection string inside "ServiceBusConnection" .将此连接字符串复制并粘贴到"ServiceBusConnection" You can also use the Secondary Connection String as well.您也可以使用辅助连接字符串

Note: Service bus queues/topics have shared access policies as well.注意:服务总线队列/主题也有共享访问策略。 So if you don't want to use the Service bus namespace level access policies, you can create one at queue/topic level, so you your function app only has access to the queue/topic defined in your namespace.因此,如果您不想使用服务总线命名空间级别的访问策略,您可以在队列/主题级别创建一个,这样您的函数应用就只能访问在您的命名空间中定义的队列/主题。

Also if you decide to publish your function app, you will need to make sure you create a configuration application setting for "ServiceBusConnection" , since local.settings.json is only used for local testing.此外,如果您决定发布函数应用,则需要确保为"ServiceBusConnection"创建配置应用程序设置,因为local.settings.json仅用于本地测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 Azure function 向服务总线主题发送批处理消息 - Send batch messages to Service Bus topic from Azure function 如何在 Azure 服务总线中显式向主题订阅死信队列发送消息 - How to send message to Topic Subscription Dead Letter Queue Explicitly in Azure Service Bus 使用 Azure 中的 IAsyncCollector 将消息从服务总线主题批量发送到另一个主题即使在收到消息后功能也会保持重试 - Send Messages from service bus topic to another as batches using IAsyncCollector in Azure Functions keeps retries even after message received Azure服务总线主题体系结构 - Azure Service Bus Topic Architecture 向服务总线主题发送消息 - send message to service bus topic 如何在Azure Service Bus主题上删除DeadLetter消息 - How do I delete a DeadLetter message on an Azure Service Bus Topic Azure 服务总线 - 如何以编程方式添加主题订阅者 - Azure Service Bus - How to Add Topic Subscriber Programmatically 如何在 azure 服务总线命名空间中创建主题、订阅和 SAS 策略? - How to create topic, subscription and SAS policy in azure service bus namespace? 如何从 .net 核心应用程序向服务总线主题发送消息 - How to send a message to service bus topic from .net core application 如何指定要与 MassTransit 一起使用的 Azure 服务总线主题 - How to specify which Azure Service Bus Topic to use with MassTransit
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM