Merge pull request 'danilov_vladimir_lab_4 is ready' (#435) from danilov_vladimir_lab_4 into main

Reviewed-on: #435
This commit was merged in pull request #435.
This commit is contained in:
2025-12-08 23:09:21 +04:00
33 changed files with 956 additions and 0 deletions

44
danilov_vladimir_lab_4/.gitignore vendored Normal file
View File

@@ -0,0 +1,44 @@
# === Системные файлы Windows ===
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
# === Конфигурации IDE (Visual Studio / VS Code) ===
.vs/
.vscode/
.idea/
# === Файлы сборки .NET ===
bin/
obj/
app.publish/
*.exe
*.dll
*.pdb
*.cache
*.log
# === Docker и временные файлы ===
**/.dockerignore
*.tar
*.bak
# === Папки публикации и артефакты ===
/app/
/publish/
/out/
# === Временные файлы и резервные копии ===
*.tmp
*.swp
*.user
*.suo
# === Исключаем всё ненужное, кроме данных ===
!data/
!result/
# === Прочее ===
*.dbmdl
*.jfm

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,37 @@
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
Console.WriteLine("Lesson 1 Consumer started");
var factory = new ConnectionFactory()
{
HostName = "localhost",
UserName = "admin",
Password = "admin"
};
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
Console.WriteLine(" [*] Waiting for messages. To exit press CTRL+C");
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine($" [x] Received '{message}' at {DateTime.Now:HH:mm:ss}");
};
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
Console.ReadLine();

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,44 @@
using RabbitMQ.Client;
using System.Text;
Console.WriteLine("Lesson 1 Producer started");
var factory = new ConnectionFactory()
{
HostName = "localhost",
UserName = "admin",
Password = "admin"
};
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
int messageCount = 1;
while (true)
{
string message = $"Hello World! #{messageCount}";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine($" [x] Sent '{message}'");
messageCount++;
Console.WriteLine("Press 'q' to quit or any other key to send another message...");
var key = Console.ReadKey();
if (key.KeyChar == 'q') break;
Console.WriteLine();
}
Console.WriteLine("Producer stopped.");

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,48 @@
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
Console.WriteLine("Lesson 2 Consumer - Work Queue");
var factory = new ConnectionFactory()
{
HostName = "localhost",
UserName = "admin",
Password = "admin"
};
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.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine($" [x] Received '{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();

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,48 @@
using RabbitMQ.Client;
using System.Text;
Console.WriteLine("Lesson 2 Producer - Work Queue");
var factory = new ConnectionFactory()
{
HostName = "localhost",
UserName = "admin",
Password = "admin"
};
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.QueueDeclare(queue: "task_queue",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
var messages = new[]
{
"First message.",
"Second message..",
"Third message...",
"Fourth message....",
"Fifth message....."
};
foreach (var message in messages)
{
var body = Encoding.UTF8.GetBytes(message);
var properties = channel.CreateBasicProperties();
properties.Persistent = true;
channel.BasicPublish(exchange: "",
routingKey: "task_queue",
basicProperties: properties,
body: body);
Console.WriteLine($" [x] Sent '{message}'");
Thread.Sleep(1000);
}
Console.WriteLine("Press [enter] to exit.");
Console.ReadLine();

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,74 @@
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
Console.WriteLine("Lesson 3 Consumer - Logs System");
var factory = new ConnectionFactory()
{
HostName = "localhost",
UserName = "admin",
Password = "admin"
};
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.ExchangeDeclare(exchange: "logs", type: ExchangeType.Fanout);
var queueName = $"logs_consumer_{Guid.NewGuid().ToString()[..8]}";
channel.QueueDeclare(queue: queueName,
durable: false,
exclusive: true,
autoDelete: true,
arguments: null);
channel.QueueBind(queue: queueName,
exchange: "logs",
routingKey: "");
Console.WriteLine($" [*] Consumer {queueName} started.");
Console.WriteLine($" [*] Waiting for logs. Press CTRL+C to exit.");
Console.WriteLine();
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var logEntry = Encoding.UTF8.GetString(body);
var originalColor = Console.ForegroundColor;
if (logEntry.Contains("[ERROR]"))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($" [!] {logEntry}");
}
else if (logEntry.Contains("[WARN]"))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($" [?] {logEntry}");
}
else if (logEntry.Contains("[INFO]"))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($" [i] {logEntry}");
}
else if (logEntry.Contains("[DEBUG]"))
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine($" [d] {logEntry}");
}
else
{
Console.WriteLine($" [>] {logEntry}");
}
Console.ForegroundColor = originalColor;
};
channel.BasicConsume(queue: queueName,
autoAck: true,
consumer: consumer);
Console.ReadLine();

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,101 @@
using RabbitMQ.Client;
using System.Text;
Console.WriteLine("Lesson 3 Producer - Publish/Subscribe (Logs System)");
var factory = new ConnectionFactory()
{
HostName = "localhost",
UserName = "admin",
Password = "admin"
};
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.ExchangeDeclare(exchange: "logs", type: ExchangeType.Fanout);
var random = new Random();
var logLevels = new[] { "INFO", "WARN", "ERROR", "DEBUG" };
var logComponents = new[] { "AuthService", "Database", "PaymentGateway", "UserService", "EmailService" };
var logMessages = new[]
{
"User authentication successful",
"Database connection established",
"Payment processing started",
"User profile updated",
"Email sent successfully",
"Failed to connect to database",
"Invalid credentials provided",
"Payment declined - insufficient funds",
"Session expired",
"Cache cleared successfully",
"High memory usage detected",
"Backup completed",
"Security alert: multiple failed login attempts",
"API rate limit exceeded"
};
int messageCount = 1;
Console.WriteLine("Log Producer started. Press:");
Console.WriteLine(" - 'q' to quit");
Console.WriteLine(" - 'a' to auto-generate logs every 2 seconds");
Console.WriteLine(" - Any other key to send one log message");
Console.WriteLine();
while (true)
{
Console.WriteLine("Choose mode (q/a/enter): ");
var key = Console.ReadKey();
Console.WriteLine();
if (key.KeyChar == 'q') break;
if (key.KeyChar == 'a')
{
Console.WriteLine("Auto-generating logs every 2 seconds. Press any key to stop...");
while (!Console.KeyAvailable)
{
SendRandomLog();
Thread.Sleep(2000);
}
Console.ReadKey();
continue;
}
SendRandomLog();
}
void SendRandomLog()
{
var logLevel = logLevels[random.Next(logLevels.Length)];
var component = logComponents[random.Next(logComponents.Length)];
var message = logMessages[random.Next(logMessages.Length)];
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
var logEntry = $"{timestamp} [{logLevel}] {component}: {message} (#{messageCount})";
var body = Encoding.UTF8.GetBytes(logEntry);
channel.BasicPublish(exchange: "logs",
routingKey: "",
basicProperties: null,
body: body);
var originalColor = Console.ForegroundColor;
Console.ForegroundColor = logLevel switch
{
"ERROR" => ConsoleColor.Red,
"WARN" => ConsoleColor.Yellow,
"INFO" => ConsoleColor.Green,
"DEBUG" => ConsoleColor.Blue,
_ => ConsoleColor.White
};
Console.WriteLine($" [x] Sent: {logEntry}");
Console.ForegroundColor = originalColor;
messageCount++;
}
Console.WriteLine("Log Producer stopped.");

