用python连接activemq写出接收图片的代码
时间: 2023-08-31 09:36:11 浏览: 70
### 回答1:
以下是一个使用 Python 连接 ActiveMQ 并接收图片的示例代码:
```python
import stomp
import base64
class MyListener(stomp.ConnectionListener):
def on_message(self, headers, message):
# 获取图片数据并解码
image_data = base64.b64decode(message)
# 将图片保存到本地
with open('received_image.jpg', 'wb') as f:
f.write(image_data)
conn = stomp.Connection([('localhost', 61613)])
conn.set_listener('', MyListener())
conn.start()
conn.connect()
# 订阅图片消息队列
conn.subscribe(destination='/queue/image_queue', id=1, ack='auto')
# 等待接收消息
while True:
pass
conn.disconnect()
```
注意:在运行代码之前,需要先安装 stomp 库。可以使用以下命令进行安装:
```
pip install stomp.py
```
### 回答2:
使用 Python 连接 ActiveMQ 并接收图片的代码示例如下:
```python
import stomp
import base64
class MyListener(stomp.ConnectionListener):
def on_message(self, headers, message):
try:
# 解析消息头中的图片文件名
filename = headers['filename']
# 解码图片数据并保存到本地文件
image_data = base64.b64decode(message)
with open(filename, 'wb') as file:
file.write(image_data)
print(f"成功接收图片 {filename}")
except Exception as e:
print(f"接收图片出错:{str(e)}")
# 初始化连接参数
conn = stomp.Connection()
conn.start()
conn.connect()
# 订阅消息队列
conn.set_listener('', MyListener())
conn.subscribe(destination='/queue/myImageQueue', id='1', ack='auto')
# 等待接收消息
while True:
try:
pass
except KeyboardInterrupt:
break
# 断开连接
conn.disconnect()
```
注意事项:
1. 需要先安装 `stomp` 库,可以通过 `pip install stomp` 命令进行安装。
2. `subscribe` 方法中的 `destination` 参数是要订阅的消息队列的名称,可根据实际情况进行修改。
3. 在消息头中添加一个自定义的字段 `filename`,用于标识图片文件名,方便保存时使用。