Dapr:Azure 服务总线接收消息不起作用

问题描述 投票:0回答:1

我已经设置了一个OrderService(ASP.NET Core Web API)应用程序,它需要通过接收来监听在Azure服务总线主题上发布的消息。我可以成功向该主题发送消息(POST SendMessages 检索 JSON 并将其发送到服务总线主题),但我无法收到实际接收来自该主题的发送项目的通知。

我做错了什么?

Servicebus.yaml

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: servicebus-pubsub
  namespace: default
spec:
  type: pubsub.azure.servicebus
  version: v1
  metadata:
  - name: connectionString
    value: "Endpoint=sb://<<sbName>>.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=<<key>>"
  - name: topic
    value: "order-service-event"
  - name: subscriptionName
    value: "test"

Program.cs

... 
var app = builder.Build();

// Dapr will send serialized event object vs. being raw CloudEvent
app.UseCloudEvents();

// needed for Dapr pub/sub routing
app.MapSubscribeHandler();

...

// Dapr subscription in [Topic] routes orders topic to this route
app.MapPost("/orders", [Topic("servicebus-pubsub", "order-service-event")] (dynamic order) =>
{
    Console.WriteLine("Subscriber received order: " + order);
    return Results.Ok(order);
});

app.Run();

public record Order([property: JsonPropertyName("id")] int id);

OrderController.cs

namespace OrderService.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class OrderController : ControllerBase
    {
        [HttpPost(Name = "send-messages-provisioned")]
        public async Task<IActionResult> SendMessages()
        {
            var _client = new DaprClientBuilder().Build();
            var messages = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(System.IO.File.ReadAllText("messages.json"));

            foreach (var message in messages)
            {
                await _client.PublishEventAsync("servicebus-pubsub", "order-service-event", message);

                string jsonString = JsonSerializer.Serialize(message, new JsonSerializerOptions { WriteIndented = true });
                Console.WriteLine("Published Message: " + jsonString);
            }

            return Ok("Messages sent successfully!");
        }
    }
}
c# azure .net-core asp.net-core-webapi dapr
1个回答
0
投票

我创建了一个示例

ASP.NET Core Web API
应用程序,通过发布请求成功发送了消息,并毫无问题地收到了来自主题的消息。

  • 确保您的应用程序正在使用 Dapr sidecar 运行,并且已正确配置为管理订阅。

  • 我在

    builder.Services.AddDaprClient();
    中添加了
    program.cs
    来设置 Dapr 并启用 Pub/Sub 交互。

  • 还添加了

    builder.Services.AddControllers().AddDapr();
    以在控制器中启用 Dapr。

我的Program.cs:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDaprClient();
builder.Services.AddControllers().AddDapr();
var app = builder.Build();

app.UseCloudEvents();
app.UseRouting();
app.UseAuthorization();
app.MapSubscribeHandler();
app.MapControllers();
app.Run();

OrderController.cs:

using Dapr.Client;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
using System.Threading.Tasks;

namespace OrderService.Controllers
{
    [ApiController]
    [Route("order")]
    public class OrderController : ControllerBase
    {
        private readonly DaprClient _daprClient;

        public OrderController(DaprClient daprClient)
        {
            _daprClient = daprClient;
        }

        [HttpPost("send")]
        public async Task<IActionResult> SendMessage([FromBody] Order order)
        {
            try
            {
                await _daprClient.PublishEventAsync("servicebus-pubsub", "test", order);
                Console.WriteLine($"Published order: {JsonSerializer.Serialize(order)}");
                return Ok("Message sent successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error while sending message: {ex.Message}");
                return StatusCode(500, $"Internal server error: {ex.Message}");
            }
        }
    }
    public record Order(int Id, string ProductName, int Quantity);
}

Servicebus.yml:

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: servicebus-pubsub
  namespace: default
spec:
  type: pubsub.azure.servicebus
  version: v1
  metadata:
    - name: connectionString
      value: "Endpoint=sb://<servicebusname>.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=<access-key>"
    - name: topic
      value: "test"
    - name: subscriptionName
      value: "samplesub"

在这里,我已使用发布请求将以下消息发送到 Azure 服务总线主题。

enter image description here

我运行了以下命令来启动 Dapr 并可以看到发送的数据。

dapr run --app-id orderservice --app-port 5000 --components-path ./components -- dotnet run

enter image description here

我成功收到了 Azure 服务总线主题中的消息,如图所示。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.