杰瑞科技汇

Python如何链接ActiveMQ?

使用Python连接ActiveMQ

在Python中连接ActiveMQ(一种流行的开源消息队列)通常使用STOMP协议,以下是几种常用的方法:

Python如何链接ActiveMQ?-图1
(图片来源网络,侵删)

使用stomp.py库

stomp.py是Python中最常用的STOMP客户端库之一。

安装

pip install stomp.py

基本示例

生产者(发送消息)
import stomp
import time
# 连接参数
conn = stomp.Connection(host_and_ports=[('localhost', 61613)])
conn.start()
conn.connect(wait=True)
# 发送消息
conn.send(body='Hello, ActiveMQ!', destination='/queue/test')
print("消息已发送")
# 断开连接
conn.disconnect()
消费者(接收消息)
import stomp
import time
class MyListener(stomp.ConnectionListener):
    def on_message(self, headers, body):
        print(f"收到消息: {body}")
        print(f"消息头: {headers}")
# 连接参数
conn = stomp.Connection(host_and_ports=[('localhost', 61613)])
conn.set_listener('', MyListener())
conn.start()
conn.connect(wait=True)
# 订阅队列
conn.subscribe(destination='/queue/test', id=1, ack='auto')
# 保持运行
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    conn.disconnect()

使用pika库(AMQP协议)

ActiveMQ也支持AMQP协议,可以使用pika库连接。

安装

pip install pika

基本示例

生产者
import pika
# 连接到ActiveMQ
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', 5672))
channel = connection.channel()
# 声明队列
channel.queue_declare(queue='test')
# 发送消息
channel.basic_publish(exchange='', routing_key='test', body='Hello, ActiveMQ!')
print("消息已发送")
# 关闭连接
connection.close()
消费者
import pika
import time
def callback(ch, method, properties, body):
    print(f"收到消息: {body}")
    ch.basic_ack(delivery_tag=method.delivery_tag)
# 连接到ActiveMQ
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', 5672))
channel = connection.channel()
# 声明队列
channel.queue_declare(queue='test')
# 消费消息
channel.basic_consume(queue='test', on_message_callback=callback)
print('等待消息...')
try:
    channel.start_consuming()
except KeyboardInterrupt:
    connection.close()

配置注意事项

  1. ActiveMQ配置

    • 确保ActiveMQ的STOMP或AMQP端口已启用(默认STOMP端口是61613,AMQP是5672)
    • activemq.xml中确认协议连接器已配置
  2. 认证

    Python如何链接ActiveMQ?-图2
    (图片来源网络,侵删)
    • 如果ActiveMQ启用了认证,需要在连接时提供用户名和密码:
      conn.connect(username='admin', password='password', wait=True)
  3. SSL/TLS

    • 对于生产环境,建议使用加密连接:
      conn = stomp.Connection(
        host_and_ports=[('localhost', 61612)],
        use_ssl=True,
        ssl_key_file='client.key',
        ssl_cert_file='client.crt'
      )

高级用法

  • 持久化订阅:使用subscribeack参数设置为'client'实现手动确认
  • 事务支持:通过begin(), commit(), rollback()方法实现事务控制
  • 消息优先级:在发送消息时添加priority参数

根据你的具体需求选择合适的方法和配置,STOMP协议通常更通用,而AMQP在某些场景下可能有更多高级特性。

Python如何链接ActiveMQ?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