问题
I attempt to stop the bus after all the messages in queue consumed using MassTransit. And I set the concurrent Message limit to 1 as my consumer needs to process one message at a time.
I've tried putting the bus.StopAsync() behind bus.StartAsync like below. And the result showed that after one message being consumed, the bus will stop.
Bus configuration:
IBusControl bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
{
IRabbitMqHost host = cfg.Host(new Uri("rabbitmq://localhost"), hostConfigurator =>
{
hostConfigurator.Username("username");
hostConfigurator.Password("password");
});
cfg.ReceiveEndpoint(host, "MyResult", ep =>
{
ep.Bind("MyExchange", s => { s.Durable = true; });
ep.Consumer<MessageConsumer>(mc =>
{
mc.UseConcurrentMessageLimit(1);
});
});
});
Bus start and stop:
await bus.StartAsync();
await bus.StopAsync();
My question is how to stop the bus after all messages in queue have been consumed. I am quite new to MassTransit, and really curious about the sequence of invoking consumers and stopping bus. Appreciate if someone could help. Thanks.
回答1:
In the Testing namespace, there is a feature used to watch for activity on the bus, which could be used to signal that there are no messages being consumed (after which, you could stop the bus as you suggest).
You can see the unit test: https://github.com/MassTransit/MassTransit/blob/develop/src/MassTransit.Tests/BusActivityMonitor_Specs.cs#L69
The observer is added using:
var activityMonitor = bus.CreateBusActivityMonitor(TimeSpan.FromMilliseconds(500));
Once the bus is idle, the timeout will be true:
var timeout = await activityMonitor.AwaitBusInactivity(TimeSpan.FromSeconds(10));
If timeout is true, there is no activity on the bus in the time specified.
来源:https://stackoverflow.com/questions/56035978/masstransit-how-to-stop-the-bus-after-all-messages-are-consumed-by-consumer