首页 > 解决方案 > Rebus - 在 ASP.NET Core 中订阅事件

问题描述

我在 ASP.NET MVC Core 中有两个使用 Rebus 的应用程序我可以使用 Bus.Send(...) 在两个应用程序之间发送消息。我不能在创建后发布诸如 CustomerCreated 之类的事件,以便其他应用程序可以采取行动。

我已将应用程序配置如下

public void ConfigureServices(IServiceCollection services)
{    
     services.AutoRegisterHandlersFromAssemblyOf<Handler1>();
     services.AddRebus(configure => configure
            .Logging(l => l.Use(new MSLoggerFactoryAdapter(_loggerFactory)))
            .Transport(t=>t.UseRabbitMq("amqp://guest:guest@localhost:5672", "rebus_rabbit_first"))
                    .Sagas(x => x.StoreInSqlServer("Data Source=.;Initial Catalog=RebusDBRabbit;User ID=student;Password=student;", "Sagas", "SagaIndex"))
                    .Options(o =>
                    {
                        o.SetNumberOfWorkers(10);
                        o.SetMaxParallelism(20);
                        o.HandleMessagesInsideTransactionScope();
                        o.SimpleRetryStrategy(errorQueueAddress: "somewhere_else", maxDeliveryAttempts: 10, secondLevelRetriesEnabled: true);

                     })

                    .Routing(r => r.TypeBased()
                    .MapAssemblyOf<CreateStudent>("rebus_rabbit_second")));


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

在控制器中,我向另一个应用程序发送消息,如下所示

CreateStudent student = new CreateStudent { StudentID="90008", StudentName="Amour Rashid Hamad",DateOfBirth=DateTime.Parse("1974-03-18") };
_bus.Send(student).Wait();

还行吧。现在我的问题是发布一个事件以将事件广播给其他相关方,例如

 _bus.Publish(new StudentCreated { StudentID="90008",Remarks="Hurray We have been Successfully"});

如何根据我的配置订阅事件。我看过一些样本,但我无法理解它们。添加到我的实现将是首选。

标签: c#.net-coreeventsrebus

解决方案


在服务配置中,我做了如下:

app.ApplicationServices.UseRebus(async bus => {
  await bus.Subscribe<StudentCreated>();
            });

然后创建了一个处理程序

public class StudentCreatedEventHandler : IHandleMessages<StudentCreated>, IHandleMessages<IFailed<StudentCreated>>
    {
        readonly IBus _bus;

        public StudentCreatedEventHandler(IBus bus)
        {
            _bus = bus;
        }

        public async Task Handle(StudentCreated student)
        {
            // do stuff that can fail here...
            var remarks = $"Remarks on RebusWithRabbit1 : {student.Remarks}";

        }

        public async Task Handle(IFailed<StudentCreated> failedMessage)
        {
            await _bus.Advanced.TransportMessage.Defer(TimeSpan.FromSeconds(30));
        }
}

这可以处理发布的事件。我只是想确定这是否是正确的做法。

然而,我注意到一件事。如果我有多个订阅事件的端点,则只通知一个。我预计可能需要通知多个端点,并且每个端点都可能从同一事件执行不同的过程。

有什么办法可以改变这种行为。我记得在 MassTransit 中这是默认行为。谢谢


推荐阅读