订阅RabbitMQ扇出交换后微服务没有响应
我的.net core3.1 web应用程序有4种微服务(MasterMS、PartyMS、ProductMS、PurchaseMS) 并使用Rabbitmq作为消息代理 在一个特定场景中,MasterMS向Rabbitmq exchange(xAlexa)发布一个事件(在公司表中插入/更新),并从该事件分散到所有订阅MS(PartyMS、ProductMS)的相应队列 PartyMS从CompanyEventPartyMS队列获取事件,ProductMS从CompanyEventProductMS队列获取事件。因此,双方和产品都更新了各自的公司表,一切都是同步和完美的。顺便说一句,PurchaseMS没有订阅,因此不受打扰 现在真正的问题来了。。订阅MSs(消费者)在请求其网页时不响应。PartyMS和ProductMS网页抛出SocketException,而非订户的PurchaseMS工作正常。现在,如果我注释掉PartyMS订阅的行,它将重新开始工作,尽管它不再获得CompanyEvent并失去同步。 有朋友吗 SocketException:无法建立连接,因为目标计算机主动拒绝连接。 System.Net.Http.ConnectHelper.ConnectAsync(字符串主机、int端口、CancellationToken CancellationToken)订阅RabbitMQ扇出交换后微服务没有响应,rabbitmq,microservices,asp.net-core-3.1,rabbitmq-exchange,Rabbitmq,Microservices,Asp.net Core 3.1,Rabbitmq Exchange,我的.net core3.1 web应用程序有4种微服务(MasterMS、PartyMS、ProductMS、PurchaseMS) 并使用Rabbitmq作为消息代理 在一个特定场景中,MasterMS向Rabbitmq exchange(xAlexa)发布一个事件(在公司表中插入/更新),并从该事件分散到所有订阅MS(PartyMS、ProductMS)的相应队列 PartyMS从CompanyEventPartyMS队列获取事件,ProductMS从CompanyEventProduct
公共无效发布(T@event),其中T:event
{
var factory=new ConnectionFactory(){HostName=“localhost”};
使用(var connection=factory.CreateConnection())
使用(var channel=connection.CreateModel())
{
channel.ExchangeClare(交换:“xAlexa”,类型:ExchangeType.Fanout);
var message=JsonConvert.SerializeObject(@event);
var body=Encoding.UTF8.GetBytes(消息);
var eventName=@event.GetType().Name;
channel.BasicPublish(交换:“xAlexa”,
routingKey:eventName,//string.Empty,
基本属性:null,
身体:身体),;
}
}
StartBasicConsume
private void StartBasicConsume<T>() where T : Event
{
var factory = new ConnectionFactory()
{
HostName = "localhost",
DispatchConsumersAsync = true
};
var connection = factory.CreateConnection();
var channel = connection.CreateModel();
var eventName = typeof(T).Name;
var msName = typeof(T).FullName;
string[] str = { };
str = msName.Split('.');
eventName += str[1];
channel.ExchangeDeclare(exchange: "xAlexa",
type: ExchangeType.Fanout);
channel.QueueDeclare(eventName, true, false, false, null); //channel.QueueDeclare().QueueName;
channel.QueueBind(queue: eventName,
exchange: "xAlexa",
routingKey: string.Empty);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += Consumer_Received;
channel.BasicConsume(eventName, true, consumer);
Console.WriteLine("Consumer Started");
Console.ReadLine();
}
private async Task Consumer_Received(object sender, BasicDeliverEventArgs e)
{
var eventName = e.RoutingKey;
var body = e.Body.ToArray();
//var body = e.Body.Span;
var message = Encoding.UTF8.GetString(body);
//var message = Encoding.UTF8.GetString(e.Body);
Console.WriteLine(message);
try
{
await ProcessEvent(eventName, message).ConfigureAwait(false);
}
catch (Exception ex)
{
}
}
private void StartBasicConsume(),其中T:Event
{
var factory=新连接工厂()
{
HostName=“localhost”,
DispatchConsumersAsync=true
};
var connection=factory.CreateConnection();
var channel=connection.CreateModel();
var eventName=typeof(T).Name;
var msName=typeof(T).FullName;
字符串[]str={};
str=msName.Split('.');
eventName+=str[1];
channel.ExchangeClare(交换:“xAlexa”,
类型:ExchangeType.Fanout);
channel.QueueDeclare(eventName,true,false,false,null);//channel.QueueDeclare().QueueName;
channel.QueueBind(队列:eventName,
交换:“xAlexa”,
routingKey:string.Empty);
var consumer=新的AsyncEventingBasicConsumer(通道);
consumer.Received+=consumer\u Received;
channel.BasicConsume(eventName、true、consumer);
Console.WriteLine(“消费者启动”);
Console.ReadLine();
}
接收到专用异步任务使用者(对象发送方,BasicDeliverEventArgs e)
{
var eventName=e.RoutingKey;
var body=e.body.ToArray();
//var body=e.body.Span;
var message=Encoding.UTF8.GetString(body);
//var message=Encoding.UTF8.GetString(e.Body);
控制台写入线(消息);
尝试
{
等待ProcessEvent(eventName,message).ConfigureAwait(false);
}
捕获(例外情况除外)
{
}
}
MVC应用程序对ProductsMS Api的调用(如果订阅,则调用失败;如果未订阅CompanyEvent,则调用有效!)
公共类ProductService:IPProductService
{
私有只读HttpClient _apiCLient;
公共产品服务(HttpClient apiCLient)
{
_apiCLient=apiCLient;
}
公共异步任务GetProducts()
{
var uri=”https://localhost:5005/api/ProductApi";
List userList=新列表();
HttpResponseMessage response=await _apiCLient.GetAsync(uri);
if(响应。IsSuccessStatusCode)
{
var readTask=response.Content.ReadAsStringAsync().Result;
userList=JsonConvert.DeserializeObject(readTask);
}
返回用户列表;
}
}
请在下面找到ProductsMS Api Startup.cs:
namespace Alexa.ProductMS.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
var connectionString = Configuration["DbContextSettings:ConnectionString"];
var dbPassword = Configuration["DbContextSettings:DbPassword"];
var builder = new NpgsqlConnectionStringBuilder(connectionString)
{
Password = dbPassword
};
services.AddDbContext<ProductsDBContext>(opts => opts.UseNpgsql(builder.ConnectionString));
services.AddMediatR(typeof(Startup));
RegisterServices(services);
}
private void RegisterServices(IServiceCollection services)
{
DependencyContainer.RegisterServices(services);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
ConfigureEventBus(app); //WORKS IF COMMENTED; FAILS OTHERWISE <---
}
private void ConfigureEventBus(IApplicationBuilder app)
{
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<CompanyEvent, CompanyEventHandler>();
eventBus.Subscribe<PartyEvent, PartyEventHandler>();
}
}
}
名称空间Alexa.ProductMS.Api
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
public void配置服务(IServiceCollection服务)
{
services.AddControllers();
var connectionString=Configuration[“DbContextSettings:connectionString”];
var dbPassword=Configuration[“DbContextSettings:dbPassword”];
var builder=新的NpgsqlConnectionStringBuilder(connectionString)
{
Password=dbPassword
};
services.AddDbContext(opts=>opts.UseNpgsql(builder.ConnectionString));
AddMediatR(类型(启动));
注册服务(服务);
}
专用无效注册表服务(IServiceCollection服务)
{
DependencyContainer.RegisterServices(服务);
}
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
public class ProductService:IProductService
{
private readonly HttpClient _apiCLient;
public ProductService(HttpClient apiCLient)
{
_apiCLient = apiCLient;
}
public async Task<List<Product>> GetProducts()
{
var uri = "https://localhost:5005/api/ProductApi";
List<Product> userList = new List<Product>();
HttpResponseMessage response = await _apiCLient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var readTask = response.Content.ReadAsStringAsync().Result;
userList = JsonConvert.DeserializeObject<List<Product>>(readTask);
}
return userList;
}
}
namespace Alexa.ProductMS.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
var connectionString = Configuration["DbContextSettings:ConnectionString"];
var dbPassword = Configuration["DbContextSettings:DbPassword"];
var builder = new NpgsqlConnectionStringBuilder(connectionString)
{
Password = dbPassword
};
services.AddDbContext<ProductsDBContext>(opts => opts.UseNpgsql(builder.ConnectionString));
services.AddMediatR(typeof(Startup));
RegisterServices(services);
}
private void RegisterServices(IServiceCollection services)
{
DependencyContainer.RegisterServices(services);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
ConfigureEventBus(app); //WORKS IF COMMENTED; FAILS OTHERWISE <---
}
private void ConfigureEventBus(IApplicationBuilder app)
{
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<CompanyEvent, CompanyEventHandler>();
eventBus.Subscribe<PartyEvent, PartyEventHandler>();
}
}
}