rabbitmq - ASP.NET CORE Web API 中的微服务通信与 RabbitMQ (AMPQ)
问题描述
我正在尝试使用 asp .net 核心 Web API 实现微服务,并对 RabbitMQ 进行研发以与每个 Web 服务进行通信。
关于我的项目,这是一个学习管理系统。当老师需要为班级学生发送批量电子邮件时。学习服务 api 会将电子邮件列表发送到电子邮件服务并抄写结果。
我搜索了 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 = "isanka.thalagala@gmail.com",
Password = "examplePassword"
};
string message = JsonConvert.SerializeObject(command);
var body = Encoding.UTF8.GetBytes(message);
_channel.BasicPublish(exchange: "",routingKey: "msgKey",basicProperties: null,body: body);
}
}
}
}
}
解决方案
在c#中有很多关于RabbitMQ的例子。但是如果你要实现asp.net core,如果服务需要在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();
}
}
}
此源代码作为示例,您可以使用高级功能进行改进 示例控制台发送器和 Asp.net 核心 API 接收器完整项目在这里