python对接事务性MSMQ队列

发布时间 2023-06-14 11:34:45作者: NIGangJun

研究了很久,逐步了解到原理后,发现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')