我想从一个队列中获取消息并将其发送到数据库。我只想在特定格式的情况下这样做。如何从消息队列中删除消息(仅在格式良好的情况下)?
如果我使用直接Receive
方法和在访问消息的Body
发生一些异常,我失去消息由于MessageQueue
的Receive
方法从队列中移除该消息。
为了避免丢失信息,现在我第一次使用Peek
这条信息,如果它的格式良好,我使用Receive
方法将它从队列中移除并将它发送到数据库。我已经写
代码是这样的:
Message msg = _queue.Peek(new TimeSpan(0, 0, LoggingService.Configuration.ReceiveTimeout));
// LogMessage is my own class which is adding some more stuff to original message from MessageQueue
LogMessage message = null;
if (msg != null)
{
if (!(msg.Formatter is BinaryMessageFormatter))
msg.Formatter = new BinaryMessageFormatter();
message = LogMessage.GetLogMessageFromFormattedString((string) msg.Body);
// Use Receive method to remove the message from queue. This line will we executed only if the above line does not
// throw any exception i.e. if msg.Body does not have any problem
Message wellFormattedMsg =
_queue.ReceiveById(msg.Id);
SendMessageToDatabase(message);
}
这是逻辑有权首先使用窥视,然后接收?或者有没有其他更好的方法来实现同样的目标?请注意,我不想一次收到所有消息。 MessageQueue是非事务性的。
相关[我怎样才能把一个队列中的消息?(http://stackoverflow.com/q/23227194/706456) – oleksii 2014-05-23 11:27:49