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

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

namespace Api.Gateway.LoadBalancers;

/// <summary>
/// Балансировщик нагрузки, выбирающий downstream-сервис случайным образом с учётом весов.
/// Чем больше вес у сервиса, тем выше вероятность его выбора.
/// Веса задаются в конфигурации (<c>WeightedRandom:Weights</c>) и применяются к сервисам в порядке их перечисления в маршруте Ocelot.
/// </summary>
/// <param name="services">Фабричная функция получения списка downstream-сервисов.</param>
/// <param name="configuration">Конфигурация приложения с секцией весов.</param>
public class WeightedRandom(Func<Task<List<Service>>> services, IConfiguration configuration) : ILoadBalancer
{
private static readonly object _locker = new();
private readonly int[] _weights = configuration
.GetSection("WeightedRandom:Weights")
.Get<int[]>() ?? [1, 1, 1, 1, 1];
private readonly Random _random = new(111);

public string Type => nameof(WeightedRandom);

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

if (serviceList.Count == 0)
throw new InvalidOperationException("Нет доступных сервисов");

lock (_locker)
{
var totalWeight = 0;
for (var i = 0; i < serviceList.Count; i++)
totalWeight += i < _weights.Length ? _weights[i] : 1;

var threshold = _random.Next(totalWeight);
var cumulative = 0;
for (var i = 0; i < serviceList.Count; i++)
{
cumulative += i < _weights.Length ? _weights[i] : 1;
if (threshold < cumulative)
return new OkResponse<ServiceHostAndPort>(serviceList[i].HostAndPort);
}

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

public void Release(ServiceHostAndPort hostAndPort) { }
}
33 changes: 33 additions & 0 deletions Api.Gateway/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using Api.Gateway.LoadBalancers;
using CourseApp.ServiceDefaults;
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>()));

builder.Services.AddCors(options =>
{
options.AddPolicy("wasm", policy =>
{
policy.AllowAnyOrigin()
.WithMethods("GET")
.WithHeaders("Content-Type");
});
});

var app = builder.Build();

app.UseCors("wasm");

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:46205",
"sslPort": 44343
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5200",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7186;http://localhost:5200",
"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"
}
}
}
12 changes: 12 additions & 0 deletions Api.Gateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"WeightedRandom": {
"Weights": [ 5, 4, 3, 2, 1 ]
}
}
38 changes: 38 additions & 0 deletions Api.Gateway/ocelot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"Routes": [
{
"UpstreamPathTemplate": "/course",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/api/course",
"DownstreamScheme": "https",
"LoadBalancerOptions": {
"Type": "WeightedRandom"
},
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8000
},
{
"Host": "localhost",
"Port": 8001
},
{
"Host": "localhost",
"Port": 8002
},
{
"Host": "localhost",
"Port": 8003
},
{
"Host": "localhost",
"Port": 8004
}
]
}
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:7186"
}
}
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>№50 "Учебный курс"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнена <Strong>Сахаровой Дарьей 6513</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/daryaskhrv/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:7186/course"
}
34 changes: 32 additions & 2 deletions CloudDevelopment.sln
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36811.4
# Visual Studio Version 18
VisualStudioVersion = 18.3.11505.172
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}") = "CourseApp.Domain", "CourseApp.Domain\CourseApp.Domain.csproj", "{8DB96A31-4C80-448B-8E97-33930E7DD01C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.Api", "CourseApp.Api\CourseApp.Api.csproj", "{3E70AD66-1A84-425D-8EAA-23B820F3A292}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.ServiceDefaults", "CourseApp.ServiceDefaults\CourseApp.ServiceDefaults.csproj", "{FA3F9ED2-E039-4168-AA5E-1E49E771AD99}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.AppHost", "CourseApp.AppHost\CourseApp.AppHost.csproj", "{8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}"
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 +25,26 @@ 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
{8DB96A31-4C80-448B-8E97-33930E7DD01C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8DB96A31-4C80-448B-8E97-33930E7DD01C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8DB96A31-4C80-448B-8E97-33930E7DD01C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8DB96A31-4C80-448B-8E97-33930E7DD01C}.Release|Any CPU.Build.0 = Release|Any CPU
{3E70AD66-1A84-425D-8EAA-23B820F3A292}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3E70AD66-1A84-425D-8EAA-23B820F3A292}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3E70AD66-1A84-425D-8EAA-23B820F3A292}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3E70AD66-1A84-425D-8EAA-23B820F3A292}.Release|Any CPU.Build.0 = Release|Any CPU
{FA3F9ED2-E039-4168-AA5E-1E49E771AD99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FA3F9ED2-E039-4168-AA5E-1E49E771AD99}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FA3F9ED2-E039-4168-AA5E-1E49E771AD99}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FA3F9ED2-E039-4168-AA5E-1E49E771AD99}.Release|Any CPU.Build.0 = Release|Any CPU
{8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8874AAD8-BCC8-4E48-B7AB-C39E7B5F0F53}.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
22 changes: 22 additions & 0 deletions CourseApp.Api/Controllers/CourseController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using CourseApp.Api.Services;
using CourseApp.Domain.Entity;
using Microsoft.AspNetCore.Mvc;

namespace CourseApp.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class CourseController(CourseService _courseService) : ControllerBase
{
/// <summary>
/// Получить курс по идентификатору
/// </summary>
/// <param name="id">Идентификатор курса</param>
/// <returns>Информация о курсе</returns>
[HttpGet]
public async Task<ActionResult<Course>> Get(int id)
{
var course = await _courseService.GetCourseAsync(id);
return Ok(course);
}
}
20 changes: 20 additions & 0 deletions CourseApp.Api/CourseApp.Api.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

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

<ItemGroup>
<PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="13.1.1" />
<PackageReference Include="Bogus" Version="35.6.5" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>

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

</Project>
28 changes: 28 additions & 0 deletions CourseApp.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using CourseApp.Api.Services;
using CourseApp.ServiceDefaults;

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();
builder.AddRedisDistributedCache("redis");

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddSingleton<CourseGenerator>();
builder.Services.AddScoped<CourseService>();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.MapDefaultEndpoints();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Loading
Loading