Home > Mobile >  How to setup durable messages using ActiveMQ and stomp.py
How to setup durable messages using ActiveMQ and stomp.py

Time:10-14

I am trying to setup a durable topic using ActiveMQ. Here is my publisher:

import time
import stomp

conn = stomp.Connection()
conn.connect('admin', 'password', wait=True)

for i in range(1, 21):
  message = "message %d"%i
  print(message)
  conn.send(body=message, destination='/topic/test', persistent=True)
  time.sleep(1)
conn.disconnect()

and here is my subscriber:

import time
import stomp


class MyListener(stomp.ConnectionListener):
    def on_error(self, frame):
        print('received an error "%s"' % frame.body)

    def on_message(self, frame):
        print('received a message "%s"' % frame.body)


conn = stomp.Connection()
conn.set_listener('', MyListener())
conn.connect('admin', 'admin', wait=True, headers = {'client-id': 'testname'})
conn.subscribe(destination='/topic/test', id=1, ack='auto',  persistent=True)

Messages are sent and received ok, but if the subscriber is not listening when a message is sent, it is lost, so the topic is not durable. How do I fix this? My understanding is if you have a client-id set and the subscriber id set, messages should be durable in the case of a dropped connection, but this is not working with the current code I have.

EDIT:

Using the accepted answer below here is the working subscriber in case anyone else runs into this issue:

import time
import stomp


class MyListener(stomp.ConnectionListener):
    def on_error(self, frame):
        print('received an error "%s"' % frame.body)

    def on_message(self, frame):
        print('received a message "%s"' % frame.body)


conn = stomp.Connection()
conn.set_listener('', MyListener())
conn.connect('admin', 'admin', wait=True, headers = {'client-id': 'testname'})
conn.subscribe(destination='/topic/test', id=1, ack='auto',  persistent=True, headers = {"activemq.subscriptionName":"testsub"})

CodePudding user response:

To subscribe as a durable topic subscriber to ActiveMQ 5.x brokers the subscriber must include the header "activemq.subscriptionName:" where the unique subscription name is provided by the client each time it reconnects to the broker. The subscription must be created first before messages are sent and only then will it accumulate messages when the subscriber is offline.

The frame should look as follows:

        frame = "SUBSCRIBE\n"  
            "destination:/topic/myTopic"   "\n"  
            "ack:auto\n"   "receipt:1\n"   "id:durablesub-1\n"  
            "activemq.subscriptionName:test1\n\n"   "\u0000";

Refer to the documentation for all the frame headers needed when working with ActiveMQ "Classic"

  • Related