Существует множество примеров RabbitMQ в c #. Но если вы собираетесь реализовать ядро asp.net и если сервис должен запускаться автоматически при запуске api, все равно не можете найти простые примеры
Нужно сделать statup.cs вот так.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;
using RabbitMQReiverCoreAPI.RebbitMQ;
namespace RabbitMQReiverCoreAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSingleton<RabbitMQPersistentConnection>(sp =>
{
var logger = sp.GetRequiredService<ILogger<RabbitMQPersistentConnection>>();
var factory = new ConnectionFactory()
{
HostName = Configuration["EventBusConnection"]
};
if (!string.IsNullOrEmpty(Configuration["EventBusUserName"]))
{
factory.UserName = Configuration["EventBusUserName"];
}
if (!string.IsNullOrEmpty(Configuration["EventBusPassword"]))
{
factory.Password = Configuration["EventBusPassword"];
}
return new RabbitMQPersistentConnection(factory);
});
services.AddOptions();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
//Initilize Rabbit Listener in ApplicationBuilderExtentions
app.UseRabbitListener();
}
}
public static class ApplicationBuilderExtentions
{
public static RabbitMQPersistentConnection Listener { get; set; }
public static IApplicationBuilder UseRabbitListener(this IApplicationBuilder app)
{
Listener = app.ApplicationServices.GetService<RabbitMQPersistentConnection>();
var life = app.ApplicationServices.GetService<IApplicationLifetime>();
life.ApplicationStarted.Register(OnStarted);
//press Ctrl+C to reproduce if your app runs in Kestrel as a console app
life.ApplicationStopping.Register(OnStopping);
return app;
}
private static void OnStarted()
{
Listener.CreateConsumerChannel();
}
private static void OnStopping()
{
Listener.Disconnect();
}
}
}
Это очень простой способ реализовать RabbitMQ с помощью основного веб-API asp .net. Распределенные сообщения обрабатываются встроенной реализацией RabbitMQ.
Этот исходный код в качестве примера, и вы можете улучшить его с помощью расширенных функциональных возможностей.
Пример консоли отправителя и основного приемника API Asp.net полный проект здесь