Reputation: 628
I am writing an ASP.NET Core MVC app with RabbitMQ. I am able to implement pub/sub patterns successfully. However, I am facing an issue to show subscribe message on the App.
Connection method on HomeController
:
[HttpPost]
public IActionResult Index(string serverName, string userName, string password, string port)
{
RabbitMq rabbitMq = new RabbitMq();
var pubConnection = rabbitMq.CreateConnection(serverName, userName, password, port);
if (!pubConnection.IsOpen)
{
ViewBag.NotConnected = "Not Connected. Try Again.";
return View();
}
var subConnection = rabbitMq.CreateConnection(serverName, userName, password, port);
MyClient myClient = new MyClient();
myClient.CreatePublisher(pubConnection);
myClient.CreateSubscriber(subConnection);
return RedirectToAction(actionName: "Index", controllerName: "MyClientXYZ", routeValues: null);
}
Subscriber method on MyClient
class :
public void CreateSubscriber(IConnection pubSubConnection)
{
var channel = pubSubConnection.CreateModel();
channel.ExchangeDeclare("MyExchange", ExchangeType.Fanout, durable: true, true);
channel.ExchangeBind("MyExchange", "ClientExchange", "#", null);
var slotQueueName = channel.QueueDeclare("my queue", true, autoDelete: true).QueueName;
channel.QueueBind(slotQueueName, "MyExchange", routingKey: "");
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] {0}", message);
};
channel.BasicConsume(queue: slotQueueName,
autoAck: true,
consumer: consumer);
}
I am able to print subscriber messages on the console. But I need to show this message on the UI (View, any JS popup, etc.) I tried many ways like set subscribe message into TempData["subMessage"], redirectToAction(), open JS popup to show subscriber message. But, I couldn't do.
I just want to show the subscriber message on the UI when the callback method executes.
Upvotes: 0
Views: 2197
Reputation: 686
This is not right. RabbitMQ connections, and consumers, are long lived entities; not something ephemeral that you initiate in a controller action.
The short answer is to use a framework on top of RabbitMQ. Here's two good ones to consider:
The long answer is to roll your own RabbitMQ infrastructure. You do this if you are an expert and have some special need. In that case, maybe start here:
The other answer is to completely re-evaluate what you are trying to achieve.
Good luck.
Upvotes: 2