开发者

How to remove message from message queue (only if its well formatted)?

I want to take message from one queue and send it to database. I want to do it only if it's in specific format.

If i use Receive method directly and some exception occurs while accessing Body of the Message, I lose the message since Receive method of the MessageQueue removes the message from the queue.

To avoid loss of message, now i first Peek the message, and if its well formatted, I use Receive method to remove it from the queue to send it to database.

Code I have written is like this:

 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);
                }

Is this logic right to first using Peek and then Receive? Or is there any other better way f achieving the same thing? Please note that I dont want to get all messages at a time. MessageQueue is non transactional.


This is the same approach that I take when manually dequeuing message one at a time and I've not come across any issues with it.

The one thing that you do not appear to dealing with is how to handle a message on the queue that does not have the required format. Is your intention to leave it on the queue? If so, you might end up with a very large queue and have all sorts of issues with peeking at messages further up the queue that have not yet been expected. It would appear to make more sense to also de-queue those messages that do not have the required format and store them elsewhere if they cannot be deleted.


"If i use Receive method directly and some exception occurs while accessing Body of the Message, I lose the message since Receive method of the MessageQueue removes the message from the queue."

You should be using transactional receives so that the message returns to the queue when/if the transaction aborts.

Cheers
John Breakwell

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