ASP.NET中的EasyNetQ(AMQP)单个应用程序连接?

时间:2018-10-29 14:19:43

标签: asp.net easynetq

社区:

我正在努力找出如何使用.NET Core 2.1在ASP.NET中创建一个与我的ASP.NET应用程序生命周期一起使用的AMQP连接。经过研究,我发现很多关于在整个应用程序中使用单个AMQP连接的参考,因为它们创建起来既昂贵又缓慢,因此我开始使用DI创建连接,但是我的方法似乎有缺陷,我似乎无法识别我需要作为单例添加的接口...

public void ConfigureServices(IServiceCollection services)
        {
            var sqlConnectionStringBuilder = new SqlConnectionStringBuilder(Configuration.GetConnectionString("DefaultConnection"));
            var envSQL = Environment.GetEnvironmentVariable("ASPNETCORE_SQL_SERVER");
            if (envSQL != null)
                sqlConnectionStringBuilder.DataSource = envSQL;

            services.AddSingleton<IMessageBusService, MessageBusService>();
            services.AddSingleton<EasyNetQ.IAdvancedBus, RabbitAdvancedBus>();
            services.AddSingleton<EasyNetQ.IConnectionFactory, ConnectionFactoryWrapper>();

            services.AddMvc();

        }

添加上述接口可以工作,但是我收到有关ConnectionConfiguration服务无法定位的错误。这是正确的方向吗?还是在ASP.NET Core中建立EasyNetQ连接后,是否有更合适的方法来创建单个应用程序?

1 个答案:

答案 0 :(得分:0)

您可以在 .net核心中使用 AutoSubcriber 并使用示例代码here

将连接添加到appsettings.json

"MessageBroker": {
"ConnectionString": "host=localhost"
}

然后在配置服务中添加IBus

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IBus>(RabbitHutch.CreateBus(Configuration["MessageBroker:ConnectionString"]));
        services.AddSingleton(RabbitHutch.CreateBus(Configuration["MessageBroker:ConnectionString"]));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

添加类AppBuilderExtension并为自动订户使用扩展方法

public static class AppBuilderExtension
{
    public static IApplicationBuilder UseSubscribe(this IApplicationBuilder appBuilder, string subscriptionIdPrefix, Assembly assembly)
    {
        var services = appBuilder.ApplicationServices.CreateScope().ServiceProvider;

        var lifeTime = services.GetService<IApplicationLifetime>();
        var Bus = services.GetService<IBus>();
        lifeTime.ApplicationStarted.Register(() =>
        {
            var subscriber = new AutoSubscriber(Bus, subscriptionIdPrefix);
            subscriber.Subscribe(assembly);
            subscriber.SubscribeAsync(assembly);
        });

        lifeTime.ApplicationStopped.Register(() => Bus.Dispose());

        return appBuilder;
    }
}

在“配置”中添加UseSubscribe

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
        app.UseSubscribe("ClientMessageService", Assembly.GetExecutingAssembly());

        app.UseHttpsRedirection();
        app.UseMvc();
    }

然后创建Producers控制器

[Route("api/[controller]")]
[ApiController]
public class ProducersController : ControllerBase
{
    private readonly IBus _bus;

    public ProducersController(IBus bus)
    {
        _bus = bus;
    }
    [HttpGet]
    [Route("Send")]
    public JsonResult Send()
    {

        _bus.Publish(new TextMessage { Text = "Send Message from the Producer" });

        return new JsonResult("");
    }


}

然后创建Consumers控制器

[Route("api/[controller]")]
[ApiController]
public class ConsumersController : ControllerBase, IConsume<TextMessage>
{
    [HttpGet]
    [Route("Receive")]
    public JsonResult Receive()
    {
        using (var bus = RabbitHutch.CreateBus("host=localhost"))
        {
            bus.Subscribe<TextMessage>("test", HandleTextMessage);
        }
        return new JsonResult("");
    }


    private static void HandleTextMessage(TextMessage textMessage)
    {
        var item = textMessage.Text;
    }

    public void Consume(TextMessage message)
    {
        // code receive message
    }
}