To send messages to an ActiveMQ broker using the STOMP protocol in a loop with Python, you can use the stomp.py library. First, you’ll need to ensure the library is installed. You can install it using pip if you haven’t already:
pip install stomp.py
Here’s a simple example of how to send messages in a loop:
import stomp
import time
class MyListener(stomp.ConnectionListener):
def on_error(self, headers, message):
print('received an error: "%s"' % message)
def on_disconnected(self):
print('disconnected')
def send_messages():
conn = stomp.Connection([('localhost', 61613)])
conn.set_listener('', MyListener())
conn.connect('admin', 'password', wait=True)
for i in range(10): # Send 10 messages
message = f'Message number {i + 1}'
conn.send(destination='/queue/test', body=message)
print(f'Sent: {message}')
time.sleep(1)
conn.disconnect()
if __name__ == '__main__':
send_messages()
Key Points:
- Connection Setup: Replace
'localhost'and61613with your ActiveMQ server’s host and port. - Authentication: Replace
'admin'and'password'with your ActiveMQ username and password. - Queue Name: Adjust the
destination='/queue/test'to the queue you want to send messages to. - Loop: Adjust the range and
time.sleep()for the number of messages and delay between sends as needed.
This script establishes a connection to the ActiveMQ broker, sends a series of messages to a specified queue, and then disconnects.
GPT
GPT 的回答基本上解决了问题。
遇到的问题是,在向 ActiveMQ 发送消息的时候,我们有一个 SendMQ 的方法。
在这个方法将会打开连接发送消息后关闭连接。
我们的问题在:现在需要向 MQ 发送 1 万多条消息,这个循环放那里。
开始我们把这个循环放在了内层,这里就出现了一个问题,Python 的循环会异步调用 Close 这方法,然后导致整个程序的挂起。
通过上面 GPT 的回答,我知道应该在整个循环的最外层打开连接,循环内不能再次打开连接和关闭连接。
等把这 1 万多条消息发送成功后再关闭连接。
同样的问题,我们也使用了 claude_3_haiku_bot 这个模型来问了这个问题,请参考后面的消息。
感觉 GPT4 的模型对这个问题回答得更好一些。