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
23 changes: 23 additions & 0 deletions Api.Gateway/Api.Gateway.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<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="..\VehicleApp\VehicleApp.ServiceDefaults\VehicleApp.ServiceDefaults.csproj" />
</ItemGroup>

<ItemGroup>
<None Update="ocelot.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

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

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();
builder.Services.AddServiceDiscovery();
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);

var overrides = new Dictionary<string, string?>();
var discovered = new List<string>();
for (var i = 0; Environment.GetEnvironmentVariable($"services__vehicleapp-api-{i}__https__0") is { } url; i++)
{
var uri = new Uri(url);
overrides[$"Routes:0:DownstreamHostAndPorts:{i}:Host"] = uri.Host;
overrides[$"Routes:0:DownstreamHostAndPorts:{i}:Port"] = uri.Port.ToString();
discovered.Add($"{uri.Host}:{uri.Port}");
}

if (overrides.Count > 0)
builder.Configuration.AddInMemoryCollection(overrides);

builder.Services.AddOcelot()
.AddCustomLoadBalancer((sp, _, provider) =>
new WeightedRoundRobinLoadBalancer(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")
.WithHeaders("Content-Type")));

var app = builder.Build();

app.MapDefaultEndpoints();

app.UseCors();

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

namespace Api.Gateway;

/// <summary>
/// Балансировщик нагрузки Weighted Round Robin (взвешенная карусель).
/// Каждой реплике сервиса присваивается вес, в зависимости от которого она используется чаще/реже других.
/// Реплики перебираются циклически: для весов [3, 2, 1] последовательность будет R1, R1, R1, R2, R2, R3, R1, R1, R1, ...
/// </summary>
/// <param name="services">Делегат получения актуального списка downstream-реплик от Ocelot.</param>
/// <param name="configuration">
/// Конфигурация приложения. Веса считываются из секции <c>LoadBalancer:Weights</c> как массив <see cref="int"/>
/// в порядке реплик. Если для реплики вес отсутствует или некорректен (≤ 0), используется значение 1.
/// </param>
public class WeightedRoundRobinLoadBalancer(
Func<Task<List<Service>>> services,
IConfiguration configuration) : ILoadBalancer
{
private readonly int[] _weights = configuration
.GetSection("LoadBalancer:Weights").Get<int[]>() ?? [];

private long _counter = -1;

public string Type => nameof(WeightedRoundRobinLoadBalancer);

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

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

var weights = NormalizeWeights(list.Count);
var total = weights.Sum();

var pick = (int)(Interlocked.Increment(ref _counter) % total);
if (pick < 0) pick += total;

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

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

public void Release(ServiceHostAndPort hostAndPort) { }

private int[] NormalizeWeights(int count)
{
var result = new int[count];
for (var i = 0; i < count; i++)
result[i] = i < _weights.Length && _weights[i] > 0 ? _weights[i] : 1;
return result;
}
}
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": [ 5, 4, 3, 2, 1 ]
}
}
35 changes: 35 additions & 0 deletions Api.Gateway/ocelot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"Routes": [
{
"UpstreamPathTemplate": "/vehicle",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/api/vehicle",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 0
},
{
"Host": "localhost",
"Port": 0
},
{
"Host": "localhost",
"Port": 0
},
{
"Host": "localhost",
"Port": 0
},
{
"Host": "localhost",
"Port": 0
}
],
"LoadBalancerOptions": {
"Type": "WeightedRoundRobinLoadBalancer"
}
}
]
}
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>№1 "Транспортное средство"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнил <Strong>Балдин Никита 6511</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/Nikita-Baldin/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:7215/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}") = "VehicleApp.AppHost", "VehicleApp\VehicleApp.AppHost\VehicleApp.AppHost.csproj", "{EF467773-3428-4934-B614-77783EAE4FA3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleApp.ServiceDefaults", "VehicleApp\VehicleApp.ServiceDefaults\VehicleApp.ServiceDefaults.csproj", "{97B1F7F0-C53D-2D4D-3803-B1150F873870}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VehicleApp.Api", "VehicleApp.Api\VehicleApp.Api.csproj", "{54C02CF3-616B-EC3E-6F35-EAF0ED92B6B0}"
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
{EF467773-3428-4934-B614-77783EAE4FA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EF467773-3428-4934-B614-77783EAE4FA3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EF467773-3428-4934-B614-77783EAE4FA3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EF467773-3428-4934-B614-77783EAE4FA3}.Release|Any CPU.Build.0 = Release|Any CPU
{97B1F7F0-C53D-2D4D-3803-B1150F873870}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{97B1F7F0-C53D-2D4D-3803-B1150F873870}.Debug|Any CPU.Build.0 = Debug|Any CPU
{97B1F7F0-C53D-2D4D-3803-B1150F873870}.Release|Any CPU.ActiveCfg = Release|Any CPU
{97B1F7F0-C53D-2D4D-3803-B1150F873870}.Release|Any CPU.Build.0 = Release|Any CPU
{54C02CF3-616B-EC3E-6F35-EAF0ED92B6B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{54C02CF3-616B-EC3E-6F35-EAF0ED92B6B0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{54C02CF3-616B-EC3E-6F35-EAF0ED92B6B0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{54C02CF3-616B-EC3E-6F35-EAF0ED92B6B0}.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