Giter Club home page Giter Club logo

rabbitmq.eventbus.extension.aspnetcore's Introduction

License: MIT

[TOC]

RabbitMQ.EventBus.Extension.AspNetCore

Lightweight EventBus Extension Library implementation of RabbitMQ.Client in ASP .NET Core Application.

Install Package

https://www.nuget.org/packages/RabbitMQ.EventBus.Extension.AspNetCore

Configure

Startup.cs

1. Connection registration

public void ConfigureServices(IServiceCollection services)
{
    // 注册 RabbitMQ
    services.AddRabbitMQEventBus(() => Configuration.GetConnectionString("Rabbit"),
    eventBusOption =>
    {
        eventBusOption.ClientProvidedAssembly(typeof(Startup).Namespace);
        eventBusOption.EnableRetryOnFailure(true, 5000, TimeSpan.FromSeconds(30));
        eventBusOption.RetryOnFailure(TimeSpan.FromSeconds(1));
        eventBusOption.MessageTTL(2000);
        eventBusOption.SetBasicQos(10);
        eventBusOption.DeadLetterExchangeConfig(config =>
        {
            config.Enabled = true;
             config.ExchangeNameSuffix = "";
        });
    });
    
    services.AddControllers();
}

2. Message subscription

2.1 Automatic subscription

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();

    app.UseRabbitMQEventBus(); // Automatic subscription

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

2.2 Manual subscription

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IRabbitMQEventBus eventBus)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();

    eventBus.Subscribe<MessageBody>(); // Manual subscription 

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

3. Publish message

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly IRabbitMQEventBus _eventBus;

    public ValuesController(IRabbitMQEventBus eventBus)
    {
        _eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus));
    }

    // GET: api/<ValuesController>
    [HttpGet]
    public ActionResult<string> Get()
    {
        return "The path variable must be 0 or 1.";
    }

    // GET: api/<ValuesController>/5
    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
        var routingKey = $"rabbitmq.eventbus.test{(id > 0 ? id + "" : "")}";

        _eventBus.Publish(new
        {
            Body = $"{routingKey} => 发送消息",
            Time = DateTimeOffset.Now
        }, exchange: "RabbitMQ.EventBus.Simple", routingKey: routingKey);

        return "Ok";
    }
}

4. Subscription message

// routingKey: rabbitmq.eventbus.test
[EventBus(Exchange = "RabbitMQ.EventBus.Simple",RoutingKey = "rabbitmq.eventbus.test")]
public class MessageBody : IEvent
{
    public string Body { get; set; }
    public DateTimeOffset Time { get; set; }
}

public class MessageBodyHandle : IEventHandler<MessageBody>, IDisposable
{
    private readonly Guid _id;
    private readonly ILogger<MessageBodyHandle> _logger;

    public MessageBodyHandle(ILogger<MessageBodyHandle> logger)
    {
        _id = Guid.NewGuid();
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public Task Handle(EventHandlerArgs<MessageBody> args)
    {
        Console.WriteLine("==================================================");
        Console.WriteLine(_id + "=>" + nameof(MessageBody));
        Console.WriteLine(args.Event.Body);
        Console.WriteLine(args.Original);
        Console.WriteLine(args.Redelivered);
        Console.WriteLine("==================================================");
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        Console.WriteLine("释放");
    }
}


// routingKey: rabbitmq.eventbus.test1
[EventBus(Exchange = "RabbitMQ.EventBus.Simple",RoutingKey = "rabbitmq.eventbus.test1")]
public class MessageBody1 : IEvent
{
    public string Body { get; set; }
    public DateTimeOffset Time { get; set; }
}

public class MessageBodyHandle11 : IEventHandler<MessageBody1>, IDisposable
{
    private readonly Guid _id;
    private readonly ILogger<MessageBodyHandle11> _logger;

    public MessageBodyHandle11(ILogger<MessageBodyHandle11> logger)
    {
        _id = Guid.NewGuid();
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public Task Handle(EventHandlerArgs<MessageBody1> args)
    {
        Console.WriteLine("==================================================");
        Console.WriteLine(_id + "=>" + nameof(MessageBody1));
        Console.WriteLine(args.Event.Body);
        Console.WriteLine(args.Original);
        Console.WriteLine(args.Redelivered);
        Console.WriteLine("==================================================");
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        Console.WriteLine("释放");
    }
}

public class MessageBodyHandle12 : IEventHandler<MessageBody1>
{
    private readonly Guid _id;
    private readonly ILogger<MessageBodyHandle12> _logger;

    public MessageBodyHandle12(ILogger<MessageBodyHandle12> logger)
    {
        _id = Guid.NewGuid();
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public Task Handle(EventHandlerArgs<MessageBody1> args)
    {
        Console.WriteLine("==================================================");
        Console.WriteLine(_id + "=>" + nameof(MessageBody1));
        Console.WriteLine(args.Event.Body);
        Console.WriteLine(args.Original);
        Console.WriteLine(args.Redelivered);
        Console.WriteLine("==================================================");
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        Console.WriteLine("释放");
    }
}

rabbitmq.eventbus.extension.aspnetcore's People

Contributors

run2948 avatar

Stargazers

 avatar Artsyom Avanesov  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.