-
Notifications
You must be signed in to change notification settings - Fork 50
Жидяев Дмитрий Лаб. 2 Группа 6513 #76
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
alxmcs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| 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) | ||
alxmcs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| 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; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| } | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,5 +6,5 @@ | |
| } | ||
| }, | ||
| "AllowedHosts": "*", | ||
| "BaseAddress": "" | ||
| "BaseAddress": "https://localhost:7081/software-projects" | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.