Skip to content
Closed
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="..\SoftwareProjects\SoftwareProjects.ServiceDefaults\SoftwareProjects.ServiceDefaults.csproj" />
</ItemGroup>

</Project>
54 changes: 54 additions & 0 deletions Api.Gateway/LoadBalancers/WeightedRandomLoadBalancer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using Ocelot.LoadBalancer.Interfaces;
using Ocelot.Responses;
using Ocelot.Values;

namespace Api.Gateway.LoadBalancers;

/// <summary>
/// Балансировщик нагрузки на основе взвешенного случайного выбора (Weighted Random).
/// Каждой реплике назначается вероятность выбора. При поступлении запроса
/// реплика выбирается случайно с учётом заданных вероятностей.
/// Веса задаются в appsettings.json в секции "WeightedRandomWeights".
/// </summary>
/// <param name="services">Фабрика для получения списка доступных сервисов.</param>
/// <param name="configuration">Конфигурация приложения для чтения весов из секции "WeightedRandomWeights".</param>
public class WeightedRandomLoadBalancer(Func<Task<List<Service>>> services, IConfiguration configuration) : ILoadBalancer
{
private readonly double[] _cumulativeWeights = BuildCumulativeWeights(
configuration.GetSection("WeightedRandomWeights").Get<double[]>() ?? [0.4, 0.3, 0.15, 0.1, 0.05]);

public string Type => nameof(WeightedRandomLoadBalancer);

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

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

var index = Array.BinarySearch(_cumulativeWeights, Random.Shared.NextDouble());
if (index < 0) index = ~index;

return new OkResponse<ServiceHostAndPort>(
availableServices[Math.Min(index, availableServices.Count - 1)].HostAndPort);
}

public void Release(ServiceHostAndPort hostAndPort) { }

/// <summary>
/// Строит массив кумулятивных весов на основе входных весов.
/// Каждый элемент результирующего массива равен сумме всех предыдущих весов включительно.
/// Используется для выбора реплики методом бинарного поиска по случайному числу.
/// </summary>
/// <param name="weights">Массив весов для каждой реплики.</param>
/// <returns>Массив кумулятивных весов.</returns>
private static double[] BuildCumulativeWeights(double[] weights)
{
var total = weights.Sum();
var cumulative = new double[weights.Length];
cumulative[0] = weights[0] / total;
for (var i = 1; i < weights.Length; i++)
cumulative[i] = cumulative[i - 1] + weights[i] / total;
return cumulative;
}
}
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.LoadBalancers;
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 WeightedRandomLoadBalancer(provider.GetAsync, sp.GetRequiredService<IConfiguration>()));

var trustedOrigins = builder.Configuration
.GetSection("TrustedOrigins")
.Get<string[]>() ?? [];

builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.WithOrigins(trustedOrigins)
.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:64729",
"sslPort": 44359
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5025",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7081;http://localhost:5025",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
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"
}
}
}
14 changes: 14 additions & 0 deletions Api.Gateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"TrustedOrigins": [
"http://localhost:5127",
"https://localhost:7282"
],
"WeightedRandomWeights": [ 0.30, 0.25, 0.20, 0.15, 0.10 ]
}
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": "/software-projects",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/api/software-projects",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 5200 },
{ "Host": "localhost", "Port": 5201 },
{ "Host": "localhost", "Port": 5202 },
{ "Host": "localhost", "Port": 5203 },
{ "Host": "localhost", "Port": 5204 }
],
"LoadBalancerOptions": {
"Type": "WeightedRandomLoadBalancer"
}
}
]
}
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>№39 "Программный проект"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнил <Strong>Жидяев Дмитрий 6513</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/Dmitrii14/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:7081/software-projects"
}
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}") = "SoftwareProjects.AppHost", "SoftwareProjects\SoftwareProjects.AppHost\SoftwareProjects.AppHost.csproj", "{EC51E772-B7D1-4185-86B3-9E0ACF79C521}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SoftwareProjects.ServiceDefaults", "SoftwareProjects\SoftwareProjects.ServiceDefaults\SoftwareProjects.ServiceDefaults.csproj", "{D568B20D-5F65-3DB5-3289-0CA101BC09FE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SoftwareProjects.Api", "SoftwareProjects.Api\SoftwareProjects.Api.csproj", "{D333DF66-6F24-76D8-CFA9-228C3368FF0D}"
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
{EC51E772-B7D1-4185-86B3-9E0ACF79C521}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EC51E772-B7D1-4185-86B3-9E0ACF79C521}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EC51E772-B7D1-4185-86B3-9E0ACF79C521}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EC51E772-B7D1-4185-86B3-9E0ACF79C521}.Release|Any CPU.Build.0 = Release|Any CPU
{D568B20D-5F65-3DB5-3289-0CA101BC09FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D568B20D-5F65-3DB5-3289-0CA101BC09FE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D568B20D-5F65-3DB5-3289-0CA101BC09FE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D568B20D-5F65-3DB5-3289-0CA101BC09FE}.Release|Any CPU.Build.0 = Release|Any CPU
{D333DF66-6F24-76D8-CFA9-228C3368FF0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D333DF66-6F24-76D8-CFA9-228C3368FF0D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D333DF66-6F24-76D8-CFA9-228C3368FF0D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D333DF66-6F24-76D8-CFA9-228C3368FF0D}.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