Failed to send message using MQ - asp.net-core

On my server side I deployed RabbitMq message middleware using docker and it works perfectly. But I combine it with asp.net core, it can't send the message successfully.
package:https://www.nuget.org/packages/RabbitMQ.Client/
I goole some answers:
RabbitMQ adopts the message response mechanism, that is, after the
consumer receives a message, it needs to send a response, and then
RabbitMQ will delete the message from the queue. If the consumer has
an exception during the consumption process, the connection is
disconnected and no response is sent. Then RabbitMQ will redeliver the
message
So I modified my code
//message received event
consumer.Received += (ch, ea) =>
{
var message = Encoding.UTF8.GetString(ea.Body);
Console.WriteLine($"Received the news: {message}");
Console.WriteLine($"received the message[{ea.DeliveryTag}] delay 10s to send receipt");
Thread.Sleep(10000);
//Confirm that the message has been consumed
channel.BasicAck(ea.DeliveryTag, false);
Console.WriteLine($"Receipt sent[{ea.DeliveryTag}]");
};
Still failed to send and no response, please help me, thank you!

I have a demo of sending a message, you may refer to it, it may be helpful.
Controller:
[Route("test")]
public void Index()
{
try
{
var factory = new ConnectionFactory();
factory.VirtualHost = "/";
factory.HostName = "localhost";
factory.Port = 5672;
factory.UserName = "guest";//Default username guest
factory.Password = "guest";//Default password guest
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "test",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
string message = "Hello World!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "test",
basicProperties: null,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
}
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.Write(string.Format("RabbitMQ connection error :{0}\n", ex.ToString()));
}
}
For the sake of convenience, I did not configure the connection information of rabbitmq here. I wrote it directly into the method, you can do it yourself.
Resullt:

Related

ASP.NET CORE combined with RabbitMq message queue

I am using asp.net core to create a project, I want to combine rabbitmq to realize the sending and receiving of message queue.I installed rabbitmq using docker and it runs successfully.But the queue I registered in the project is not displayed on the RabbitMq management interface.
ConnectionFactory factory = new ConnectionFactory
{
UserName = "guest",
Password = "guest",
HostName = "*******"
};
var connection = factory.CreateConnection();
var channel = connection.CreateModel();
channel.QueueDeclare("test", false, false, false, null);
Console.WriteLine("\nRabbitMQ enter exit to exit!");
string input;
do
{
input = Console.ReadLine();
var sendBytes = Encoding.UTF8.GetBytes(input);
channel.BasicPublish("", "test", null, sendBytes);
} while (input.Trim().ToLower()!="exit");
channel.Close();
connection.Close();
The above is my message production code.But there is no display on my RabbitMq dashboard.
enter image description here
You did not specify the port number to connect to and the VirtualHost to connect to, I am not sure if you are caused by this. Do you have a specific error? Or your project can run normally. I have written a demo for sending messages here, you can refer to it, it may be useful to you.
class Program
{
static void Main(string[] args)
{
try
{
var factory = new ConnectionFactory();
factory.VirtualHost = "/";
factory.HostName = "localhost";
factory.Port = 5672;
factory.UserName = "guest";//Default username guest
factory.Password = "guest";//Default password guest
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
string message = "Hello World!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
}
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.Write(string.Format("RabbitMQ connection error :{0}\n", ex.ToString()));
}
}
}
Refer to the official document example:
https://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html
If you run this code and get this error:
Check if your corresponding virtual hosts match, I set "/" here, if you are not, please add your hosts here:
Result:
console:
rabbitmq:

Code to get single message from the queue in RabbitMQ using C#

How to receive single message from the queue in RabbitMQ using C#
I am using the RabbitMQ to maintain my Queue.When I am read my queue messages its shows all massage present in the queue.
I want to retrieve single message as per First come first out criteria.
Please provide me code to get the single message from the queue by using RabbitMQ
var connection = connectionFactory.CreateConnection();
var channel = connection.CreateModel();
// accept only one unack-ed message at a time
// uint prefetchSize, ushort prefetchCount, bool global
channel.BasicQos(0, 1, false);
MessageReceiver messageReceiver = new MessageReceiver(channel);
channel.BasicConsume("viewer_Queues", false, messageReceiver);
//channel.QueueDeclare("viewer_Queues", false, false, false, null);
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume("viewer_Queues", true, consumer);
BasicDeliverEventArgs ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(message + " Received.");
Console.ReadLine();
I think you need something like this, from the website Tutorials in the worker Queues Section:
`using System;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Threading;
class Worker
{
public static void Main()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "task_queue",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
Console.WriteLine(" [*] Waiting for messages.");
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
int dots = message.Split('.').Length - 1;
Thread.Sleep(dots * 1000);
Console.WriteLine(" [x] Done");
channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
};
channel.BasicConsume(queue: "task_queue",
autoAck: false,
consumer: consumer);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}`
the prefetch argument is important if you want to get only one message at a time you can read about it in the official website https://www.rabbitmq.com/

