MassTransit - 如何创建具有通用类型和 2 个不同消费者的交换主题

MassTransit - How to create an exchange topic with a generic type and 2 different consumers

我正在使用通用事件类型和 2 个不同的消费者创建主题交换,我想知道是否有更好的方法使用通用来完成此操作?

我最近怎么样

一般事件:

public interface IOrchestratorTopicType<T> where T : class
    {
        public Guid? TraceId { get; set; }
        public string Event { get; set; }
        public string Source { get; set; }
        public string Destination { get; set; }
        public T Data { get; set; }
    }

配置:

services.AddMassTransit(bus =>
            {
                bus.SetKebabCaseEndpointNameFormatter();

                bus.UsingRabbitMq((ctx, busConfigurator) =>
                {
                    busConfigurator.Host(configuration.GetConnectionString("RabbitMq"));

                    busConfigurator.Publish<IOrchestratorTopicType<object>>(a => a.ExchangeType = ExchangeType.Topic);

                    busConfigurator.ReceiveEndpoint("create-order", e =>
                    {
                        e.ConfigureConsumeTopology = false;
                        e.Consumer<CreateOrderConsumer>();
                        e.Bind<IOrchestratorTopicType<object>>(s =>
                        {
                            s.RoutingKey = "create.order";
                            s.ExchangeType = ExchangeType.Topic;
                        });
                    });

                    busConfigurator.ReceiveEndpoint("valid-order", e =>
                    {
                        e.ConfigureConsumeTopology = false;
                        e.Consumer<ValidOrderConsumer>();
                        e.Bind<IOrchestratorTopicType<object>>(s =>
                        {
                            s.RoutingKey = "valid.order";
                            s.ExchangeType = ExchangeType.Topic;
                        });
                    });
                });
            });
            services.AddMassTransitHostedService();

制作人:

await _publisher.Publish<IOrchestratorTopicType<object>>(new
                {
                    TraceId = new Guid(),
                    Event = "create.order",
                    Source = "SourceTestSource",
                    Destination = "DestinationTest",
                    Data = createOrderModel
                }, e => e.TrySetRoutingKey("create.order"));

消费者:

public class ValidOrderConsumer : IConsumer<IOrchestratorTopicType<object>>
    {
        public Task Consume(ConsumeContext<IOrchestratorTopicType<object>> context)
        {
            throw new NotImplementedException();
        }
    }

public class CreateOrderConsumer : IConsumer<IOrchestratorTopicType<object>>
    {
        public Task Consume(ConsumeContext<IOrchestratorTopicType<object>> context)
        {
            throw new NotImplementedException();
        }
    }

我希望生产者发送对象的确切类型,消费者使用对象的确切类型而不是通用对象

我建议观看 this video MassTransit 如何使用 RabbitMQ。零需要使用与 MassTransit 的主题交换,因为它默认使用基于类型的路由。

我不推荐上面的代码,因为 MassTransit 已经默认使用 RabbitMQ 进行基于多态类型的路由。