Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# mq

作者:诸神之翼   发布日期:2026-07-09   浏览:43

using System;
using IBM.WMQ;

class Program
{
    static void Main(string[] args)
    {
        // 创建 MQ 连接工厂
        MQQueueManager queueManager = null;
        try
        {
            // 定义 MQ 环境属性
            Hashtable mqEnvironment = new Hashtable();
            mqEnvironment.Add(MQC.HOST_NAME_PROPERTY, "your.host.name");
            mqEnvironment.Add(MQC.CHANNEL_PROPERTY, "YOUR.CHANNEL.NAME");
            mqEnvironment.Add(MQC.PORT_PROPERTY, 1414);
            mqEnvironment.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);

            // 创建队列管理器
            queueManager = new MQQueueManager("YOUR.QUEUE.MANAGER.NAME", mqEnvironment);

            // 打开队列
            int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT;
            MQQueue queue = queueManager.AccessQueue("YOUR.QUEUE.NAME", openOptions);

            // 发送消息
            MQMessage helloWorld = new MQMessage();
            helloWorld.WriteString("Hello, World!");
            MQPutMessageOptions pmo = new MQPutMessageOptions();
            queue.Put(helloWorld, pmo);

            // 接收消息
            MQMessage receivedMessage = new MQMessage();
            MQGetMessageOptions gmo = new MQGetMessageOptions();
            queue.Get(receivedMessage, gmo);
            string messageText = receivedMessage.ReadString(receivedMessage.MessageLength);
            Console.WriteLine("Received message: " + messageText);

            // 关闭队列和队列管理器
            queue.Close();
            queueManager.Disconnect();
        }
        catch (MQException ex)
        {
            Console.WriteLine("An MQ error occurred: {0}", ex.ToString());
        }
        catch (System.Exception ex)
        {
            Console.WriteLine("A System error occurred: {0}", ex.ToString());
        }
        finally
        {
            if (queueManager != null)
            {
                queueManager.Disconnect();
            }
        }
    }
}

解释说明

这段代码展示了如何使用 C# 与 IBM MQ(以前称为 WebSphere MQ)进行交互。以下是关键步骤的解释:

  1. 创建 MQ 连接工厂:通过 Hashtable 设置连接属性,如主机名、通道名称、端口号等。
  2. 创建队列管理器:使用 MQQueueManager 类连接到指定的队列管理器。
  3. 打开队列:使用 AccessQueue 方法打开指定的队列,并设置打开选项(输入或输出)。
  4. 发送消息:创建 MQMessage 对象并写入消息内容,然后使用 Put 方法将消息放入队列中。
  5. 接收消息:创建 MQMessage 对象并使用 Get 方法从队列中获取消息。
  6. 关闭资源:确保在操作完成后关闭队列和断开队列管理器连接,以释放资源。
  7. 异常处理:捕获并处理可能发生的 MQExceptionSystem.Exception 异常。

请根据实际情况替换示例代码中的占位符(如 your.host.nameYOUR.CHANNEL.NAME 等)。

上一篇:c# sunnyui

下一篇:c# base64编码

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站