View File

@@ -0,0 +1,11 @@
version: "3.9"
services:
rabbitmq:
image: rabbitmq:3-management
container_name: rabbitmq-tutorial
ports:
- "5672:5672"
- "15672:15672"
environment:
RABBITMQ_DEFAULT_USER: admin
RABBITMQ_DEFAULT_PASS: admin

View File

@@ -0,0 +1,72 @@
# Лабораторная работа №4 - Работа с брокером сообщений
**Цель**: изучение проектирования приложений при помощи брокера сообщений.
**Задачи**:
1. Установить брокер сообщений RabbitMQ.
2. Пройти уроки 1, 2 и 3 из [RabbitMQ Tutorials](https://www.rabbitmq.com/getstarted.html) на любом языке программирования.
3. Продемонстрировать работу брокера сообщений.
## Как запустить лабораторную работу
#### Предварительные требования
- Установлен **Docker**
- Установлен **Docker Compose**
#### Выполните команду:
```'docker compose up --build'```
## Технологии
- Docker
- .NET 9 (C#)
## Прохождение туториалов
1. "Hello World!"
![tutorial_1](./images/tutorial_1.png)
2. Work Queues
![tutorial_2](./images/tutorial_2.png)
3. Publish/Subscribe
![tutorial_3](./images/tutorial_3.png)
## Предметная область
В качестве предметной области была выбрана система поддержки клиентов (ticketing system).
Поэтому сообщения моделируют операции по созданию новых заявок в системе поддержки:
- создание нового тикета поддержки;
- автоматическая нумерация тикетов;
- уведомление о новых заявках.
Затем были разработаны три приложения.
### Publisher
Генерирует каждую секунду новое событие о создании тикета поддержки и публикует его в обменник RabbitMQ.
### Consumer slow
Моделирует медленного агента поддержки, который обрабатывает тикеты с задержкой в 3 секунды.
### Consumer fast
Моделирует быстрого агента поддержки с мгновенной обработкой тикетов.
## Работа приложений
### Запущено по одному экземпляру:
![test1_1](./images/test1_1.png)
![test1_2](./images/test1_2.png)
![test1_3](./images/test1_3.png)
После просмотра графиков можно увидеть, что быстрый обработчик успешно справляется с нагрузкой.
А вот медленный обработчик уже нет, т.к. в "consumer_slow_queue" накапливаются сообщения, причем достаточно быстро.
### Запущено 3 экземпляра Consumer slow:
![test2_1](./images/test2_1.png)
![test2_2](./images/test2_2.png)
Тут можно увидеть, что суммарная производительность 3 медленных обработчиков все же позволяет решить проблему с накоплением сообщений.
## Ссылка
[[Ссылка на видео](https://disk.yandex.ru/d/BAxsFhGOHv8w-A)]

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,11 @@
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src
COPY *.csproj .
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app
FROM mcr.microsoft.com/dotnet/runtime:9.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "ConsumerFast.dll"]

View File

@@ -0,0 +1,85 @@
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
Console.WriteLine("Fast consumer started...");
await WaitForRabbitMQ();
var factory = new ConnectionFactory()
{
HostName = "rabbit",
UserName = "admin",
Password = "admin",
AutomaticRecoveryEnabled = true
};
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.ExchangeDeclare(exchange: "support_events", type: "fanout", durable: true);
// Другая очередь
channel.QueueDeclare(
queue: "consumer_fast_queue",
durable: true,
exclusive: false,
autoDelete: false
);
channel.QueueBind("consumer_fast_queue", "support_events", "");
// Ограничиваем prefetch для честной обработки
channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (s, e) =>
{
var msg = Encoding.UTF8.GetString(e.Body.Span);
Console.WriteLine($"[FAST][{DateTime.Now:HH:mm:ss}] Received: {msg}");
// Мгновенная обработка (без задержки)
Console.WriteLine($"[FAST][{DateTime.Now:HH:mm:ss}] ✅ Processed: {msg}");
channel.BasicAck(e.DeliveryTag, false);
};
channel.BasicConsume("consumer_fast_queue", autoAck: false, consumer);
Console.WriteLine("Fast consumer is waiting for messages...");
// Бесконечное ожидание для контейнера
await Task.Delay(Timeout.Infinite);
async Task WaitForRabbitMQ()
{
const int maxRetries = 30;
const int delayMs = 2000;
for (int i = 0; i < maxRetries; i++)
{
try
{
var testFactory = new ConnectionFactory()
{
HostName = "rabbit",
UserName = "admin",
Password = "admin",
RequestedConnectionTimeout = TimeSpan.FromSeconds(2)
};
using var testConnection = testFactory.CreateConnection();
using var testChannel = testConnection.CreateModel();
Console.WriteLine("Fast consumer connected to RabbitMQ!");
return;
}
catch (Exception)
{
Console.WriteLine($"Fast consumer waiting for RabbitMQ... Attempt {i + 1}/{maxRetries}");
if (i == maxRetries - 1) throw;
await Task.Delay(delayMs);
}
}
}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,11 @@
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src
COPY *.csproj .
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app
FROM mcr.microsoft.com/dotnet/runtime:9.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet","ConsumerSlow.dll"]

View File

@@ -0,0 +1,85 @@
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
Console.WriteLine("Slow consumer started...");
await WaitForRabbitMQ();
var factory = new ConnectionFactory()
{
HostName = "rabbit",
UserName = "admin",
Password = "admin",
AutomaticRecoveryEnabled = true
};
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.ExchangeDeclare(exchange: "support_events", type: "fanout", durable: true);
channel.QueueDeclare(
queue: "consumer_slow_queue",
durable: true,
exclusive: false,
autoDelete: false
);
channel.QueueBind("consumer_slow_queue", "support_events", "");
// Ограничиваем prefetch для честной обработки
channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += async (s, e) =>
{
var msg = Encoding.UTF8.GetString(e.Body.Span);
Console.WriteLine($"[SLOW][{DateTime.Now:HH:mm:ss}] Received: {msg}");
// Медленная обработка - 3 секунды
await Task.Delay(3000);
Console.WriteLine($"[SLOW][{DateTime.Now:HH:mm:ss}] ✅ Processed: {msg}");
channel.BasicAck(e.DeliveryTag, multiple: false);
};
channel.BasicConsume("consumer_slow_queue", autoAck: false, consumer);
Console.WriteLine("Slow consumer is waiting for messages...");
// Бесконечное ожидание для контейнера
await Task.Delay(Timeout.Infinite);
async Task WaitForRabbitMQ()
{
const int maxRetries = 30;
const int delayMs = 2000;
for (int i = 0; i < maxRetries; i++)
{
try
{
var testFactory = new ConnectionFactory()
{
HostName = "rabbit",
UserName = "admin",
Password = "admin",
RequestedConnectionTimeout = TimeSpan.FromSeconds(2)
};
using var testConnection = testFactory.CreateConnection();
using var testChannel = testConnection.CreateModel();
Console.WriteLine("Slow consumer connected to RabbitMQ!");
return;
}
catch (Exception)
{
Console.WriteLine($"Slow consumer waiting for RabbitMQ... Attempt {i + 1}/{maxRetries}");
if (i == maxRetries - 1) throw;
await Task.Delay(delayMs);
}
}
}

View File

@@ -0,0 +1,67 @@
version: "3.9"
services:
rabbitmq:
image: rabbitmq:3.13-management
container_name: rabbit
ports:
- "5672:5672"
- "15672:15672"
environment:
RABBITMQ_DEFAULT_USER: admin
RABBITMQ_DEFAULT_PASS: admin
healthcheck:
test: rabbitmq-diagnostics check_port_connectivity
interval: 5s
timeout: 30s
retries: 10
publisher:
build:
context: ./publisher
dockerfile: Dockerfile
container_name: publisher
depends_on:
rabbitmq:
condition: service_healthy
restart: on-failure
consumer_slow:
build:
context: ./consumer_slow
dockerfile: Dockerfile
container_name: consumer_slow
depends_on:
rabbitmq:
condition: service_healthy
restart: on-failure
consumer_slow_1:
build:
context: ./consumer_slow
dockerfile: Dockerfile
container_name: consumer_slow_1
depends_on:
rabbitmq:
condition: service_healthy
restart: on-failure
consumer_slow_2:
build:
context: ./consumer_slow
dockerfile: Dockerfile
container_name: consumer_slow_2
depends_on:
rabbitmq:
condition: service_healthy
restart: on-failure
consumer_fast:
build:
context: ./consumer_fast
dockerfile: Dockerfile
container_name: consumer_fast
depends_on:
rabbitmq:
condition: service_healthy
restart: on-failure

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

View File

@@ -0,0 +1,11 @@
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src
COPY *.csproj .
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app
FROM mcr.microsoft.com/dotnet/runtime:9.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "Publisher.dll"]

View File

@@ -0,0 +1,81 @@
using RabbitMQ.Client;
using System.Text;
Console.WriteLine("Publisher started...");
await WaitForRabbitMQ();
var factory = new ConnectionFactory()
{
HostName = "rabbit",
UserName = "admin",
Password = "admin",
AutomaticRecoveryEnabled = true,
NetworkRecoveryInterval = TimeSpan.FromSeconds(5)
};
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.ExchangeDeclare(exchange: "support_events", type: "fanout", durable: true);
Console.WriteLine("Exchange 'support_events' declared. Starting to publish messages...");
int i = 1;
while (true)
{
try
{
string message = $"New ticket created #{i}";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(
exchange: "support_events",
routingKey: "",
basicProperties: null,
body: body
);
Console.WriteLine($"Published: {message}");
i++;
await Task.Delay(1000);
}
catch (Exception ex)
{
Console.WriteLine($"Error publishing message: {ex.Message}");
await Task.Delay(2000);
}
}
async Task WaitForRabbitMQ()
{
const int maxRetries = 30;
const int delayMs = 2000;
for (int i = 0; i < maxRetries; i++)
{
try
{
var testFactory = new ConnectionFactory()
{
HostName = "rabbit",
UserName = "admin",
Password = "admin",
RequestedConnectionTimeout = TimeSpan.FromSeconds(2)
};
using var testConnection = testFactory.CreateConnection();
using var testChannel = testConnection.CreateModel();
Console.WriteLine("Successfully connected to RabbitMQ!");
return;
}
catch (Exception ex)
{
Console.WriteLine($"Waiting for RabbitMQ... Attempt {i + 1}/{maxRetries}. Error: {ex.Message}");
if (i == maxRetries - 1) throw;
await Task.Delay(delayMs);
}
}
}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
</ItemGroup>
</Project>