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

<ProjectExtensions><VisualStudio><UserProperties ocelot_1json__JsonSchema="" /></VisualStudio></ProjectExtensions>

</Project>
43 changes: 43 additions & 0 deletions Api.Gateway/Balancing/WeightedRoundRobin.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using Microsoft.Extensions.Configuration;
using Ocelot.LoadBalancer.Interfaces;
using Ocelot.Responses;
using Ocelot.Values;

namespace Api.Gateway.Balancing;

/// <summary>
/// Реализация алгоритма балансировки нагрузки "Взвешенный круговой обход" (Weighted Round Robin).
/// </summary>
/// <param name="services"></param>
/// <param name="configuration"></param>
public class WeightedRoundRobin(Func<Task<List<Service>>> services, IConfiguration configuration) : ILoadBalancer
{
private static readonly object _locker = new();

private readonly int[] _weights = configuration
.GetSection("WeightsRoundRobin")
.Get<int[]>() ?? [1, 2, 3, 4, 5];
private int _lastIndex = 0;
private int _currentWeight = 0;

public string Type => nameof(WeightedRoundRobin);

public async Task<Response<ServiceHostAndPort>> LeaseAsync(HttpContext httpContext)
{
var servicesList = await services();
if (servicesList.Count == 0)
throw new InvalidOperationException("No available downstream services");
lock (_locker)
{
if(_currentWeight >= _weights[_lastIndex])
{
_currentWeight = 0;
_lastIndex = (_lastIndex +1 >= _weights.Length) ? 0 : _lastIndex + 1;
}
_currentWeight++;
return new OkResponse<ServiceHostAndPort>(servicesList[_lastIndex].HostAndPort);
}
}

public void Release(ServiceHostAndPort hostAndPort) { }
}
40 changes: 40 additions & 0 deletions Api.Gateway/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using Api.Gateway.Balancing;
using CloudDevelopment.ServiceDefaults;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

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

var overrides = new Dictionary<string, string?>();
for (var i = 0; Environment.GetEnvironmentVariable($"services__service-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();
}

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

builder.Services.AddOcelot()
.AddCustomLoadBalancer((sp, _, provider) =>
new WeightedRoundRobin(provider.GetAsync, sp.GetRequiredService<IConfiguration>()));

builder.Services.AddCors(options => options.AddDefaultPolicy(policy =>
{
policy.AllowAnyOrigin();
policy.AllowAnyMethod();
policy.AllowAnyHeader();
}));

builder.AddServiceDefaults();
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:35010",
"sslPort": 44322
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5293",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7121;http://localhost:5293",
"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"
}
}
}
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": "*",
"WeightsRoundRobin": [ 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": "/study-course",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/api/study-course",
"DownstreamScheme": "https",
"LoadBalancerOptions": {
"Type": "WeightedRoundRobin"
},
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5666
},
{
"Host": "localhost",
"Port": 5667
},
{
"Host": "localhost",
"Port": 5668
},
{
"Host": "localhost",
"Port": 5669
},
{
"Host": "localhost",
"Port": 5670
}
]
}
]
}
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>№10 "Учебный Курс"</Strong></UnorderedListItem>
<UnorderedListItem>Выполнена <Strong>Марининым Андреем 6511</Strong> </UnorderedListItem>
<UnorderedListItem><Link To="https://github.com/andrM66/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:7121/study-course"
}
26 changes: 26 additions & 0 deletions CloudDevelopment.AppHost/CloudDevelopment.AppHost.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">

<Sdk Name="Aspire.AppHost.Sdk" Version="9.5.2" />

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireHost>true</IsAspireHost>
<UserSecretsId>f765995e-9d3a-45b8-96dc-a5dc50cd0089</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting" Version="9.5.2" />
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.5.2" />
<PackageReference Include="Aspire.Hosting.Redis" Version="9.5.2" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Api.Gateway\Api.Gateway.csproj" />
<ProjectReference Include="..\Service.Api\Service.Api.csproj" />
<ProjectReference Include="..\Client.Wasm\Client.Wasm.csproj" />
</ItemGroup>

</Project>
19 changes: 19 additions & 0 deletions CloudDevelopment.AppHost/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddRedis("course-cache")
.WithRedisInsight(containerName: "course-insight");
var gateway = builder.AddProject<Projects.Api_Gateway>("api-gateway");

for(var i = 0; i < 5; i++)
{
var service = builder.AddProject<Projects.Service_Api>($"service-api-{i}", launchProfileName:null)
.WithReference(cache, "RedisCache")
.WaitFor(cache)
.WithHttpsEndpoint(port:5666+i);
gateway.WaitFor(service).WithReference(service);
}

builder.AddProject<Projects.Client_Wasm>("client")
.WaitFor(gateway);

builder.Build().Run();
29 changes: 29 additions & 0 deletions CloudDevelopment.AppHost/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:17010;http://localhost:15047",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21117",
"DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22258"
}
},
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:15047",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19001",
"DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20248"
}
}
}
}
8 changes: 8 additions & 0 deletions CloudDevelopment.AppHost/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions CloudDevelopment.AppHost/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Aspire.Hosting.Dcp": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">

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

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />

<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="9.0.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
</ItemGroup>

</Project>
Loading
Loading