【Azure 服务总线】如何批量删除Azure Service Bus中的Topics(数量较多,需要过滤后批量删除)

问题描述

Azure Service Bus 的门户操作页面上,是否可以批量删除其中的Topics呢?

 

问题解答

Azure Service Bus门户或Service Bus Explorer工具没有提供批量删除Topic的方法。但是可以自己写脚本删除,并且可以在删除的时候自定义过滤条件。

以Python举例:

第一步:在本地安装Python Service Bus SDK。

pip install azure-servicebus

第二步:参考Service Bus Topic 管理相关操作,结合 list_topics 和 delete_topic 方法删除满足要求的Topic

import os
from azure.servicebus.management import ServiceBusAdministrationClient

#CONNECTION_STR =  "Endpoint=sb://xxx.servicebus.chinacloudapi.cn/;SharedAccessKeyName=xxx;SharedAccessKey=xxxx"
CONNECTION_STR = os.environ['SERVICEBUS_CONNECTION_STR']

def delete_all_topic(servicebus_mgmt_client):
    print("-- Delete all the Topics")
    for topic_properties in servicebus_mgmt_client.list_topics():
        #print("delete Topic Name:", topic_properties.name)
        #根据Topic名称可以过滤是否需要删除
        servicebus_mgmt_client.delete_topic(topic_properties.name)
        print("Topic {} is deleted.".format(topic_properties.name))
    print("")



with ServiceBusAdministrationClient.from_connection_string(CONNECTION_STR) as servicebus_mgmt_client:
    delete_all_topic(servicebus_mgmt_client)

执行效果图:

 

参考资料

Service Bus Python sdk 安装:https://pypi.org/project/azure-servicebus/
Service Bus Topic 管理相关操作:https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/servicebus/azure-servicebus/samples/sync_samples/mgmt_topic.py
获取Service Bus 连接字符串:https://docs.azure.cn/zh-cn/service-bus-messaging/service-bus-quickstart-portal#get-the-connection-string

 

posted @ 2023-05-17 20:26  路边两盏灯  阅读(27)  评论(0编辑  收藏  举报