Merge pull request 'kuzarin_maxim_lab_4' (#34) from kuzarin_maxim_lab_4 into main

Reviewed-on: Alexey/DAS_2024_1#34
This commit is contained in:
Alexey 2024-10-07 23:01:48 +04:00
commit 1289d67a62
31 changed files with 1304 additions and 0 deletions

View File

@ -0,0 +1,30 @@
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
!**/.gitignore
!.git/HEAD
!.git/config
!.git/packed-refs
!.git/refs/heads/**

484
kuzarin_maxim_lab_4/.gitignore vendored Normal file
View File

@ -0,0 +1,484 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from `dotnet new gitignore`
# dotenv files
.env
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET
project.lock.json
project.fragment.lock.json
artifacts/
# Tye
.tye/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
.idea
##
## Visual studio for Mac
##
# globs
Makefile.in
*.userprefs
*.usertasks
config.make
config.status
aclocal.m4
install-sh
autom4te.cache/
*.tar.gz
tarballs/
test-results/
# Mac bundle stuff
*.dmg
*.app
# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# Vim temporary swap files
*.swp

View File

@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PublishSubscribe\PublishSubscribe.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,23 @@
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/runtime:8.0 AS base
WORKDIR /app
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["Consumer1/Consumer1.csproj", "Consumer1/"]
COPY ["PublishSubscribe/PublishSubscribe.csproj", "PublishSubscribe/"]
RUN dotnet restore "./Consumer1/Consumer1.csproj"
COPY . .
WORKDIR "/src/Consumer1"
RUN dotnet build "./Consumer1.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./Consumer1.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Consumer1.dll"]

View File

@ -0,0 +1,36 @@

using PublishSubscribe;
var rabbitHost = Environment.GetEnvironmentVariable("RABBIT_HOST") ?? "localhost";
var rabbitUsername = Environment.GetEnvironmentVariable("RABBIT_USERNAME") ?? "user";
var rabbitPassword = Environment.GetEnvironmentVariable("RABBIT_PASSWORD") ?? "password";
var rabbitExchange = Environment.GetEnvironmentVariable("RABBIT_EXCHANGE") ?? "SorterIn";
var rabbitQueue = Environment.GetEnvironmentVariable("RABBIT_QUEUE") ?? "SorterFirst";
var HasDelay = bool.Parse(Environment.GetEnvironmentVariable("HAS_DELAY") ?? "false");
Thread.Sleep(2000);
var Receiver = new ExchangeReceiver(rabbitHost, rabbitUsername, rabbitPassword);
Receiver.SubscribeTo(rabbitExchange, (message) =>
{
var rnd = new Random();
var messageData = message.Split("|");
Console.WriteLine($"[<-]\tПришло сообщение\tId:{messageData[0]}\tType:{messageData[2]}\t Data:{string.Join(";", messageData.Skip(3))}");
if (HasDelay)
{
Thread.Sleep(rnd.Next(2000, 3000));
Console.WriteLine($"[\\/]\tОбработка сообщения {messageData[0]} завершена");
}
else
{
Console.WriteLine($"[\\/]\tСообщение {messageData[0]} обрабатывается мгновенно");
}
},
rabbitQueue);
while (true) ;

View File

@ -0,0 +1,10 @@
{
"profiles": {
"Consumer1": {
"commandName": "Project"
},
"Container (Dockerfile)": {
"commandName": "Docker"
}
}
}

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.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,19 @@

using HelloWorld;
string brokerHost = "localhost";
string queueName = "hello";
using var sender = new Sender(brokerHost,"user", "password", queueName);
using var receiver = new Receiver(brokerHost, "user", "password", queueName);
receiver.AddMessageHandler(text => Console.WriteLine($"Received Message from rabbit: {text}"));
Console.WriteLine("Send Message to rabbit: Hellow World!");
sender.SendMessageToQueue("Hellow World!");
while (true) ;

View File

@ -0,0 +1,70 @@
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace HelloWorld
{
public class Receiver : IDisposable
{
private readonly ConnectionFactory _connectionFactory;
private readonly IConnection _connection;
private readonly IModel _channel;
private readonly string _queueName;
public Receiver(string brockerHost, string brockerUsername, string brockerPassword, string queueName)
{
_queueName = queueName;
_connectionFactory = new ConnectionFactory() { HostName = brockerHost, UserName = brockerUsername, Password = brockerPassword };
_connection = _connectionFactory.CreateConnection();
_channel = _connection.CreateModel();
_channel.QueueDeclare(queue: _queueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
_channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
}
public bool AddMessageHandler(Action<string> handler)
{
try
{
var consumer = new EventingBasicConsumer(_channel);
consumer.Received += (model, ea) =>
{
var messageBody = ea.Body.ToArray();
var messageText = Encoding.UTF8.GetString(messageBody);
handler(messageText);
_channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
};
_channel.BasicConsume(queue: _queueName,
autoAck: false,
consumer: consumer);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return false;
}
~Receiver() => Dispose();
public void Dispose()
{
_connection.Dispose();
_channel.Dispose();
}
}
}

View File

@ -0,0 +1,62 @@
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace HelloWorld
{
public class Sender : IDisposable
{
private readonly ConnectionFactory _connectionFactory;
private readonly IConnection _connection;
private readonly IModel _channel;
private readonly string _queueName;
public Sender(string brockerHost, string brockerUsername, string brockerPassword, string queueName)
{
_queueName = queueName;
_connectionFactory = new ConnectionFactory() { HostName = brockerHost, UserName = brockerUsername, Password = brockerPassword };
_connection = _connectionFactory.CreateConnection();
_channel = _connection.CreateModel();
_channel.QueueDeclare( queue: _queueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
}
public bool SendMessageToQueue(string messageText)
{
try
{
var messageBody = Encoding.UTF8.GetBytes(messageText);
var properties = _channel.CreateBasicProperties();
properties.Persistent = true;
_channel.BasicPublish(exchange: string.Empty,
routingKey: _queueName,
basicProperties: properties,
body: messageBody);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return false;
}
~Sender() => Dispose();
public void Dispose()
{
_connection.Dispose();
_channel.Dispose();
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 418 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 265 KiB

View File

@ -0,0 +1,87 @@
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace PublishSubscribe
{
public class ExchangeReceiver: IDisposable
{
private readonly ConnectionFactory _connectionFactory;
private readonly IConnection _connection;
private readonly IModel _channel;
public Dictionary<string, HashSet<string>> Queues { get; private set; } = new();
public ExchangeReceiver(string brockerHost, string brockerUsername, string brockerPassword)
{
_connectionFactory = new ConnectionFactory() { HostName = brockerHost, UserName = brockerUsername, Password = brockerPassword };
_connection = _connectionFactory.CreateConnection();
_channel = _connection.CreateModel();
}
public bool SubscribeTo(string exchange, Action<string> handler, string? queueName = null)
{
try
{
if (!Queues.ContainsKey(exchange))
{
_channel.ExchangeDeclare(exchange: "logs", type: ExchangeType.Fanout);
Queues.Add(exchange, new HashSet<string>());
}
if (queueName != null)
_channel.QueueDeclare(queue: queueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
queueName = queueName ?? _channel.QueueDeclare().QueueName;
_channel.QueueBind(queue: queueName,
exchange: exchange,
routingKey: string.Empty);
var consumer = new EventingBasicConsumer(_channel);
consumer.Received += (model, ea) =>
{
try
{
var message = Encoding.UTF8.GetString(ea.Body.ToArray());
handler(message);
_channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
};
_channel.BasicConsume(queue: queueName,
autoAck: false,
consumer: consumer);
Queues[exchange].Add(queueName);
return true;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return false;
}
~ExchangeReceiver() => Dispose();
public void Dispose()
{
_connection.Dispose();
_channel.Dispose();
}
}
}

View File

@ -0,0 +1,70 @@
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace PublishSubscribe
{
public class ExchangeSender: IDisposable
{
private readonly ConnectionFactory _connectionFactory;
private readonly IConnection _connection;
private readonly IModel _channel;
public HashSet<string> Exchanges { get; private set; } = new HashSet<string>();
public ExchangeSender(string brockerHost, string brockerUsername, string brockerPassword)
{
_connectionFactory = new ConnectionFactory() { HostName = brockerHost, UserName = brockerUsername, Password = brockerPassword };
_connection = _connectionFactory.CreateConnection();
_channel = _connection.CreateModel();
}
public bool AddExcange(string exchange, string exchangeType = ExchangeType.Fanout)
{
try
{
_channel.ExchangeDeclare(exchange, exchangeType);
Exchanges.Add(exchange);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return false;
}
public bool PublishToExchange(string exchange, string message)
{
try
{
if (!Exchanges.Contains(exchange))
return false;
var messageBody = Encoding.UTF8.GetBytes(message);
_channel.BasicPublish(exchange: exchange,
routingKey: string.Empty,
basicProperties: null,
body: messageBody);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return false;
}
~ExchangeSender() => Dispose();
public void Dispose()
{
_connection.Dispose();
_channel.Dispose();
}
}
}

View File

@ -0,0 +1,24 @@
using PublishSubscribe;
string brokerHost = "localhost";
string exchangeName = "logs";
var sender = new ExchangeSender(brokerHost, "user", "password");
sender.AddExcange(exchangeName);
var receiver1 = new ExchangeReceiver(brokerHost, "user", "password");
var receiver2 = new ExchangeReceiver(brokerHost, "user", "password");
receiver1.SubscribeTo(exchangeName, message => Console.WriteLine($" [->1] Received: {message}"));
receiver2.SubscribeTo(exchangeName, message => Console.WriteLine($" [->2] Received: {message}"));
for (int i = 0; i < 10; i++)
{
var message = $"Messga number {i}";
Console.WriteLine($" [0->] Send: {message}");
sender.PublishToExchange(exchangeName, message);
}
while (true);

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.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,23 @@
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/runtime:8.0 AS base
WORKDIR /app
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["Publisher/Publisher.csproj", "Publisher/"]
COPY ["PublishSubscribe/PublishSubscribe.csproj", "PublishSubscribe/"]
RUN dotnet restore "./Publisher/Publisher.csproj"
COPY . .
WORKDIR "/src/Publisher"
RUN dotnet build "./Publisher.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./Publisher.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Publisher.dll"]

View File

@ -0,0 +1,51 @@

using PIHelperSh.RandomEx.Extentions;
using PublishSubscribe;
using System.Text;
var rabbitHost = Environment.GetEnvironmentVariable("RABBIT_HOST") ?? "localhost";
var rabbitUsername = Environment.GetEnvironmentVariable("RABBIT_USERNAME") ?? "user";
var rabbitPassword = Environment.GetEnvironmentVariable("RABBIT_PASSWORD") ?? "password";
var rabbitExchange = Environment.GetEnvironmentVariable("RABBIT_EXCHANGE") ?? "SorterIn";
var Sender = new ExchangeSender(rabbitHost, rabbitUsername, rabbitPassword);
Sender.AddExcange(rabbitExchange);
var rnd = new Random();
while (true)
{
StringBuilder sb = new();
sb.Append(rnd.Next().ToString("0000000000"));
sb.Append("|");
switch (rnd.Next(4))
{
case 0:
sb.Append($"0|Прибыла послыка|{rnd.NextString("[0-9]7")}");
break;
case 1:
sb.Append($"1|Прибыла послыка без штрих кода|");
break;
case 2:
var count = rnd.Next(2,8);
sb.Append($"2|Прибыла послыка c несколькими кодами|{count}");
for (int i = 0; i < count; i++)
{
sb.Append($"|{rnd.NextString("[0-9]7")}");
}
break;
default:
sb.Append($"3|Произошла ошибка|{rnd.Next(500,599)}");
break;
}
var text = sb.ToString();
Console.WriteLine($"[->]\tОтправлено сообщение\t{text}");
Sender.PublishToExchange(rabbitExchange, text);
await Task.Delay(1000);
}

View File

@ -0,0 +1,10 @@
{
"profiles": {
"Publisher": {
"commandName": "Project"
},
"Container (Dockerfile)": {
"commandName": "Docker"
}
}
}

View File

@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
<PackageReference Include="PIHelperSh.RandomEx" Version="1.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PublishSubscribe\PublishSubscribe.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,39 @@
# Лабораторная работа 4
Данная работа посвящена работе с брокером сообщений RabbitMQ.
## Прохождение tutorial
Для каждого из уроков был создан отдельный проект, где в Program создаётся producer и concumer(s), а для подтверждения работоспособности использовалась консоль. Скриншоты подтверждения
### "Hello World!"
![Task 1](Images/task1.png)
### Work Queues
![Task 2](Images/task2.png)
### Publish/Subscribe
![Task 3](Images/task3.png)
## Описание
Для демонстрационной работы была выбрана предметная область гипотетический системы обработки посылок. Имеется некий сканер, который отправляет устройству сведения через очереди (какие штрих-коды он отсканировал, или, если произошла какая-то ошибка - какая это ошибка).
## Запуск
Для запуска лабораторной работы необходимо иметь запущенный движок Docker на устройстве.
Необходимо перейти в папку, где располагается данный файл. Далее открыть терминал и ввести команду:
```
docker compose up -d --build
```
Важно, чтобы в этот момент на компьютере был свободен порт 8081 и 5672.
Результаты работы системы можно простелить через Web GUI брокера(http://localhost:8081) или посмотрел логи контейнеров.
## Исследования
Первоначальный вариант запуска предполагает, что имеется всего 2 потребителя:
1. Тратит на обработку сообщения 2-3 секунды
2. Тратит на обработку сообщения минимальное возможное время(условно - не тратит вообще ничего)
Так как производитель отправляет сообщения 1 раз в секунду, можно понять, что первый потребитель не справится с потоком сообщения, в то время как второй будет успевать обрабатывать их. На практике это подтверждается: очередь, куда из exchange попадают сообщения для первого потребителя только растёт(не справляемся с нагрузкой). В то время как у второго значения практически всегда - о.
<br/>
![Queue 1](Images/FirstService1.png)
<br/>
![Queue 2](Images/SecondService.png)
<br/>
Учитывая описанное ранее, можно попробовать решить проблему первого сервиса за счёт горизонтального масштабирования. Теоретически должно хватить 3-х копий, чтобы сообщения не застаивались. На практике эта гипотеза подтвердилась. Очередь пусть и не пустеет, но не становится длиннее.
<br/>
![Queue 1 for 3 services](\Images\FirstService3.png)
## Видеодемонстрация
Был записан видеоролик, демонстрирующий процесс запуска и работы системы. Он расположен по [адресу](https://drive.google.com/file/d/1l7LXVXOb-oRNdS8aJGgeV7xbGCOpi1Es/view?usp=sharing)
Стоит отметить, что ошибки, которые были видны в логах сервисов связаны с относительно долгим стартом RabbitMQ (несмотря на depands_on брокер не усаапевает подняться, когда сервисы встают, и они не могут подключиться, из-за чего и падают. но из за политики перехапуска их раз за разом востанавливают, до тех пор пока брокер полностью не будет готов принимать сообщения)

View File

@ -0,0 +1,49 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.34916.146
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HelloWorld", "HelloWorld\HelloWorld.csproj", "{60B7884C-CE35-49A0-821A-50785A154E43}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkQueues", "WorkQueues\WorkQueues.csproj", "{556D0467-9405-44C6-A75F-E72F04CB4A82}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PublishSubscribe", "PublishSubscribe\PublishSubscribe.csproj", "{4FDFD479-F6C1-49AE-8EE7-F91E926608AA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Publisher", "Publisher\Publisher.csproj", "{E92C8339-8C8F-4449-9B75-2DB4563DA494}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Consumer1", "Consumer1\Consumer1.csproj", "{58FFED3D-414A-4575-B6C7-8F82B781BDFC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{60B7884C-CE35-49A0-821A-50785A154E43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{60B7884C-CE35-49A0-821A-50785A154E43}.Debug|Any CPU.Build.0 = Debug|Any CPU
{60B7884C-CE35-49A0-821A-50785A154E43}.Release|Any CPU.ActiveCfg = Release|Any CPU
{60B7884C-CE35-49A0-821A-50785A154E43}.Release|Any CPU.Build.0 = Release|Any CPU
{556D0467-9405-44C6-A75F-E72F04CB4A82}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{556D0467-9405-44C6-A75F-E72F04CB4A82}.Debug|Any CPU.Build.0 = Debug|Any CPU
{556D0467-9405-44C6-A75F-E72F04CB4A82}.Release|Any CPU.ActiveCfg = Release|Any CPU
{556D0467-9405-44C6-A75F-E72F04CB4A82}.Release|Any CPU.Build.0 = Release|Any CPU
{4FDFD479-F6C1-49AE-8EE7-F91E926608AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4FDFD479-F6C1-49AE-8EE7-F91E926608AA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4FDFD479-F6C1-49AE-8EE7-F91E926608AA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4FDFD479-F6C1-49AE-8EE7-F91E926608AA}.Release|Any CPU.Build.0 = Release|Any CPU
{E92C8339-8C8F-4449-9B75-2DB4563DA494}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E92C8339-8C8F-4449-9B75-2DB4563DA494}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E92C8339-8C8F-4449-9B75-2DB4563DA494}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E92C8339-8C8F-4449-9B75-2DB4563DA494}.Release|Any CPU.Build.0 = Release|Any CPU
{58FFED3D-414A-4575-B6C7-8F82B781BDFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{58FFED3D-414A-4575-B6C7-8F82B781BDFC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{58FFED3D-414A-4575-B6C7-8F82B781BDFC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{58FFED3D-414A-4575-B6C7-8F82B781BDFC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B293D70F-0A74-4F7D-A290-05DFCF97DBCC}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,2 @@
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

View File

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,37 @@

using HelloWorld;
string brokerHost = "localhost";
string queueName = "task_queue";
using var sender = new Sender(brokerHost, "user", "password", queueName);
using var receiver1 = new Receiver(brokerHost, "user", "password", queueName);
using var receiver2 = new Receiver(brokerHost, "user", "password", queueName);
receiver1.AddMessageHandler(text => {
Console.WriteLine($"[1] Received Message from rabbit: {text}");
int dots = text.Split('.').Length - 1;
Thread.Sleep(dots * 1000);
Console.WriteLine($"[1] Done Message: {text}");
});
receiver2.AddMessageHandler(text => {
Console.WriteLine($"[2] Received Message from rabbit: {text}");
int dots = text.Split('.').Length - 1;
Thread.Sleep(dots * 1000);
Console.WriteLine($"[2] Done Message: {text}");
});
for (int i = 0; i < 5; i++)
{
var message = $"Message number {i}{string.Join("", Enumerable.Range(0, i).Select(x=>"."))}";
Console.WriteLine($"Send Message to rabbit: {message}");
sender.SendMessageToQueue(message);
}
while (true) ;

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\HelloWorld\HelloWorld.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,87 @@
services:
rabbit:
image: rabbitmq:${RABBIT_TAG}
restart: always
ports:
- 5672:5672
- 8081:15672
environment:
RABBITMQ_DEFAULT_USER: ${RABBIT_USERNAME}
RABBITMQ_DEFAULT_PASS: ${RABBIT_PASSWORD}
publisher:
build:
context: .
dockerfile: ./Publisher/Dockerfile
restart: always
depends_on:
- rabbit
environment:
RABBIT_HOST: rabbit
RABBIT_USERNAME: ${RABBIT_USERNAME}
RABBIT_PASSWORD: ${RABBIT_PASSWORD}
RABBIT_EXCHANGE: 'SorterIn'
concumer1:
build:
context: .
dockerfile: ./Consumer1/Dockerfile
restart: always
depends_on:
- rabbit
- publisher
environment:
RABBIT_HOST: rabbit
RABBIT_USERNAME: ${RABBIT_USERNAME}
RABBIT_PASSWORD: ${RABBIT_PASSWORD}
RABBIT_EXCHANGE: 'SorterIn'
RABBIT_QUEUE: 'SorterFirst'
HAS_DELAY: "true"
concumer2:
build:
context: .
dockerfile: ./Consumer1/Dockerfile
restart: always
depends_on:
- rabbit
- publisher
environment:
RABBIT_HOST: rabbit
RABBIT_USERNAME: ${RABBIT_USERNAME}
RABBIT_PASSWORD: ${RABBIT_PASSWORD}
RABBIT_EXCHANGE: 'SorterIn'
RABBIT_QUEUE: 'SorterSecond'
HAS_DELAY: "false"
concumer12:
build:
context: .
dockerfile: ./Consumer1/Dockerfile
restart: always
depends_on:
- rabbit
- publisher
environment:
RABBIT_HOST: rabbit
RABBIT_USERNAME: ${RABBIT_USERNAME}
RABBIT_PASSWORD: ${RABBIT_PASSWORD}
RABBIT_EXCHANGE: 'SorterIn'
RABBIT_QUEUE: 'SorterFirst'
HAS_DELAY: "true"
concumer13:
build:
context: .
dockerfile: ./Consumer1/Dockerfile
restart: always
depends_on:
- rabbit
- publisher
environment:
RABBIT_HOST: rabbit
RABBIT_USERNAME: ${RABBIT_USERNAME}
RABBIT_PASSWORD: ${RABBIT_PASSWORD}
RABBIT_EXCHANGE: 'SorterIn'
RABBIT_QUEUE: 'SorterFirst'
HAS_DELAY: "true"