如果服务关闭一段时间,如何在c#中重新连接到MSMQ
本文关键字:重新连接 MSMQ 服务 一段时间 如果 | 更新日期: 2023-09-27 18:16:53
是否有可能在服务关闭后重新连接到MSMQ,而不重新启动我的应用程序?如果是,那是怎么回事?
我的代码是:void tmrDelay_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
tmrDelay.Stop();
while (isConnected)
{
try
{
if (ImportFromMSMQ.HasMessages())
{
MSMQ_ServiceLog.WriteEntry(string.Format("Transfering data from MSMQ to ActiveMQ started at {0}", DateTime.Now.ToString()));
while (ImportFromMSMQ.HasMessages())
{
ImportFromMSMQ.Run();
MSMQ_ServiceLog.WriteEntry(string.Format("Transfering data from MSMQ to ActiveMQ completed at {0}", DateTime.Now.ToString()));
}
}
else
{
MSMQ_ServiceLog.WriteEntry(string.Format("MSMQ is empty {0}", DateTime.Now.ToString()));
}
}
catch (Exception ex)
{
logger.Error(string.Format(" Error in data transfer MSMQ to ActiveMQ {0}", ex.Message));
MSMQ_ServiceLog.WriteEntry(string.Format(" Error in data transfer MSMQ to ActiveMQ {0}", ex.Message), EventLogEntryType.Error, -1);
}
}
tmrDelay.Start();
}
while循环是我添加的,但还没有测试,因为怀疑是无限循环。如果关闭了MSMQ服务,我们就会在catch
子句中结束,当MSMQ再次启动时,我们需要重新启动整个应用程序。但是,我如何重试连接到MSMQ,并在等待它再次启动时继续这样做?
public class ImportFromMSMQ
{
private static readonly ILog logger = LogManager.GetLogger(typeof(ImportFromMSMQ));
//Max records per records
private static int _maxMessagesPerTransaction = ConstantHelper.MaxMessagesPerTransaction;
private static bool _isNotCompleted = true;
private static int counter = 0;
private static MessageQueue mq;
private static long _maxMessageBodySizeLimitInBytes = ConstantHelper.MaxMessageBodySizeLimitInBytes;
// Start import
public static void Run()
{
Start();
}
public static bool HasMessages()
{
var _mqName = ConstantHelper.SourceQueue;
mq = new System.Messaging.MessageQueue(_mqName);
long _totalmsg = MessagesCounter.GetMessageCount(mq);
if (_totalmsg > 0)
{
logger.Info(string.Format(" {0} messages found in the {1} Queue ", _totalmsg.ToString(), _mqName));
}
else
{
logger.Info(string.Format(" There are no messages in the {1} Queue ", _totalmsg.ToString(), _mqName));
}
return _totalmsg > 0;
}
private static void Start()
{
logger.Info(string.Format("Data transfer starting at {0}", DateTime.Now.ToString()));
long _currentMessageBodySizeLimitInBytes = 0;
ArrayList messageList = new ArrayList();
System.Messaging.Message mes;
System.IO.Stream bodyStream = null;
// Create a transaction.
MessageQueueTransaction trans = new MessageQueueTransaction();
List<ConventionalData> objectList = new List<ConventionalData>();
IMessageContainer _container = new MessageContainer();
// Begin the transaction.
trans.Begin();
try
{
while (_isNotCompleted && counter < _maxMessagesPerTransaction)
{
try
{
counter++;
mes = mq.Receive(new TimeSpan(0, 0, 3), trans);
if (mes != null)
{
bodyStream = mes.BodyStream;
_currentMessageBodySizeLimitInBytes = _currentMessageBodySizeLimitInBytes + bodyStream.Length;
}
VisionAir.Messaging.ConventionalData data = ProtoBuf.Serializer.Deserialize<ConventionalData>(mes.BodyStream);
objectList.Add(data);
_isNotCompleted = _currentMessageBodySizeLimitInBytes <= _maxMessageBodySizeLimitInBytes;
}
catch
{
_isNotCompleted = false;
}
}
if (objectList.Count != 0)
{
logger.Info(string.Format("Starting transfer of {0} messages", objectList.Count));
_container.MQMessages = objectList;
ExportToActiveMQ _export = new ExportToActiveMQ(_container, (ExportOption) Enum.Parse(typeof(ExportOption),ConstantHelper.ExportFormat));
_export.Export();
}
logger.Info(string.Format("Transfer of {0} messages is completed at {1}",objectList.Count, DateTime.Now.ToString()));
// Commit transaction
trans.Commit();
counter = 0; //ResetF
_isNotCompleted = true; //Reset
}
catch (Exception ex)
{
logger.Error(ex);
// Roll back the transaction.
trans.Abort();
counter = 0;
}
}
}
我看过这个问题服务没有收到消息后消息队列服务重启,但似乎不完全理解它,所以如果有人能详细说明它,这将是很好的。
我必须递归地调用我的tmrDelay_Elapsed()
方法,我的catch
子句或其他什么?
我找到了解决方案,当我第一次意识到我们第一次访问队列是在HasMessages()
方法中时,这很简单,所以我将其更改为以下内容:
public static bool HasMessages()
{
var _mqName = ConstantHelper.SourceQueue;
long _totalmsg = 0;
int countAttempts = 0;
queueExists = false;
while (!queueExists)
{
if (MessageQueue.Exists(_mqName))
{
queueExists = true;
mq = new System.Messaging.MessageQueue(_mqName);
_totalmsg = MessagesCounter.GetMessageCount(mq);
if (_totalmsg > 0)
{
logger.Info(string.Format(" {0} messages found in the {1} Queue ", _totalmsg.ToString(), _mqName));
}
else
{
logger.Info(string.Format(" There are no messages in the {1} Queue ", _totalmsg.ToString(), _mqName));
}
}
else
{
logger.Info(string.Format("No Queue named {0} found, trying again.", _mqName));
countAttempts++;
if(countAttempts % 10 == 0)
{
logger.Info(string.Format("Still no queue found, have you checked Services that Message Queuing(Micrsoft Message Queue aka. MSMQ) is up and running"));
}
Thread.Sleep(5000);
}
}
return _totalmsg > 0;
}
我检查是否MessageQueue.Exists
并继续尝试,如果它不存在,直到我找到队列。当我找到它时,我将queueExists设置为true,以中断while循环,继续处理接收到的数据(如果接收到任何数据)。我在一些帖子中读到,使用Thread.Sleep(n)
是不好的,但现在我要用这个解决方案。