如果ServiceBus主题尚不存在,请创建它

时间:2017-12-11 21:25:01

标签: c# azure azureservicebus

Microsoft已更新其.NET ServiceBus客户端库,其文档目前在旧的WindowsAzure.ServiceBus包和新的Microsoft.Azure.ServiceBus包之间进行了拆分。我喜欢新的包,因为它更清洁,依赖性更低。在旧包中,我们有类似以下的方法:

if (!namespaceManager.TopicExists(topicName))
{
    var topic = new TopicDescription(topicName);
    namespaceManager.CreateTopic(topic);
}

以编程方式创建主题的文档仍然使用旧包,其代码如上所述。 NamespaceManager类在新包中不可用,那么如何实现相应的呢?

3 个答案:

答案 0 :(得分:5)

在Github Repo azure-service-bus-dotnet上,他们解释了如何管理Service Bus实体:

有关于如何使用此库的示例:

您需要安装这些软件包:

  • Microsoft.Azure.Management.ServiceBus
  • Microsoft.Azure.Management.ResourceManager
  • Microsoft.IdentityModel.Clients.ActiveDirectory

如果您想创建主题,那么有趣的部分。请注意,您无需检查主题是否存在。 Azure资源管理器仅在资源已存在时更新资源。

// On you've got the ServiceBusManagementClient
ServiceBusManagementClient sbClient = ...

sbClient.Topics.CreateOrUpdateAsync("resource group name", "namespace name", "topic name", 
    new Microsoft.Azure.Management.ServiceBus.Models.SBTopic());

答案 1 :(得分:4)

在.NET Core中,您可以使用ManagementClient这样做,与命名空间管理器相比,它更容易。

try
{   
    await managementClient.GetTopicAsync(topicName);
}
catch (MessagingEntityNotFoundException)
{   
    await managementClient.CreateTopicAsync(new TopicDescription(topicName) { EnablePartitioning = true });
}

try
{
    await managementClient.GetQueueAsync(queueName);
}
catch (MessagingEntityNotFoundException)
{
    await managementClient.CreateQueueAsync(new QueueDescription(queueName) { EnablePartitioning = true });
}

See azure-service-bus-dotnet/issues/65

答案 2 :(得分:1)

如果您可以等待,还有未来的选择 - 将NamespaceManager作为following issue中描述的独立包。 options it will support也列在问题中。

  • 获取 - 仅限于存在检查并返回元数据
  • GetRuntimeInformation(获取所有计数和最后状态,近似计数,在10秒内准确)
  • GetQueueNames,GetTopicNames(列出实体名称)
  • 创建实体
  • 删除实体
  • 更新(需要有关要更新的元数据的详细信息,可以在实施期间完成)
  • FindOrCreate(Upsert - 队列不存在创建它)
  • UpdateOrCreate(Upsert)

如果您喜欢NamespaceManager的轻松,那么值得关注此问题。