Skip to content
Open
Show file tree
Hide file tree
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
17 changes: 17 additions & 0 deletions Api.Gateway/Api.Gateway.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Ocelot" Version="24.1.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\WarehouseApp\WarehouseApp.ServiceDefaults\WarehouseApp.ServiceDefaults.csproj" />
</ItemGroup>

</Project>
32 changes: 32 additions & 0 deletions Api.Gateway/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Api.Gateway;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();
builder.Services.AddServiceDiscovery();
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddOcelot()
.AddCustomLoadBalancer((sp, _, provider) =>
new WeightedRandom(provider.GetAsync, sp.GetRequiredService<IConfiguration>()));

var allowedOrigins = builder.Configuration
.GetSection("Cors:AllowedOrigins")
.Get<string[]>() ?? [];

builder.Services.AddCors(options =>
options.AddDefaultPolicy(policy =>
policy.WithOrigins(allowedOrigins)
.WithMethods("GET")
.AllowAnyHeader()));

var app = builder.Build();

app.UseCors();

app.MapDefaultEndpoints();

await app.UseOcelot();

app.Run();
38 changes: 38 additions & 0 deletions Api.Gateway/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:48792",
"sslPort": 44345
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5252",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7032;http://localhost:5252",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
56 changes: 56 additions & 0 deletions Api.Gateway/WeightedRandom.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using Ocelot.LoadBalancer.Interfaces;
using Ocelot.Responses;
using Ocelot.Values;

namespace Api.Gateway;

