我有一个MassTransit示例程序,它发布一条消息,其正文是当前时间戳。然而,奇怪的是,消费者总是被召唤5次。
该计划如下:
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();
}
}
输出如下:
Encounter message 1
201410131349034661
Encounter message 2
201410131349034661
Encounter message 3
201410131349034661
Encounter message 4
201410131349034661
Encounter message 5
201410131349034661
答案 0 :(得分:1)
您不应该在消费者中丢弃总线,也不应该是IBusService。 .Dispose方法可能抛出异常,导致使用者重试。
您还应该在程序退出之前等待,然后调用总线。一旦完成处理,请暂停。
不调用IBusService start,因为使用者不是总线服务,因此总线成员始终为null。