Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何不断从远程IBM MQ获取消息_C#_Windows Services_Ibm Mq - Fatal编程技术网

C# 如何不断从远程IBM MQ获取消息

C# 如何不断从远程IBM MQ获取消息,c#,windows-services,ibm-mq,C#,Windows Services,Ibm Mq,我创建了一个windows服务,该服务将连接到远程MQ并以MQSTR格式获取消息,但在获取消息后,我没有关闭到远程MQ的连接。我的windows服务将持续检查远程MQ中的数据是否可用,但在收到一条消息后,我需要重新启动服务以从远程MQ获取另一条消息。谁能告诉我需要做什么才能不断地从远程MQ获取消息。任何线索或链接都可以。请帮忙 我的C#windows服务代码如下: Program.cs using System; using System.Collections.Generic; using S

我创建了一个windows服务,该服务将连接到远程MQ并以MQSTR格式获取消息,但在获取消息后,我没有关闭到远程MQ的连接。我的windows服务将持续检查远程MQ中的数据是否可用,但在收到一条消息后,我需要重新启动服务以从远程MQ获取另一条消息。谁能告诉我需要做什么才能不断地从远程MQ获取消息。任何线索或链接都可以。请帮忙

我的C#windows服务代码如下:

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace MQ_listner
{
    static class Program
    {
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };
            ServiceBase.Run(ServicesToRun);


        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace MQ_listner
{
    public partial class Service1 : ServiceBase
    {
        private MQReader MQReader;
        private string _serviceName = "MQ_Listener";
        private DateTime _TimeStart;
        private bool _run = true; 
        private Thread _thread;
        int WaitWhenStop = 0;
        private DateTime _TimeEnd;
        private TimeSpan _TimeDifference;
        private TimeSpan _TimeElasped = new TimeSpan(0);



        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                EventLog.WriteEntry(_serviceName + "was started at" + _TimeStart.ToString());
                _run = true;

                _thread = new Thread(new ThreadStart(StartMQListenerService));
                _thread.IsBackground = true;
                _thread.Start();
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(_serviceName + "was not started . Error Message : " + ex.ToString());
            }


        }

        protected override void OnStop()
        {
            _run = false;
            _thread.Join(WaitWhenStop);

            _TimeEnd = DateTime.Now;
            _TimeDifference = _TimeEnd.Subtract(_TimeStart); 
            _TimeElasped = _TimeElasped.Add(_TimeDifference);
            EventLog.WriteEntry(_serviceName + "was stopped at " + _TimeEnd.ToString() + "\r\n ran for total time :" + _TimeElasped.ToString());
        }


        // MQ connection service 

        public void StartMQListenerService()
        {
            try
            {
                if (_run)
                {
                    if (MQReader == null)
                    {
                        MQReader = new MQReader();
                        MQReader.InitializeConnections();
                        EventLog.WriteEntry(_serviceName + "MQ connection is established");
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry(_serviceName, ex.ToString());
                System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo();
                startinfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startinfo.FileName = "NET";
                startinfo.Arguments = "stop" + this.ServiceName;
                Process.Start(startinfo);
            }
        }
    }
}


****MQReader.cs****

using System;
using IBM.WMQ;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Configuration;

namespace MQ_listner
{
    internal class MQReader
    {
        public MQReader()
        {
        }
        public void InitializeConnections()
        {

            MQQueueManager queueManager;
            MQMessage queueMessage;
            MQGetMessageOptions queueGetMessageOptions;
            MQQueue queue;


            string QueueName;
            string QueueManagerName;
            string ChannelInfo;
            string channelName;
            string PortNumber;
            string transportType;
            string connectionName;

            QueueManagerName = ConfigurationManager.AppSettings["QueueManager"]; 
            QueueName = ConfigurationManager.AppSettings["Queuename"];
            ChannelInfo = ConfigurationManager.AppSettings["ChannelInformation"];
            PortNumber = ConfigurationManager.AppSettings["Port"];
            char[] separator = { '/' };
            string[] ChannelParams;
            ChannelParams = ChannelInfo.Split(separator);
            channelName = ConfigurationManager.AppSettings["Channel"];
            transportType = ConfigurationManager.AppSettings["TransportType"];
            connectionName = ConfigurationManager.AppSettings["ConnectionName"];
            String strReturn = "";

            try
            {
                queueManager = new MQQueueManager(QueueManagerName,
                channelName, connectionName);
                strReturn = "Connected Successfully";

                queue = queueManager.AccessQueue(QueueName,
                MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);
                queueMessage = new MQMessage();
                queueMessage.Format = MQC.MQFMT_STRING;
                queueGetMessageOptions = new MQGetMessageOptions();
                queue.Get(queueMessage, queueGetMessageOptions);
                strReturn = queueMessage.ReadString(queueMessage.MessageLength);
            }
            catch (MQException exp)
            {
                strReturn = "Exception: " + exp.Message;
            }

            string path1 = @"C:\documents\Example.txt";
            System.IO.File.WriteAllText(path1, strReturn);

        }
    }
}
Service1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace MQ_listner
{
    static class Program
    {
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };
            ServiceBase.Run(ServicesToRun);


        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace MQ_listner
{
    public partial class Service1 : ServiceBase
    {
        private MQReader MQReader;
        private string _serviceName = "MQ_Listener";
        private DateTime _TimeStart;
        private bool _run = true; 
        private Thread _thread;
        int WaitWhenStop = 0;
        private DateTime _TimeEnd;
        private TimeSpan _TimeDifference;
        private TimeSpan _TimeElasped = new TimeSpan(0);



        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                EventLog.WriteEntry(_serviceName + "was started at" + _TimeStart.ToString());
                _run = true;

                _thread = new Thread(new ThreadStart(StartMQListenerService));
                _thread.IsBackground = true;
                _thread.Start();
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(_serviceName + "was not started . Error Message : " + ex.ToString());
            }


        }

        protected override void OnStop()
        {
            _run = false;
            _thread.Join(WaitWhenStop);

            _TimeEnd = DateTime.Now;
            _TimeDifference = _TimeEnd.Subtract(_TimeStart); 
            _TimeElasped = _TimeElasped.Add(_TimeDifference);
            EventLog.WriteEntry(_serviceName + "was stopped at " + _TimeEnd.ToString() + "\r\n ran for total time :" + _TimeElasped.ToString());
        }


        // MQ connection service 

        public void StartMQListenerService()
        {
            try
            {
                if (_run)
                {
                    if (MQReader == null)
                    {
                        MQReader = new MQReader();
                        MQReader.InitializeConnections();
                        EventLog.WriteEntry(_serviceName + "MQ connection is established");
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry(_serviceName, ex.ToString());
                System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo();
                startinfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startinfo.FileName = "NET";
                startinfo.Arguments = "stop" + this.ServiceName;
                Process.Start(startinfo);
            }
        }
    }
}


****MQReader.cs****

using System;
using IBM.WMQ;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Configuration;

namespace MQ_listner
{
    internal class MQReader
    {
        public MQReader()
        {
        }
        public void InitializeConnections()
        {

            MQQueueManager queueManager;
            MQMessage queueMessage;
            MQGetMessageOptions queueGetMessageOptions;
            MQQueue queue;


            string QueueName;
            string QueueManagerName;
            string ChannelInfo;
            string channelName;
            string PortNumber;
            string transportType;
            string connectionName;

            QueueManagerName = ConfigurationManager.AppSettings["QueueManager"]; 
            QueueName = ConfigurationManager.AppSettings["Queuename"];
            ChannelInfo = ConfigurationManager.AppSettings["ChannelInformation"];
            PortNumber = ConfigurationManager.AppSettings["Port"];
            char[] separator = { '/' };
            string[] ChannelParams;
            ChannelParams = ChannelInfo.Split(separator);
            channelName = ConfigurationManager.AppSettings["Channel"];
            transportType = ConfigurationManager.AppSettings["TransportType"];
            connectionName = ConfigurationManager.AppSettings["ConnectionName"];
            String strReturn = "";

            try
            {
                queueManager = new MQQueueManager(QueueManagerName,
                channelName, connectionName);
                strReturn = "Connected Successfully";

                queue = queueManager.AccessQueue(QueueName,
                MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);
                queueMessage = new MQMessage();
                queueMessage.Format = MQC.MQFMT_STRING;
                queueGetMessageOptions = new MQGetMessageOptions();
                queue.Get(queueMessage, queueGetMessageOptions);
                strReturn = queueMessage.ReadString(queueMessage.MessageLength);
            }
            catch (MQException exp)
            {
                strReturn = "Exception: " + exp.Message;
            }

            string path1 = @"C:\documents\Example.txt";
            System.IO.File.WriteAllText(path1, strReturn);

        }
    }
}
有人能告诉我我的代码出了什么问题吗?我是否需要在此处添加任何内容以不断从远程MQ获取消息。请帮忙。任何链接或线索都可以

编辑


经过一定时间后,我需要重新启动服务以从远程mq获取数据。您能告诉我为什么windows服务需要重新启动以获取数据吗。有线索吗?知道吗?

您的队列关闭和队列管理器断开连接在哪里?如果您连接和/或打开了某物,您必须确保关闭和断开连接。我强烈建议您参加MQ编程课程。或者转到具有MQ编程会话的

我发布了一个功能齐全的C#MQ程序,可以在

下面是MQReader类的更新版本,它应该给您提供正确的想法。注意:我没有测试它。我把这个留给你

此外,您应该将连接信息放入哈希表中,并将哈希表传递给MQQueueManager类

using System;
using IBM.WMQ;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Configuration;

namespace MQ_listner
{
    internal class MQReader
    {
        private MQQueueManager qManager = null;
        private MQMessage      inQ = null;
        private bool           running = true;

        public MQReader()
        {
        }

        public bool InitQMgrAndQueue()
        {
            bool flag = true;
            Hashtable qMgrProp = new Hashtable();
            qMgrProp.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
            qMgrProp.Add(MQC.HOST_NAME_PROPERTY, ConfigurationManager.AppSettings["ConnectionName"]);
            qMgrProp.Add(MQC.CHANNEL_PROPERTY, ConfigurationManager.AppSettings["Channel"]);

            try
            {
               if (ConfigurationManager.AppSettings["Port"] != null)
                  qMgrProp.Add(MQC.PORT_PROPERTY, System.Int32.Parse(ConfigurationManager.AppSettings["Port"]));
               else
                  qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
            }
            catch (System.FormatException e)
            {
               qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
            }

            if (ConfigurationManager.AppSettings["UserID"] != null)
               qMgrProp.Add(MQC.USER_ID_PROPERTY, ConfigurationManager.AppSettings["UserID"]);

            if (ConfigurationManager.AppSettings["Password"] != null)
               qMgrProp.Add(MQC.PASSWORD_PROPERTY, ConfigurationManager.AppSettings["Password"]);

            try
            {
                qManager = new MQQueueManager(ConfigurationManager.AppSettings["QueueManager"],
                                              qMgrProp);
                System.Console.Out.WriteLine("Connected Successfully");

                inQ = qManager.AccessQueue(ConfigurationManager.AppSettings["Queuename"],
                                              MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);
                System.Console.Out.WriteLine("Open queue Successfully");
            }
            catch (MQException exp)
            {
                System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
                flag = false;
            }

            return flag;
        }

        public void LoopThruMessages()
        {
            MQGetMessageOptions gmo = new MQGetMessageOptions();
            gmo.Options |= MQC.MQGMO_WAIT | MQC.MQGMO_FAIL_IF_QUIESCING;
            gmo.WaitInterval = 2500;  // 2.5 seconds wait time or use MQC.MQEI_UNLIMITED to wait forever
            MQMessage msg = null;

            while (running)
            {
                try
                {
                   msg = new MQMessage();
                   inQ.Get(msg, gmo);
                   System.Console.Out.WriteLine("Message Data: " + msg.ReadString(msg.MessageLength));
                }
                catch (MQException mqex)
                {
                   if (mqex.Reason == MQC.MQRC_NO_MSG_AVAILABLE)
                   {
                      // no meesage - life is good - loop again
                   }
                   else
                   {
                      running = false;  // severe error - time to exit
                      System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
                   }
                }
                catch (System.IO.IOException ioex)
                {
                   System.Console.Out.WriteLine("ioex=" + ioex);
                }
            }

            try
            {
               if (inQ != null)
               {
                  inQ.Close();
                  System.Console.Out.WriteLine("Closed queue");
               }
            }
            catch (MQException mqex)
            {
                System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
            }

            try
            {
               if (qMgr != null)
               {
                  qMgr.Disconnect();
                  System.Console.Out.WriteLine("disconnected from queue manager");
               }
            }
            catch (MQException mqex)
            {
                System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
            }
        }

        public void StopIt()
        {
            running = false;
        }
    }
}

每当您停止服务时,请确保它调用MQReader中的StopIt方法。

没有获取消息的循环。@Reniuz感谢您的回复:)但是您能告诉我需要做什么吗?因为我有点困惑如何不断地从远程MQ获取消息。我正在启动我的服务,然后下载了一条消息,对于第二条消息,我必须重新启动服务。因为服务一直在运行,但我无法一直收到消息。您需要一个异步事件来检测何时收到数据。我看起来你有一个表单,我不知道为什么你需要使用线程,如果表单已经在运行。表单通常是进程,因此如果您使用事件来读取数据,则不需要第二级表单。在服务启动时,您只需获取一条消息。只需添加循环即可不断获取消息。您知道如何使用线程(这里根本不需要线程),因此您应该知道如何编写循环。您还可以查看XMS.NET,它有一个消息使用者,您只需注册一个onMessage方法,以便为收到的每条消息调用。谢谢:)以更正我的代码。从MQ获取消息后,我关闭了MQ连接。但您能告诉我为什么我们需要使用哈希表来连接远程MQE吗?正如我已经说过的,MQEnvironment类不是线程安全的,并且您所使用的方式不允许任何类型的安全性。i、 e.SSL/TLS或安全出口。始终,安全第一,业务逻辑第二。突然过了一段时间,我需要重新启动windows服务,从远程mq下载文件。你能告诉我为什么吗?有线索吗?任何想法。我关闭了来自mq的连接,并解决了从循环获取消息的问题。为什么我需要重新启动windows服务?如果您关闭队列或断开与队列管理器的连接,并且在1分钟或2分钟后没有代码重新连接,则听起来您的设计很糟糕。MQ中没有魔力。如果希望在不重新启动服务的情况下重新连接,请添加代码。