MassTransit Azure ServiceBus 强制连接使用 HTTPS 而不是 AMQP

MassTransit Azure ServiceBus force the connection to use HTTPS rather than AMQP

我们如何强制 MassTransit 使用 HTTPS 连接到 Azure 服务总线而不是 AMQP?

我们的应用程序在企业防火墙后面。它需要 send/receive 来自 Azure 主题的消息。我们更愿意使用 HTTPS 而不是 AMQP,这样更容易实现安全管理目的。

该应用有以下设置

根据 Azure 服务总线文档,我们应该能够将传输类型设置为 AmqpWebSockets,它应该使用 HTTPS 进行通信。连接字符串如下所示:

Endpoint=sb://test.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=secret;TransportType=AmqpWebSockets

(参考:https://github.com/MicrosoftDocs/azure-docs/issues/14133

如果我们使用Microsoft.Azure.ServiceBus 4.1.1中的TopicClient,我们可以看到流量通过端口443。示例代码是

class Program
{
    public static async Task Main(string[] args)
    {
        var serviceBus = new ServiceBus();
        await serviceBus.SendMessageAsync();

        Console.ReadKey();
    }
}

public class ServiceBus
{
    public async Task SendMessageAsync()
    {
        const int numberOfMessages = 10;
        topicClient = new TopicClient(ServiceBusConnectionString, TopicName);
        // Send messages.
        await SendMessagesAsync(numberOfMessages);

        Console.ReadKey();

        await topicClient.CloseAsync();
    }

    public async Task SendMessagesAsync(int numberOfMessagesToSend)
    {
        try
        {
            for (var i = 0; i < numberOfMessagesToSend; i++)
            {
                // Create a new message to send to the topic.
                string messageBody = $"Message {i}";
                var message = new Message(Encoding.UTF8.GetBytes(messageBody));

                // Write the body of the message to the console.
                Console.WriteLine($"Sending message: {messageBody}");

                // Send the message to the topic.
                await topicClient.SendAsync(message);
            }
        }
        catch (Exception exception)
        {
            Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
        }
    }
}

但是,当我们使用具有 TransportType=AmqpWebSockets 的相同连接字符串时,MassTransit 仍然使用 AMQP 端口 5671:

public class Order : IModel
{
    public int Id { get; set; }
    public double Amount { get; set; }
    public string Description { get; set; }
}


public static async Task Main(string[] args)
{
    var bus = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
    {
        cfg.Host(ConnectionString);
    });
    await bus.StartAsync();
    for (int i = 0; i < 100; i++)
    {
        var order = new Order() { Id = i, Amount = 20, Description = "Test order" };
        await bus.Publish(order);
    }
}

这是 Wireshark 捕获的流量:

有趣的是,前几个数据包使用端口 443 然后更改为端口 5671

找到解决方案,可以在设置总线时设置传输类型:

var bus = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
{
    cfg.Host(ConnectionString, hc => hc.TransportType = TransportType.AmqpWebSockets);
    cfg.PrefetchCount = 1;
    AddSubscriptionEndpoints(context, cfg);
});

Bingo,它现在使用端口 443