ASP.NET CORE Web API与RabbitMQ(AMPQ)中的微服务通信

问题描述 投票:0回答:1

我正在尝试使用asp .net核心Web API实现微服务,并对RabbitMQ进行研发以与每个Web服务进行通信。

关于我的项目,它是一个学习管理系统。当老师需要为班级学生发送批量电子邮件。学习服务api会将电子邮件列表发送给电子邮件服务和抄写员以获取结果。

enter image description here

我搜索了RabbitMQ示例并实现了一些用于创建连接的类。但是为了进行异步化,我认为它应该在Startup.cs中进行初始化。但是我找不到任何样本,因为它在这一点上停留了2天。检查下面的代码并给我一些帮助..

using Newtonsoft.Json;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RabbitMQSender.RabbitMQ
{
    public class RabbitMQConnection
    {
        private static ConnectionFactory _factory;
        private static IConnection _connection;
        private static IModel _channel;

        public void CreateConnection()
        {
            _factory = new ConnectionFactory { HostName = "localhost", UserName = "guest", Password = "guest" };
           // _factory = new ConnectionFactory(){HostName = "172.22.144.236",Port = 5672,UserName = "guest",Password = "guest"};
        }

        public void Close()
        {
            _connection.Close();
        }

        public void ProcessMessages()
        {           

            using (_connection = _factory.CreateConnection())
            {
                using (_channel = _connection.CreateModel())
                {
                    _channel.QueueDeclare(queue: "msgKey", durable: false, exclusive: false, autoDelete: false, arguments: null);

                        var command = new AddUser{
                            FirstName = "Isanka",
                            LastName = "Thalagala",
                            EmailAddress = "[email protected]",
                            Password = "examplePassword"
                        };
                    string message = JsonConvert.SerializeObject(command);
                    var body = Encoding.UTF8.GetBytes(message);

                    _channel.BasicPublish(exchange: "",routingKey: "msgKey",basicProperties: null,body: body);
                   
                   
                   
                }
            }
        }
  
      
    }
    }
rabbitmq amqp asp.net-core-webapi
1个回答
0
投票

在c#中有很多关于RabbitMQ的例子。但是如果你打算实现asp.net核心,并且如果服务需要在api启动时自动运行仍然找不到简单的样本

需要像这样制作startup.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();
        }
    }
}
This is very simple way to implement RabbitMQ with asp .net core web API. Distributed messages handled by built in RabbitMQ implementation.

此源代码作为示例,您可以使用高级功能进行改进示例控制台发件人和Asp.net核心API接收器完整项目here

© www.soinside.com 2019 - 2024. All rights reserved.