Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 34 additions & 36 deletions RabbitMQ.DirectExchange/Producer/Program.cs
Original file line number Diff line number Diff line change
@@ -1,51 +1,49 @@
using RabbitMQ.Client;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RabbitMQ.Client;

namespace Producer
namespace RabbitMQ.DirectExchange.Producer
{
class Program
{
private const string QueueName = "km23_lab_queue";

static void Main(string[] args)
{
Task.Run(CreateTask(12000, "error"));
Task.Run(CreateTask(10000, "info"));
Task.Run(CreateTask(8000, "warning"));
var factory = new ConnectionFactory
{
HostName = "localhost"
};

Console.ReadKey();
}
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.QueueDeclare(
queue: QueueName,
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);

static Func<Task> CreateTask(int timeToSleepTo, string routingKey)
{
return () =>
Console.WriteLine("Producer started. Press Ctrl+C to stop.");

int counter = 1;

while (true)
{
var counter = 0;
do
{
int timeToSleep = new Random().Next(1000, timeToSleepTo);
Thread.Sleep(timeToSleep);

var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.ExchangeDeclare(exchange: "direct_logs", type: ExchangeType.Direct);

string message = $"Message type [{routingKey}] from publisher N {counter}";

var body = Encoding.UTF8.GetBytes(message);

channel.BasicPublish(exchange: "direct_logs",
routingKey: routingKey,
basicProperties: null,
body: body);

Console.WriteLine($"Message type [{routingKey}] is sent into Direct Exchange [N:{counter++}]");
}
} while (true);
};
string message = $"[{DateTime.Now:HH:mm:ss}] KM-23 lab message #{counter}";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(
exchange: "",
routingKey: QueueName,
basicProperties: null,
body: body);

Console.WriteLine($"[x] Sent: {message}");

counter++;
Thread.Sleep(2000);
}
}
}
}