gpt4 book ai didi

c# - 使用 .NET Core 注册 RabbitMQ 使用者?

转载 作者:行者123 更新时间:2023-12-04 13:45:28 29 4
gpt4 key购买 nike

我正在尝试使用消息队列 (RabbitMQ) 在基于微服务的架构中处理请求授权。

根据这些 instructions,我已经将接收器和发送器配置为 .NET Core 中的控制台应用程序.但是,在实际示例中使用它时,我的应用程序接收项目不会作为使用者收集消息。

我假设我必须在 Startup.cs 中注册消费者,但我似乎无法让这个工作。

我的消费者/响应者代码:

public class RabbitMqHandler 
{
private readonly IJWTFactory _jwtFactory;

public RabbitMqHandler(IJWTFactory jWTFactory)
{
_jwtFactory = jWTFactory;

}

public void Register()
{
var mqFactory = new ConnectionFactory() { HostName = "localhost" };

using (var connection = mqFactory.CreateConnection())
{
Console.WriteLine("Listening on Rabbit MQ");
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "Authorize", durable: false, exclusive: false, autoDelete: false, arguments: null);

var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var jwtToken = Encoding.UTF8.GetString(body);

Console.WriteLine("Rceived Message");

var validatedToken = _jwtFactory.ValidateTokenSignature(jwtToken);

SendResponse(validatedToken);
};
channel.BasicConsume(queue: "Authorize", autoAck: true, consumer: consumer);
}
}
}

public void Deregister()
{

}
Startup.cs注册
.AddSingleton()

编辑:我添加了一些额外的监听代码,这肯定是在启动时运行,但 RabbitMQ 没有将应用程序显示为消费者或 channel :
public static class ApplicationBuilderExtentions
{
public static RabbitMqHandler Listener { get; set; }

public static IApplicationBuilder UseRabbitListener(this IApplicationBuilder app)
{
Listener = app.ApplicationServices.GetService<RabbitMqHandler>();

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.Register();
}

private static void OnStopping()
{
Listener.Deregister();
}
}

总结一下:
  • 如何在 .NET Core 中正确配置使用者以使用消息?
  • 期望 Message Queue 管理请求/响应风格的通信是错误的吗?
  • 我应该只使用 API 调用来验证和授权用户吗?
  • 最佳答案

    答案由 @Evk 提供(在评论中):

    "using is designed to dispose things, it calls Dispose when you reach the end of the using block. BasicConsume is not a blocking call, so it starts consumption and returns immediately.
    Right after that the end of the using blocks is reached for both channel and connection, disposing them (and disposing them is the same as closing)."


    我想添加以下内容:
    如果删除 using 很容易带来所需的结果,您可以快速尝试。更改以下代码行:
    using (var connection = mqFactory.CreateConnection())
    到:
    var connection = mqFactory.CreateConnection();
    这将立即奏效。但请注意,它也会删除适当的处理 - 所以你需要添加 - here是 Microsoft 的一篇文章,描述了 IDisposable要正确执行。

    关于c# - 使用 .NET Core 注册 RabbitMQ 使用者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49122130/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com