azure - 验证 Microsoft Azure 服务总线的连接字符串

标签 azure .net-core azureservicebus azure-servicebus-queues azure-servicebus-subscriptions

我有一个 Microsoft Azure 服务总线连接字符串,我想验证它是否有效。我还想验证主题和订阅(如果存在)。如果连接字符串、主题和订阅无效,那么我们可以采取适当的操作。

示例连接字符串可以类似于 - TransportType=AmqpWebSockets;Endpoint=sb://myservicebus.servicebus.windows.net/;SharedAccessKeyName=sendkey;SharedAccessKey=MQHnx3voLhH/xVgoamX3KijzkZ0qb7U6oHTolj7LM9H=;

我尝试了 ServiceBusClient 但它没有这样的支持。有没有办法验证连接字符串和主题/订阅?

最佳答案

客户端将验证连接字符串和实体名称的格式是否正确,但没有专门的操作来测试其与服务总线通信的能力。

当第一个需要连接和链接的网络操作被调用时,它们会被延迟地建立。我想到了两种方法可以在不造成干扰的情况下触发网络资源创建。

创建消息批处理

为了确保批量大小不超过给定资源的限制,ServiceBusSender 必须查询队列/主题。如果客户端配置错误,则会抛出异常。

// In a real scenario, you would want to create these as
// singletons and reuse them for the lifetime of the application.

await using var client = new ServiceBusClient("<< Connection String>>");
await using var sender = client.CreateSender("<< Queue/Topic >>");

var valid = true;

try
{
    using var batch = await sender.CreateMessageBatchAsync().ConfigureAwait(false);
}
catch (Exception ex)
    when (ex is ServiceBusException 
        || ex is IOException 
        || ex is SocketException)
{
    valid = false;
}

查看消息

查看消息不会导致消息被锁定或以其他方式影响接收。

await using var client = new ServiceBusClient("<< Connection String>>");
await using var receiver = client.CreateReceiver("<< Queue/Subscription >>");

var valid = true;

try
{
    _ = await receiver.PeekMessageAsync().ConfigureAwait(false);
}
catch (Exception ex)
    when (ex is ServiceBusException 
        || ex is IOException 
        || ex is SocketException)
{
    valid = false;
}

与每个队列、主题和订阅的交互都使用专用的 AMQP 链接,因此如果您想确保名称与已知的服务总线实体匹配,则需要单独测试每个队列、主题和订阅。

关于azure - 验证 Microsoft Azure 服务总线的连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71255225/

相关文章:

git - 致命 : unable to access 'https://dev.azure.com/xxx' : OpenSSL SSL_connect: Connection was reset in connection to dev. azure.com:443

c# - csproj 根据操作系统复制文件

c# - 使用 NUnit 测试无限序列,但只需检查有限序列

java - Windows Azure : Error when deleting brokered message

linux - Azcopy linux 包含下载选项

azure - 如何在 Azure WebApp 上指定 aspnet core 项目的构建配置

c# - 从 azure 应用程序发送电子邮件时为 "The remote certificate is invalid according to the validation procedure"

.net - 在遇到问题的 Docker 上部署 Blazor Client(WebAssembly)

c# - BrokerProperties REST header 值未显示在 .NET 客户端代码中

c# - 使用新的 Azure.messaging.servicebus 获取事件消息计数