{Azure Service Bus}Azure CLI を使用して Service Bus 名前空間とキューを作成する

 

https://learn.microsoft.com/ja-jp/azure/service-bus-messaging/service-bus-quickstart-cli

https://learn.microsoft.com/ja-jp/azure/service-bus-messaging/service-bus-python-how-to-use-queues

 


-- 1. 前作業

az login --use-device-code
az account show

az version

az configure --list-defaults
az configure --defaults location=japaneast
az configure --list-defaults

az group create \
--name rg9999999 \
--location japaneast

az group list
az upgrade


-- 2. Service Bus 名前空間を作成

az servicebus namespace create \
--resource-group rg9999999 \
--name ns123 \
--location japaneast \
--sku Basic

az servicebus namespace list \
--resource-group rg9999999


-- 3. 名前空間にキューを作成

az servicebus queue create \
--resource-group rg9999999 \
--namespace-name ns123 \
--name queue01

az servicebus queue list \
--resource-group rg9999999 \
--namespace-name ns123

 

 

-- 4. 名前空間のプライマリ接続文字列を取得

az servicebus namespace authorization-rule keys list \
--resource-group rg9999999 \
--namespace-name ns123 \
--name RootManageSharedAccessKey \
--query primaryConnectionString \
--output tsv


-- 5. メッセージをキューに送信する

vim a.py

from azure.servicebus import ServiceBusClient, ServiceBusMessage

CONNECTION_STR = "Endpoint=sb://ns123.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
QUEUE_NAME = "queue01"

def send_single_message(sender):
    # create a Service Bus message
    message = ServiceBusMessage("Single Message")
    # send the message to the queue
    sender.send_messages(message)
    print("Sent a single message")

# create a Service Bus client using the connection string
servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR, logging_enable=True)
with servicebus_client:
    # get a Queue Sender object to send messages to the queue
    sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME)
    with sender:
        # send one message        
        send_single_message(sender)

print("Done sending messages")
print("-----------------------")

with servicebus_client:
    # get the Queue Receiver object for the queue
    receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME, max_wait_time=5)
    with receiver:
        for msg in receiver:
            print("Received: " + str(msg))
            # complete the message so that the message is removed from the queue
            receiver.complete_message(msg)

 

-- 6. アプリを実行する

pip3 install azure-servicebus

python3 a.py

 

-- 7. クリーンアップ


az servicebus queue delete \
--resource-group rg9999999 \
--namespace-name ns123 \
--name queue01


az servicebus namespace delete \
--resource-group rg9999999 \
--name ns123

 

az group list
az group delete \
--name rg9999999 \
--yes