python对接事务性MSMQ队列
2023/10/31补充:若发送队列消息还需要标记响应队列,需要添加以下代码
1 resp_info = win32com.client.Dispatch("MSMQ.MSMQDestination") # 定义回执队列 2 resp_info.FormatName = f'direct=tcp:{response_ip}\\PRIVATE$\\{response_queue}' # response_ip: 响应队列地址 response_queue: 响应队列 3 4 # 下面这行放在发送消息之前即可 5 msg.ResponseDestination = resp_info
参考:https://learn.microsoft.com/en-us/previous-versions/windows/desktop/msmq/ms705720(v=vs.85)
研究了很久,逐步了解到原理后,发现python发送消息到事务性msmq肯定可行。
现在能搜到的资源没有任何一篇文章说明了这个,包括gpt都一样。废话不多说,直接上代码
import win32com.client
# 关键代码 必须使用 gencache 导入 "MSMQ.MSMQQueueInfo"
win32com.client.gencache.EnsureDispatch("MSMQ.MSMQQueueInfo")
host_name = 'www.xxxxx.com' # 可替换为 IP 地址
queues = 'send' # 目标队列
def send_message(queue_name: str, label: str, message: str):
"""
发送消息
:param queue_name: 队列名称
:param label: 标签
:param message: 消息
:return:
"""
queue_info = win32com.client.Dispatch("MSMQ.MSMQQueueInfo")
queue_info.FormatName = f'direct=tcp:{host_name}\\PRIVATE$\\{queue_name}'
queue = None
try:
queue = queue_info.Open(2, 0)
msg = win32com.client.Dispatch("MSMQ.MSMQMessage")
msg.Label = label
msg.Body = message
# 是否发送事务性队列 win32com.client.constants.MQ_SINGLE_MESSAGE
msg.Send(queue, win32com.client.constants.MQ_SINGLE_MESSAGE)
except Exception as e:
print(f'Error! {e}')
finally:
queue.Close()
send_message(queues, 'test label', 'this is a test message')

浙公网安备 33010602011771号