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="..\VehicleVault\VehicleVault.ServiceDefaults\VehicleVault.ServiceDefaults.csproj" />
</ItemGroup>

</Project>
34 changes: 34 additions & 0 deletions Api.Gateway/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
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 WeightedRoundRobin(provider.GetAsync, sp.GetRequiredService<IConfiguration>()));

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

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

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:6371",
"sslPort": 44374
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5116",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7145;http://localhost:5116",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
52 changes: 52 additions & 0 deletions Api.Gateway/WeightedRoundRobin.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using Ocelot.LoadBalancer.Interfaces;
using Ocelot.Responses;
using Ocelot.Values;

namespace Api.Gateway;

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

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

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

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

lock (_lock)
{
if (_index >= pool.Count) _index = 0;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Думаю в этом случае _used тоже нужно обнулять


if (_used >= Weight(_index))
{
_index = (_index + 1) % pool.Count;
_used = 0;
}

_used++;
return new OkResponse<ServiceHostAndPort>(pool[_index].HostAndPort);
}
}

public void Release(ServiceHostAndPort hostAndPort) { }

/// <summary>Возвращает вес реплики по индексу. Если не задан или не положителен — возвращает 1.</summary>
/// <param name="i">Индекс реплики.</param>
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"
}
},
"AllowedHosts": "*",
"Cors": {
"AllowedOrigins": [
"http://localhost:5127",
"https://localhost:7282"
]
},
"LoadBalancer": {
"Weights": [ 3, 2, 1, 1, 1 ]
}
}
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": [
{
"UpstreamPathTemplate": "/vehicle",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/api/vehicle",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 8000 },
{ "Host": "localhost", "Port": 8001 },
{ "Host": "localhost", "Port": 8002 },
{ "Host": "localhost", "Port": 8003 },
{ "Host": "localhost", "Port": 8004 }
],
"LoadBalancerOptions": {
"Type": "WeightedRoundRobin"
}
}
]
}
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>№27 "Транспортное средство"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнила <Strong>Лаврук Маргарита 6512</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/Mlavrukk/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:7145/vehicle"
}
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}") = "VehicleVault.AppHost", "VehicleVault\VehicleVault.AppHost\VehicleVault.AppHost.csproj", "{675E2979-6231-45C9-A79D-E8D1BE095D7E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleVault.ServiceDefaults", "VehicleVault\VehicleVault.ServiceDefaults\VehicleVault.ServiceDefaults.csproj", "{2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleVault.Api", "VehicleVault.Api\VehicleVault.Api.csproj", "{EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}"
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
{675E2979-6231-45C9-A79D-E8D1BE095D7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{675E2979-6231-45C9-A79D-E8D1BE095D7E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{675E2979-6231-45C9-A79D-E8D1BE095D7E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{675E2979-6231-45C9-A79D-E8D1BE095D7E}.Release|Any CPU.Build.0 = Release|Any CPU
{2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2691D15C-C371-2A92-5FA1-3FA8EDE4BFA9}.Release|Any CPU.Build.0 = Release|Any CPU
{EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EEC635D9-1FAB-BCC6-17E0-3EE52C2D262C}.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