.NET Core + RabbitMQ

عند تطوير الخدمات المتناهية الصغر ، يطرح السؤال توفير معلومات من خدمة إلى خدمات أخرى عند حدوث أي أحداث. من المهم أن يكون لديك نظام دون ربط المرسل بالمستلمين. في هذه الحالة ، يتم استخدام نمط المشتركين الناشرين.

هناك العديد من منتجات المراسلة في السوق التي تدعم نمط الناشر-المشترك ، مثل Azure Service Bus أو RabbitMQ أو Apache Kafka.

لقد قمت مؤخرًا بنشر مكتبتي NuGet للإعداد السريع والمريح للاتصال القائم على الأحداث باستخدام Azure Service Bus و RabbitMQ. تصف هذه المقالة الإرشادية القصيرة خطوات استخدام الأخير.

مصدر


إن Publisher هو تطبيق .NET Core يعمل كمرسل.
المشترك هو تطبيق .NET Core يعمل كمستلم.

كيف


1. في الناشر و المشترك التطبيقات، تثبيت اثنين NuGet المكتبات.

PM> Install-Package Autofac.Extensions.DependencyInjection
PM> Install-Package EventBus.RabbitMQ.Standard


2. في الناشر و المشترك التطبيقات، إضافة إلى تكوين appsettings.json .

{
  "RabbitMq": {
    "BrokerName": "test_broker",
    "AutofacScopeName": "test_autofac",
    "QueueName": "test_queue",
    "RetryCount": "5",
    "VirtualHost": "your_virtual_host",
    "Username": "your_username",
    "Password": "your_password",
    "Host": "your_host",
    "DispatchConsumersAsync": true
  }
}

هذه الإعدادات متاحة على CoudAMQP . بدلاً من ذلك ، يمكنك استخدام RabbitMQ محليًا ( صورة Docker ).

3. في الناشر و المشترك التطبيقات، إنشاء فئة لهذا الحدث التي سيتم نشرها ومعالجتها في وقت لاحق.

public class ItemCreatedIntegrationEvent : IntegrationEvent
{
    public string Title { get; set; }
    public string Description { get; set; }

    public ItemCreatedIntegrationEvent(string title, string description)
    {
        Title = title;
        Description = description;
    }
}


4. في تطبيق المشترك ، قم بإنشاء فئة لمعالج الأحداث ItemCreatedIntegrationEvent .

public class ItemCreatedIntegrationEventHandler : IIntegrationEventHandler<ItemCreatedIntegrationEvent>
{
    public ItemCreatedIntegrationEventHandler()
    {
    }

    public async Task Handle(ItemCreatedIntegrationEvent @event)
    {
        //Handle the ItemCreatedIntegrationEvent event here.
    }
}


5. في الناشر و المشترك التطبيقات وتحديث Program.cs لإضافة سطر واحد.

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseServiceProviderFactory(new AutofacServiceProviderFactory()) //Add this line.
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}


6. في تطبيق الناشر ، قم بتحديث طريقة ConfigureServices في Startup.cs .

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        ...

        var rabbitMqOptions = Configuration.GetSection("RabbitMq").Get<RabbitMqOptions>();

        services.AddRabbitMqConnection(rabbitMqOptions);
        services.AddRabbitMqRegistration(rabbitMqOptions);

        ...
    }
}


7. في تطبيق المشترك ، قم بتكوين ملحق EventBusExtension .

public static class EventBusExtension
{
    public static IEnumerable<IIntegrationEventHandler> GetHandlers()
    {
        return new List<IIntegrationEventHandler>
        {
            new ItemCreatedIntegrationEventHandler()
        };
    }

    public static IApplicationBuilder SubscribeToEvents(this IApplicationBuilder app)
    {
        var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();

        eventBus.Subscribe<ItemCreatedIntegrationEvent, ItemCreatedIntegrationEventHandler>();

        return app;
    }
}


8. في المشترك التطبيق، تحديث ConfigureServices و تكوين طرق في Startup.cs .

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        ...

        var rabbitMqOptions = Configuration.GetSection("RabbitMq").Get<RabbitMqOptions>();

        services.AddRabbitMqConnection(rabbitMqOptions);
        services.AddRabbitMqRegistration(rabbitMqOptions);
        services.AddEventBusHandling(EventBusExtension.GetHandlers());

        ...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        ...

        app.UseAuthorization();

        ...
    }
}


9. للتوضيح والبساطة ، يمكنك إنشاء وحدة تحكم في تطبيق الناشر بالطريقة التي تم بها نشر الحدث.

public class ItemController : ControllerBase
{
    private readonly IEventBus _eventBus;

    public ItemController(IEventBus eventBus)
    {
        _eventBus = eventBus;
    }

    [HttpPost]
    public IActionResult Publish()
    {
        var message = new ItemCreatedIntegrationEvent("Item title", "Item description");

        _eventBus.Publish(message);

        return Ok();
    }
}


10. يمكنك الآن نشر ItemCreatedIntegrationEvent. قم بتشغيل كلا التطبيقين ، واستدعاء طريقة النشر POST في المشترك والتعامل مع الحدث في المشترك .

المراجع


Source: https://habr.com/ru/post/undefined/


All Articles