简体   繁体   中英

Read message from MSMQ by Label

I need to create a C# based MSMQ environment where I need to be able to read messages from the queue based on some unique value which has been supplied by an external process. ie Ideally something like ReceiveByLabel("1234"). I can arrange things such that the label is unique but there does not seem to be easy way to do this. I could use he GetAllMessage enumerator but as here may be 30,000 messages on the queue this is probably going to to be very slow.

Any ideas suggestions would be much appreciated.

I would suggest to use correlation id. 1. Need to build correlation id (38-42 chars length). Can be build in any manner, as example build it by GUID

    /// <summary>
    /// Generate random correlation ID(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\xxxxx)
    /// </summary>
    /// <returns>string</returns>
    /// <param name="id">if want specific id in end of generated id, else it will be random forom 1- 10000</param>
    public string GenerateId(int id = 0)
    {
        if (id == 0)
        {
            Random r = new Random();
            id = r.Next(1, 10000);
            id = r.Next(1, 10000);
        }
        return $"{Guid.NewGuid().ToString()}\\{id.ToString()}";
    }
  1. Specify message with generated correlation id.

     Message message = new Message(); string messageUniqueID = GenerateId(); message.CorrelationId = messageUniqueID;
  2. Receive it by this correlation id.

     string yourQueuePath= "..."; MessageQueue queue = new MessageQueue(yourQueuePath); Message myMessage = queue.ReceiveByCorrelationId(messageUniqueID);

Id's can be specified and generated in code or in any other manner(save in DB etc.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM