David Nguyen
David Nguyen

Reputation: 51

Duplicated messages sent to MassTransit consumer

I have a MassTransit sample program that publishes 1 single message whose body is current timestamp. However, it's strange that there are always exactly 5 times that the consumers get called.

The program is as below:

public class MassTransitTest
{
    static void Main(string[] args)
    {
        var bus = ServiceBusFactory.New(x =>
        {
            x.UseRabbitMq();
            x.ReceiveFrom("rabbitmq://localhost/test");
            x.Subscribe(s => s.Consumer(() => new MyConsumer()));
        });

        bus.Publish<IMyObject>(new MyObject { Timestamp = DateTime.Now.ToString("yyyyMMddHHmmssffff"), CorrelationId = Guid.NewGuid() });
    }
}

public interface IMyObject : CorrelatedBy<Guid>
{
    string Timestamp { get; }
}

public class MyObject : IMyObject
{
    public string Timestamp { get; set; }
    public Guid CorrelationId { get; set; }
}

public class MyConsumer : Consumes<IMyObject>.All, IBusService
{
    private IServiceBus bus;

    private static int count = 0; // to gauge the call to handler

    public void Consume(IMyObject message)
    {
        count++;
        Console.WriteLine("Encounter message " + count);
        Console.WriteLine(message.Timestamp);
    }

    public void Start(IServiceBus bus)
    {
        this.bus = bus;
    }

    public void Stop()
    {            
    }

    public void Dispose()
    {
        bus.Dispose();
    }
}

The output is as below:

Encounter message 1
201410131349034661
Encounter message 2
201410131349034661
Encounter message 3
201410131349034661
Encounter message 4
201410131349034661
Encounter message 5
201410131349034661

Upvotes: 5

Views: 2496

Answers (2)

David Castro
David Castro

Reputation: 1967

In my case, I was getting an error within the consumer calling a method trying to save data, and my catch was also failing. Since the consumer couldn't send any appropriate response success/failed the consumer was trying to retry over and over again. Make sure you're not getting any errors within the consumer process.

Upvotes: 0

Chris Patterson
Chris Patterson

Reputation: 33278

You should not dispose of the bus in the Consumer, nor should you be an IBusService. The .Dispose method is probably throwing an exception, which causes the consumer to Retry.

You should also wait before your program exits, and call bus.Dispose once you're done processing.

IBusService start is not called, because consumers are not bus services, so the bus member is always null.

Upvotes: 3

Related Questions