Search code examples
python-3.xactivemq-classicstompjms-topic

Subscribing and reading from Topic: ActiveMQ & Python


I am trying to subscribe to a topic in ActiveMQ running in localhost using stompest for connecting to the broker. Please refer below code:

import os
import json
from stompest.sync import Stomp
from stompest.config import StompConfig

CONFIG = StompConfig(uri=os.environ['MQ_URL'],
                     login=os.environ['MQ_UID'],
                     passcode=os.environ['MQ_DWP'],
                     version="1.2")

topic = '/topic/SAMPLE.TOPIC'

msg = {'refresh': True}

client = Stomp(CONFIG)
client.connect()
client.send(topic, json.dumps(msg).encode())
client.disconnect()

client = Stomp(CONFIG)
client.connect(heartBeats=(0, 10000))
token = client.subscribe(topic, {
    "ack": "client",
    "id": '0'
})

frame = client.receiveFrame()
if frame and frame.body:
    print(f"Frame received from MQ: {frame.info()}")
client.disconnect()

Although I see active connection it the ActiveMQ web console, no message is received in the code. The flow of control seems to pause at frame = client.receiveFrame().

I didn't find any reliable resource or documentation regarding this.

Am I doing anything wrong here?


Solution

  • This is the expected behavior since you're using a topic (i.e. pub/sub semantics). When you send a message to a topic it will be delivered to all existing subscribers. If no subscribers are connected then the message is discarded.

    You send your message before any subscribers are connected which means the broker will discard the message. Once the subscriber connects there are no messages to receive therefore receiveFrame() will simply block waiting for a frame as the stompest documentation notes:

    Keep in mind that this method will block forever if there are no frames incoming on the wire.

    Try either sending a message to a queue and then receiving it or creating an asynchronous client first and then sending your message.