Skip to content

Елагин Денис 6513 Лаб. 2#24

Open
Donistr wants to merge 24 commits intoitsecd:mainfrom
Donistr:main
Open

Елагин Денис 6513 Лаб. 2#24
Donistr wants to merge 24 commits intoitsecd:mainfrom
Donistr:main

Conversation

@Donistr
Copy link

@Donistr Donistr commented Mar 4, 2026

ФИО: Елагин Денис
Номер группы: 6513
Номер лабораторной: 2
Номер варианта: 38
Краткое описание предметной области: Объект жилого строительства
Краткое описание добавленных фич: сделал query based балансировщик нагрузки, подключил его в ocelot-е для 5 реплик сервиса-генератора

@github-actions github-actions bot added In progress Код в процессе проверки Lab 2 Лабораторная №2. Балансировка нагрузки labels Mar 4, 2026
@github-actions github-actions bot requested a review from alxmcs March 4, 2026 15:37
public class QueryBasedLoadBalancer(ILogger<QueryBasedLoadBalancer> logger, Func<Task<List<Service>>> services)
: ILoadBalancer
{
private static readonly object _lock = new();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут либо использовать PascalCase, либо s_ из гайдлайнов (хотя лично я не особо фанат таких префиксов)

Comment on lines +37 to +38
lock (_lock)
{
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У тебя тут нет разделяемых данных, тебе нечего лочить

Comment on lines +49 to +60
var queryParams = query
.OrderBy(kvp => kvp.Key, StringComparer.Ordinal)
.Select(kvp => $"{kvp.Key}={string.Join(",", kvp.Value.OrderBy(v => v))}")
.ToList();

var hashKey = string.Join("&", queryParams);
var hash = hashKey.GetHashCode();
if (hash < 0)
{
hash = -hash;
}
var index = (hash % currentServices.Count);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Более того, ты как будто тут планируешь сделать этот балансировщик универсальным, чтобы потенциально использовать его на разных маршрутах

public class QueryBasedLoadBalancer(ILogger<QueryBasedLoadBalancer> logger, Func<Task<List<Service>>> services)
: ILoadBalancer
{
private static readonly object _lock = new();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А _lock у тебя тут статический, так что все балансировщики перелочат друг друга, если будут существовать несколько экземпляров службы

Comment on lines +6 to +29
var generator1 = builder.AddProject<Projects.ResidentialBuilding_Generator>("generator-1")
.WithReference(cache, "residential-building-cache")
.WithEndpoint("http", endpoint => endpoint.Port = 5201)
.WaitFor(cache);

var generator2 = builder.AddProject<Projects.ResidentialBuilding_Generator>("generator-2")
.WithReference(cache, "residential-building-cache")
.WithEndpoint("http", endpoint => endpoint.Port = 5202)
.WaitFor(cache);

var generator3 = builder.AddProject<Projects.ResidentialBuilding_Generator>("generator-3")
.WithReference(cache, "residential-building-cache")
.WithEndpoint("http", endpoint => endpoint.Port = 5203)
.WaitFor(cache);

var generator4 = builder.AddProject<Projects.ResidentialBuilding_Generator>("generator-4")
.WithReference(cache, "residential-building-cache")
.WithEndpoint("http", endpoint => endpoint.Port = 5204)
.WaitFor(cache);

var generator5 = builder.AddProject<Projects.ResidentialBuilding_Generator>("generator-5")
.WithReference(cache, "residential-building-cache")
.WithEndpoint("http", endpoint => endpoint.Port = 5205)
.WaitFor(cache);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это можно сделать в цикле

Comment on lines +33 to +37
.WithReference(generator1)
.WithReference(generator2)
.WithReference(generator3)
.WithReference(generator4)
.WithReference(generator5)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Гейтвею не нужны референсы на сервисы, референсы попадают в appsettings.json, а конфиг у тебя в ocelot.json

Comment on lines +39 to +43
.WaitFor(generator1)
.WaitFor(generator2)
.WaitFor(generator3)
.WaitFor(generator4)
.WaitFor(generator5);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это тоже внести в цикл

Comment on lines +10 to +19
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowLocalDev", policy =>
{
policy
.AllowAnyOrigin()
.WithHeaders("Content-Type")
.WithMethods("GET");
});
});
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А зачем тебе тут корс? У тебя клиент больше не стучится в сервис напрямую

{
"Routes": [
{
"DownstreamPathTemplate": "/api/{everything}",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тебе серьёзно нужен тут плейсхолдер? у тебя всего один маршрут

{
hash = -hash;
}
var index = (hash % currentServices.Count);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Чето ты играл с хешами и проиграл. Читаем задание:

Image

Смотрим:
11 % 5 = 1
21 % 5 = 1
101 % 5 =1
Значит, эти идентификаторы должны обработаться одной и то же репликой

Получаем:

11 21 101
Image Image Image

Реплики разные 🤷‍♂️

@Donistr Donistr requested a review from alxmcs March 5, 2026 14:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

In progress Код в процессе проверки Lab 2 Лабораторная №2. Балансировка нагрузки

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants