How to add two process into separate queue using RabbitMQ

Viewed 194

In my application, I have consumer called MessageConsumer, which were responsible for consume message request and send messages as SMS and Email.

public class MessageConsumer : IConsumer<MessageRequest>
{
    IMessage _message;
    public MessageConsumer(IMessage message)
    {
        _message = message;
    }

    public Task Consume(ConsumeContext<MessageRequest> context)
    {
        var data = new Dictionary<string, string>();
        data.Add("name", "stack");
        data.Add("mobile", "002");

        try
        {
            var viaList = context.Message.ViaList;
            foreach (var item in viaList)
            {
                _message.TriggerMessage(data,item);
            }
        }
        catch (System.Exception ex)
        {
            System.Console.WriteLine(ex.Message);
            throw;
        }
        return Task.CompletedTask;
    }
}

TriggerMessage() implementation as follows, here I checking the Via type, inside the switch I process the each SMS and Email Sending methods,

public class Message : IMessage
{
    private ISmsSend _sms;
    private IEmailSend _email;
    public Message(ISmsSend sms , IEmailSend email)
    {
        _sms = sms;
        _email = email;
    }

    public void TriggerMessage(Dictionary<string, string> data , int via)
    {
        switch (via)
        {
            case 1:
                _sms.send(data);
                break;
            case 2:
                _email.send(data);
                break;
        }
    }
}

For an example those methods working as follows,

public class Email : IEmailSend
{
    public void send(Dictionary<string, string> data)
    {
        Console.WriteLine("Start the email sending");
    }
}

public class Sms : ISmsSend
{
    public void send(Dictionary<string, string> data)
    {
        Console.WriteLine("Start the Sms sending");
    }
}

This is just a sample code, to present my concern. Now my concern is, suppose above MessageConsumer execute for request called "Request A". according to the above code somehow, Email sending logic throws an exception. SMS logic also will be failed. Suppose, even though Failed to send email, but if I execute the SMS sending process by handling try-catch inside the Email logic (without throw exceptions) , Email send part never execute again for that "Request A". So how can I handle this? can I add Email sending and SMS sending part to the separate Queues? if yes how can I do it? please help me.

1 Answers

You really should have separate commands, and separate consumers, for email and SMS messages. Using subclasses of an interface in a message contract, while it can be supported by reconfiguring the serializer, is not recommended.

It simplifies the consumer, reduces the dependencies of each consumer to either email or SMS components, and allows the messages to be split across two queues, one queue for each consumer.

Related