Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicated messages sent to MassTransit consumer

Tags:

masstransit

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
like image 200
David Nguyen Avatar asked Oct 20 '22 00:10

David Nguyen


1 Answers

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.

like image 95
Chris Patterson Avatar answered Oct 24 '22 02:10

Chris Patterson