gpt4 book ai didi

c# - MassTransit 自动添加消费者

转载 作者:行者123 更新时间:2023-12-03 08:26:03 28 4
gpt4 key购买 nike

我正在使用 MassTransit 连接到我们的 RabbitMQ。目前我正在致力于将代码推广到使用它的 15 个解决方案中。但我在设置部分遇到了障碍。原来它看起来像这样:

  services.AddMassTransit(c =>
{
c.AddConsumer<MoveMouldConsumer>();
c.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
{
cfg.UseHealthCheck(provider);
cfg.Host(MassTransitHelper.CreateRabbitMQEndpointUri(messageQueueSettings), h =>
{
h.Username(messageQueueSettings.Username);
h.Password(messageQueueSettings.Password);
});

cfg.PrefetchCount = (ushort) messageQueueSettings.PrefetchCount;
cfg.MessageTopology.SetEntityNameFormatter(new EntityNameFormatter());
cfg.ExchangeType = ExchangeType.Direct;

cfg.ReceiveEndpoint(NameFormatter.FormatQueueName<MouldMovementEvent>("serviceName"), e =>
{
e.Bind(NameFormatter.FormatExchangeName<MouldMovementEvent>()); //Bind to Exchange
e.UseMessageRetry(r => r.Incremental(5, 5.Seconds(), 10.Seconds()));
e.ExclusiveConsumer = false;
e.PrefetchCount = messageQueueSettings.PrefetchCount;
e.Consumer<MoveMouldConsumer>(provider);
e.UseCircuitBreaker(cb =>
{
cb.TripThreshold = 15;
cb.ActiveThreshold = 10;
cb.ResetInterval = 5.Minutes();
});
});
}));
});

到目前为止,我已经成功地将其概括为:

services.AddMassTransit(c =>
{
c.AddConsumer<MoveMouldConsumer>();
c.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>
{
cfg.UseHealthCheck(provider);
MassTransitSetup.BasicSetup(cfg, messageQueueSettings);
MassTransitSetup.InitializeConsumer<MouldMovementEvent, MoveMouldConsumer>(cfg, messageQueueSettings, provider, 5, "report");
}));
});

但我缺少的部分是,我喜欢能够通过从我喜欢的程序集获取来自动添加所有消费者:

var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => typeof(IConsumer).IsAssignableFrom(p) && p.IsClass && !p.IsAbstract && p.Namespace!.Contains("MST.Hepper.")).ToList();

但我的问题是如何迭代并添加 c.AddConsumer<>();MassTransitSetup.InitializeConsumer<,>

最佳答案

MassTransit 具有根据程序集、类型等自动配置消费者的方法。

services.AddMassTransit(x =>
{
// Add a single consumer
x.AddConsumer<SubmitOrderConsumer>(typeof(SubmitOrderConsumerDefinition));

// Add a single consumer by type
x.AddConsumer(typeof(SubmitOrderConsumer), typeof(SubmitOrderConsumerDefinition));

// Add all consumers in the specified assembly
x.AddConsumers(typeof(SubmitOrderConsumer).Assembly);

// Add all consumers in the namespace containing the specified type
x.AddConsumersFromNamespaceContaining<SubmitOrderConsumer>();
});

Related Documentation Link

关于c# - MassTransit 自动添加消费者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66601229/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com