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>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

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

<ItemGroup>
<ProjectReference Include="..\Cloud.ServiceDefaults\Cloud.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>
/// Балансировщик нагрузки на основе взвешенного случайного выбора (Weighted Random).
/// Каждой реплике назначается вероятность выбора. При поступлении запроса реплика выбирается случайно с учётом заданных вероятностей
/// </summary>
/// <param name="services">Фабрика для получения списка доступных сервисов</param>
/// <param name="configuration">Конфигурация приложения</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;
}
}
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.LoadBalancers;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
options.AddPolicy("LocalPolicy", policy =>
{
policy
.SetIsOriginAllowed(origin => origin.StartsWith("https://localhost"))
.WithHeaders("Content-Type")
.WithMethods("GET");
});
});

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

builder.Services
.AddOcelot(builder.Configuration)
.AddCustomLoadBalancer((sp, _, discoveryProvider) =>
{
var configuration = sp.GetRequiredService<IConfiguration>();
return new WeightedRandomLoadBalancer(discoveryProvider.GetAsync, configuration);
});

var app = builder.Build();

app.UseCors("LocalPolicy");
await app.UseOcelot();

await app.RunAsync();
23 changes: 23 additions & 0 deletions API.Gateway/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5296",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7270;http://localhost:5296",
"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"
}
}
}
10 changes: 10 additions & 0 deletions API.Gateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"WeightedRandomWeights": [ 0.30, 0.25, 0.20, 0.15, 0.10 ]
}
36 changes: 36 additions & 0 deletions API.Gateway/ocelot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"Routes": [
{
"UpstreamPathTemplate": "/employee",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/employee",
"DownstreamScheme": "https",
"LoadBalancerOptions": {
"Type": "WeightedRandomLoadBalancer"
},
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8000
},
{
"Host": "localhost",
"Port": 8001
},
{
"Host": "localhost",
"Port": 8002
},
{
"Host": "localhost",
"Port": 8003
},
{
"Host": "localhost",
"Port": 8004
}
]
}
]
}

6 changes: 3 additions & 3 deletions Client.Wasm/Client.Wasm.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
Expand All @@ -14,8 +14,8 @@
<PackageReference Include="Blazorise" Version="1.8.8" />
<PackageReference Include="Blazorise.Bootstrap" Version="1.8.8" />
<PackageReference Include="Blazorise.Icons.FontAwesome" Version="1.8.8" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="8.0.22" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="8.0.22" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="10.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="10.0.7" PrivateAssets="all" />
</ItemGroup>

</Project>
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>№48 "Weighted Random"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнена <Strong>Ненашевым Дмитрием 6513</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/neygenius/cloud-development/">Ссылка на форк</Link></UnorderedListItem>
</UnorderedList>
</CardBody>
</Card>
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:7270/employee"
}
19 changes: 19 additions & 0 deletions Cloud.API/Cloud.API.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

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

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

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

</Project>
39 changes: 39 additions & 0 deletions Cloud.API/Controllers/EmployeeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Cloud.Api.Services;
using Cloud.Api.Models;
using Microsoft.AspNetCore.Mvc;

namespace Cloud.Api.Controllers;

/// <summary>
/// Контроллер для получения сотрудника компании по id
/// </summary>
/// <param name="employeeService">Сервис получения сотрудника компании</param>
/// <param name="logger">Логгер</param>
[ApiController]
[Route("employee")]
public class EmployeesController(
IEmployeeService employeeService,
ILogger<EmployeesController> logger
) : ControllerBase
{
/// <summary>
/// Метод для получения сотрудника компании по id
/// </summary>
/// <param name="id">Идентификатор сотрудника</param>
/// <returns>Информация о сотруднике компании</returns>
/// <response code="200">Успешное получение сотрудника компании</response>
/// <response code="400">Некорректный id сотрудника</response>
[ProducesResponseType(typeof(Employee), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
[HttpGet]
public async Task<ActionResult<Employee>> GetEmployee([FromQuery] int id)
{
if (id <= 0)
return BadRequest(new { error = "Id must be a positive number" });

logger.LogInformation("HTTP GET /employee, id: {employeeId}", id);

var employee = await employeeService.GetOrGenerateAsync(id);
return Ok(employee);
}
}
48 changes: 48 additions & 0 deletions Cloud.API/Models/Employee.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
namespace Cloud.Api.Models;

/// <summary>
/// Информация о сотруднике компании
/// </summary>
public class Employee
{
/// <summary>
/// Идентификатор сотрудника в системе
/// </summary>
public required int Id { get; set; }
/// <summary>
/// ФИО
/// </summary>
public required string FullName { get; set; }
/// <summary>
/// Должность
/// </summary>
public required string Position { get; set; }
/// <summary>
/// Отдел
/// </summary>
public required string Department { get; set; }
/// <summary>
/// Дата приема
/// </summary>
public DateOnly HireDate { get; set; }
/// <summary>
/// Зарплата
/// </summary>
public required decimal Salary { get; set; }
/// <summary>
/// Электронная почта
/// </summary>
public required string Email { get; set; }
/// <summary>
/// Номер телефона
/// </summary>
public required string PhoneNumber { get; set; }
/// <summary>
/// Индикатор увольнения
/// </summary>
public required bool IsFired { get; set; }
/// <summary>
/// Дата увольнения
/// </summary>
public DateOnly? FiredDate { get; set; }
}
28 changes: 28 additions & 0 deletions Cloud.API/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Cloud.Api.Services;

var builder = WebApplication.CreateBuilder(args);

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

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

builder.Services.AddSingleton<IEmployeeGenerator, EmployeeGenerator>();
builder.Services.AddScoped<IEmployeeService, EmployeeService>();

var app = builder.Build();

app.MapDefaultEndpoints();

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

app.UseHttpsRedirection();
app.MapControllers();

app.Run();
Loading