/// <summary>
/// Балансировщик нагрузки «Взвешенный случайный выбор» (Weighted Random).
/// Каждой реплике присваивается целочисленный вес из секции <c>LoadBalancer:Weights</c>.
/// При поступлении запроса реплика выбирается случайно — вероятность выбора пропорциональна весу
/// (вес реплики / сумма всех весов).
/// </summary>
/// <param name="services">Делегат для получения списка доступных реплик сервиса.</param>
/// <param name="configuration">
/// Конфигурация приложения с секцией <c>LoadBalancer:Weights</c> —
/// массив <c>int</c>, где индекс соответствует номеру реплики, а значение — относительному весу.
/// </param>
public class WeightedRandom(
Func<Task<List<Service>>> services,
IConfiguration configuration) : ILoadBalancer
{
public string Type => nameof(WeightedRandom);

private readonly int[] _weights = configuration.GetSection("LoadBalancer:Weights").Get<int[]>() ?? [];

public async Task<Response<ServiceHostAndPort>> LeaseAsync(HttpContext context)
{
var pool = await services();

if (pool.Count == 0)
throw new InvalidOperationException("No available downstream services");

var total = 0;
for (var i = 0; i < pool.Count; i++)
total += Weight(i);

var value = Random.Shared.Next(total);

for (var i = 0; i < pool.Count; i++)
{
value -= Weight(i);
if (value < 0)
return new OkResponse<ServiceHostAndPort>(pool[i].HostAndPort);
}

return new OkResponse<ServiceHostAndPort>(pool[^1].HostAndPort);
}

public void Release(ServiceHostAndPort hostAndPort) { }

/// <summary>
/// Возвращает вес реплики по индексу.
/// Если вес не задан или не положителен — возвращает 1.
/// </summary>
private int Weight(int i) => i < _weights.Length && _weights[i] > 0 ? _weights[i] : 1;
}
8 changes: 8 additions & 0 deletions Api.Gateway/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
18 changes: 18 additions & 0 deletions Api.Gateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Cors": {
"AllowedOrigins": [
"http://localhost:5127",
"https://localhost:7282"
]
},
"LoadBalancer": {
"Weights": [ 35, 25, 20, 12, 8 ]
},
"AllowedHosts": "*"
}
20 changes: 20 additions & 0 deletions Api.Gateway/ocelot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"Routes": [
{
"DownstreamPathTemplate": "/api/warehouse-item",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 7250 },
{ "Host": "localhost", "Port": 7251 },
{ "Host": "localhost", "Port": 7252 },
{ "Host": "localhost", "Port": 7253 },
{ "Host": "localhost", "Port": 7254 }
],
"UpstreamPathTemplate": "/warehouse-item",
"UpstreamHttpMethod": [ "GET" ],
"LoadBalancerOptions": {
"Type": "WeightedRandom"
}
}
]
}
8 changes: 4 additions & 4 deletions Client.Wasm/Components/StudentCard.razor
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
</CardHeader>
<CardBody>
<UnorderedList Unstyled>
<UnorderedListItem>Номер <Strong>№X "Название лабораторной"</Strong></UnorderedListItem>
<UnorderedListItem>Вариант <Strong>№Х "Название варианта"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнена <Strong>Фамилией Именем 65ХХ</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://puginarug.com/">Ссылка на форк</Link></UnorderedListItem>
<UnorderedListItem>Номер <Strong>№2 "Балансировка нагрузки"</Strong></UnorderedListItem>
<UnorderedListItem>Вариант <Strong>№31 "Товар на складе"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнил <Strong>Пахомов Леонид 6512</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/Sonya-From-IBAS/cloud-development">Ссылка на форк</Link></UnorderedListItem>
</UnorderedList>
</CardBody>
</Card>
6 changes: 3 additions & 3 deletions Client.Wasm/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"applicationUrl": "http://localhost:5127",
"environmentVariables": {
Expand All @@ -22,7 +22,7 @@
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"applicationUrl": "https://localhost:7282;http://localhost:5127",
"environmentVariables": {
Expand All @@ -31,7 +31,7 @@
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchBrowser": false,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
Expand Down
2 changes: 1 addition & 1 deletion Client.Wasm/wwwroot/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
}
},
"AllowedHosts": "*",
"BaseAddress": ""
"BaseAddress": "https://localhost:7032/warehouse-item"
}
24 changes: 24 additions & 0 deletions CloudDevelopment.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ VisualStudioVersion = 17.14.36811.4
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client.Wasm", "Client.Wasm\Client.Wasm.csproj", "{AE7EEA74-2FE0-136F-D797-854FD87E022A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WarehouseApp.AppHost", "WarehouseApp\WarehouseApp.AppHost\WarehouseApp.AppHost.csproj", "{62DA23FA-2BAF-4F9A-B719-B4EE06809BA0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WarehouseApp.ServiceDefaults", "WarehouseApp\WarehouseApp.ServiceDefaults\WarehouseApp.ServiceDefaults.csproj", "{ADCEFD5A-DE46-3D8E-DD7F-B5FD83A993DF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WarehouseApp.Api", "WarehouseApp.Api\WarehouseApp.Api.csproj", "{6D2468DE-58C5-E4A1-2839-0E91AF620D88}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Gateway", "Api.Gateway\Api.Gateway.csproj", "{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -15,6 +23,22 @@ Global
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AE7EEA74-2FE0-136F-D797-854FD87E022A}.Release|Any CPU.Build.0 = Release|Any CPU
{62DA23FA-2BAF-4F9A-B719-B4EE06809BA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{62DA23FA-2BAF-4F9A-B719-B4EE06809BA0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{62DA23FA-2BAF-4F9A-B719-B4EE06809BA0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{62DA23FA-2BAF-4F9A-B719-B4EE06809BA0}.Release|Any CPU.Build.0 = Release|Any CPU
{ADCEFD5A-DE46-3D8E-DD7F-B5FD83A993DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ADCEFD5A-DE46-3D8E-DD7F-B5FD83A993DF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ADCEFD5A-DE46-3D8E-DD7F-B5FD83A993DF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ADCEFD5A-DE46-3D8E-DD7F-B5FD83A993DF}.Release|Any CPU.Build.0 = Release|Any CPU
{6D2468DE-58C5-E4A1-2839-0E91AF620D88}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6D2468DE-58C5-E4A1-2839-0E91AF620D88}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6D2468DE-58C5-E4A1-2839-0E91AF620D88}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6D2468DE-58C5-E4A1-2839-0E91AF620D88}.Release|Any CPU.Build.0 = Release|Any CPU
{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C99E72F4-9BA7-7D56-C88E-FB28534EFCB6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
Loading
Loading