RabbitMQ in .NET Core

docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.9-management
using RabbitMQ.Client;
using System;
using System.Text;
namespace RabbitMQSender
{
class Sender
{
static void Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
Console.WriteLine("Enter command 'exit' to stop sending meesages");
string message = string.Empty;
do
{
SendMessage(connection, message);
Console.Write("Enter your next message:");
message = Console.ReadLine();
} while (!message.Equals("exit", StringComparison.OrdinalIgnoreCase));
}
}
private static void SendMessage(IConnection connection, string message)
{
if (string.IsNullOrEmpty(message))
return;
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var body = Encoding.UTF8.GetBytes(message);var properties = channel.CreateBasicProperties();
properties.Persistent = true;
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: properties,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
}
}
}
}
var properties = channel.CreateBasicProperties();properties.Persistent = true;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

using System;
using System.Text;
namespace RabbitMQReceiver
{
class Receiver
{
public static void Main()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
};
channel.BasicConsume(queue: "hello",
autoAck: false,//making it false as we are doing it manually above
consumer: consumer);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
}
}
channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Binod Mahto

Binod Mahto

Solution Architect & Full Stack Developer. Passionate about Software designing & development and Learning Technologies and Love to share what I learn.