RabbitMQ queue declare never ends

I'm just trying to make a simple test for RabbitMQ, and I have Erlang installed as well as RabbitMQ running.
My receiver:
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
Consumer consumer = new DefaultConsumer(channel) {
#Override
public void handleDelivery(String consumerTag, Envelope envelope,
BasicProperties properties, byte[] body) throws IOException
{
// TODO Auto-generated method stub
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
}
It never prints out the first sysout, because it gets stuck declaring the queue on "channel.queueDeclare" line.
Rabbit log says it is accepting AMQP connection and user guest gets authenticated and granted access to vhost.
Any help would be appreciated.
I just copied/pasted your code with no problems...
[*] Waiting for messages. To exit press CTRL+C
[x] Received 'foo'
I suggest you enable the management plugin and explore the admin UI.
Why did you add the spring-amqp spring-rabbitmq tags since this question has nothing to do with Spring and you are using the native client directly?

NServiceBus MSMQ, How to Stop message transfer to Error Queue

I am using NServiceBus for a proof of concept. I am using it with MSMQ. I Have a Web Application which send a message. This message will be handled by a subscriber or message handler. When i shutdown the message handler, message will be send to Error Queue after few retries.
I don't want to send it to error queue, i want to keep message in Input queue as long as Handler is again online and process this message automatically from input queue. If message can not be processed from handler due to any error, it must transfer message to error queue.
Here is my configuration in MVC application Global.asax
private void ConfigureServiceBus()
{
var endpointConfiguration = new EndpointConfiguration("Samples.Mvc.Endpoint");
endpointConfiguration.UseSerialization<JsonSerializer>();
endpointConfiguration.UsePersistence<InMemoryPersistence>();
endpointConfiguration.UseTransport<MsmqTransport>();
endpointConfiguration.SendFailedMessagesTo("error");
endpointConfiguration.AuditProcessedMessagesTo("audit");
var recoverability = endpointConfiguration.Recoverability();
recoverability.Delayed(
delayed =>
{
delayed.NumberOfRetries(2);
delayed.TimeIncrease(TimeSpan.FromSeconds(2));
});
endpointConfiguration.EnableInstallers();
endpoint = Endpoint.Start(endpointConfiguration).GetAwaiter().GetResult();
//var endpointInstance = Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
var mvcContainerBuilder = new ContainerBuilder();
mvcContainerBuilder.RegisterInstance(endpoint);
// Register MVC controllers.
mvcContainerBuilder.RegisterControllers(typeof(MvcApplication).Assembly);
var mvcContainer = mvcContainerBuilder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(mvcContainer));
}
This is the part in Controller where i send message to endpoint.
[HttpPost]
public async Task<ActionResult> Contact(ContactModel c)
{
if (ModelState.IsValid)
{
try
{
var message = new ContactMessage()
{
Comment = c.Comment,
Email = c.Email,
FirstName = c.FirstName,
LastName = c.LastName,
TransectionId = Guid.NewGuid()
};
await endpoint.Send("Samples.Mvc.Endpoint", message).ConfigureAwait(false);
return View("Success");
}
catch (Exception ex)
{
return View("Error");
}
}
return View();
}
My goal is to keep unhandled messages in input queue as long as message handler is not back on work. currently if message handler is down, it send messages after retries to Error Queue.
I am using NServiceBus 6.x
thanks in advance

Need help in creating RabbitMQ consumer as windows service?

This code works fine with console application but it doesnt work with Windows service application.
//code to receive message from queue
public void ReceiveMessage()
{
const string EXCHANGE_NAME = "EXCHANGE3";
ConnectionFactory factory = new ConnectionFactory();
//Rabbit MQ connection
using (IConnection connection = factory.CreateConnection())
{
using (IModel channel = connection.CreateModel())
{
channel.QueueDeclare("task_queue", true, false, false, null);
channel.BasicQos(0, 1, false);
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume("task_queue", false, consumer);
//Waiting in loop to get message
while (true)
{
var ea =
(BasicDeliverEventArgs)consumer.Queue.Dequeue();
Object message = Desserialize(ea.Body);
//Acknowledge one or more delivered message
channel.BasicAck(ea.DeliveryTag, false);
}
}
}
}