-
Notifications
You must be signed in to change notification settings - Fork 49
Карпачева Полина Лаб. 2 Группа 6512 #33
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
Open
PolinaKrp
wants to merge
35
commits into
itsecd:main
Choose a base branch
from
PolinaKrp:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
35 commits
Select commit
Hold shift + click to select a range
9ad2ccd
лабораторная 1
PolinaKrp c4c60f4
Update setup_pr.yml
PolinaKrp e68541a
Update setup_pr.yml
PolinaKrp 84d9ec8
Update launchSettings.json
PolinaKrp 793e167
Delete .DS_Store
PolinaKrp 4c2c530
Delete AspireApp.EmptyService directory
PolinaKrp 7aa21f3
Delete AspireApp.Web directory
PolinaKrp 834e450
правки
PolinaKrp a04c423
Delete .DS_Store
PolinaKrp ed0e3b7
Delete global.json
PolinaKrp 421a083
net10.0, удалила using, настроила cors
PolinaKrp 5604532
Update .DS_Store
PolinaKrp 64625d4
Merge branch 'main' of https://github.com/PolinaKrp/cloud-development
PolinaKrp 347e0ac
добавила файл DS_Store в gitignore
PolinaKrp 4e7668e
Delete AspireApp.ApiService/.DS_Store
PolinaKrp 12c2ad2
Update Client.Wasm.csproj
PolinaKrp 997adf6
Delete AspireApp.ServiceDefaults/.DS_Store
PolinaKrp 66d6046
Update Program.cs
PolinaKrp 069f253
Update Client.Wasm.csproj
PolinaKrp a5f252a
лр 2
PolinaKrp f234550
Merge branch 'main' of https://github.com/PolinaKrp/cloud-development
PolinaKrp 5f98602
Delete .DS_Store
PolinaKrp 0ec1fcd
Delete AspireApp.ApiGateway/.DS_Store
PolinaKrp 1cf3861
Delete AspireApp.AppHost/.DS_Store
PolinaKrp 9f158a2
Delete Client.Wasm/.DS_Store
PolinaKrp ee121fd
fix
PolinaKrp 23cc81b
Update .DS_Store
PolinaKrp 05f06d4
Merge branch 'main' of https://github.com/PolinaKrp/cloud-development
PolinaKrp 483e507
Update WeightedRandomLoadBalancer.cs
PolinaKrp a11ab57
fix
PolinaKrp 902ca74
Update WeightedRandomLoadBalancer.cs
PolinaKrp baa9534
правки
PolinaKrp 806377b
Merge branch 'main' of https://github.com/PolinaKrp/cloud-development
PolinaKrp b947e8c
правки в WeightedRandomLoadBalancer
PolinaKrp 22d8781
исправление косяков с балансировщиком
PolinaKrp 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
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 |
|---|---|---|
|
|
@@ -416,3 +416,5 @@ FodyWeavers.xsd | |
| *.msix | ||
| *.msm | ||
| *.msp | ||
|
|
||
| .DS_Store | ||
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,13 @@ | ||
| <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> | ||
|
|
||
| </Project> |
50 changes: 50 additions & 0 deletions
50
AspireApp.ApiGateway/LoadBalancing/WeightedRandomLoadBalancer.cs
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,50 @@ | ||
| using Microsoft.AspNetCore.Http; | ||
| using Ocelot.LoadBalancer.Interfaces; | ||
| using Ocelot.Responses; | ||
| using Ocelot.Values; | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace AspireApp.ApiGateway.LoadBalancing; | ||
|
|
||
| /// <summary> | ||
| /// Weighted Random балансировщик нагрузки. | ||
| /// Распределяет запросы между сервисами по заданным весам. | ||
| /// </summary> | ||
| public class WeightedRandomLoadBalancer(List<Service> services) : ILoadBalancer | ||
| { | ||
| private readonly List<Service> _services = services; | ||
| private readonly List<int> _weights = services.Select(s => GetWeight(s)).ToList(); | ||
| private readonly Random _random = new(); | ||
|
|
||
| private static int GetWeight(Service service) | ||
| { | ||
| var port = service.HostAndPort.DownstreamPort; | ||
| return port == 5001 ? 5 : port == 5002 ? 3 : port == 5003 ? 2 : 1; | ||
| } | ||
|
|
||
| public async Task<Response<ServiceHostAndPort>> LeaseAsync(HttpContext httpContext) | ||
| { | ||
| var totalWeight = _weights.Sum(); | ||
| var randomValue = _random.Next(totalWeight); | ||
|
|
||
| var current = 0; | ||
| for (var i = 0; i < _services.Count; i++) | ||
| { | ||
| current += _weights[i]; | ||
| if (randomValue < current) | ||
| { | ||
| return new OkResponse<ServiceHostAndPort>(_services[i].HostAndPort); | ||
| } | ||
| } | ||
|
|
||
| return new OkResponse<ServiceHostAndPort>(_services.First().HostAndPort); | ||
| } | ||
|
|
||
| public void Release(ServiceHostAndPort hostAndPort) {} | ||
|
|
||
| public string Name => nameof(WeightedRandomLoadBalancer); | ||
| public string Type => "WeightedRandom"; | ||
| } |
24 changes: 24 additions & 0 deletions
24
AspireApp.ApiGateway/LoadBalancing/WeightedRandomLoadBalancerFactory.cs
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,24 @@ | ||
| using Ocelot.Configuration; | ||
| using Ocelot.LoadBalancer.Interfaces; | ||
| using Ocelot.Responses; | ||
| using Ocelot.Values; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
|
|
||
| namespace AspireApp.ApiGateway.LoadBalancing; | ||
|
|
||
| /// <summary> | ||
| /// Фабрика для создания WeightedRandomLoadBalancer. | ||
| /// </summary> | ||
|
|
||
| public class WeightedRandomLoadBalancerFactory : ILoadBalancerFactory | ||
| { | ||
| public Response<ILoadBalancer> Get(DownstreamRoute route, ServiceProviderConfiguration serviceProviderConfiguration) | ||
| { | ||
| var services = route.DownstreamAddresses | ||
| .Select(x => new Service("service", new ServiceHostAndPort(x.Host, x.Port), "", "", new List<string>())) | ||
| .ToList(); | ||
|
|
||
| return new OkResponse<ILoadBalancer>(new WeightedRandomLoadBalancer(services)); | ||
| } | ||
| } |
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,29 @@ | ||
| using Ocelot.DependencyInjection; | ||
| using Ocelot.Middleware; | ||
| using Ocelot.LoadBalancer.Interfaces; | ||
| using AspireApp.ApiGateway.LoadBalancing; | ||
|
|
||
| var builder = WebApplication.CreateBuilder(args); | ||
|
|
||
| builder.Services.AddCors(options => | ||
| { | ||
| options.AddPolicy("AllowClient", policy => | ||
| { | ||
| policy.WithOrigins("http://localhost:5127") | ||
| .AllowAnyMethod() | ||
| .AllowAnyHeader(); | ||
| }); | ||
| }); | ||
|
|
||
| builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true); | ||
|
|
||
| builder.Services.AddOcelot(); | ||
| builder.Services.AddSingleton<ILoadBalancerFactory, WeightedRandomLoadBalancerFactory>(); | ||
|
|
||
| var app = builder.Build(); | ||
|
|
||
| app.UseCors("AllowClient"); | ||
|
|
||
| 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,13 @@ | ||
| { | ||
| "profiles": { | ||
| "http": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": false, | ||
| "applicationUrl": "http://localhost:5101", | ||
| "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,9 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| }, | ||
| "AllowedHosts": "*" | ||
| } |
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,24 @@ | ||
| { | ||
| "Routes": [ | ||
| { | ||
| "DownstreamPathTemplate": "/warehouse", | ||
| "DownstreamScheme": "http", | ||
| "DownstreamHostAndPorts": [ | ||
| { "Host": "localhost", "Port": 5001 }, | ||
| { "Host": "localhost", "Port": 5002 }, | ||
| { "Host": "localhost", "Port": 5003 } | ||
| ], | ||
| "UpstreamPathTemplate": "/warehouse", | ||
| "UpstreamHttpMethod": [ "GET" ], | ||
| "LoadBalancerOptions": { | ||
| "Type": "WeightedRandom" | ||
| }, | ||
| "HttpHandlerOptions": { | ||
| "UseTracing": true | ||
| } | ||
| } | ||
| ], | ||
| "GlobalConfiguration": { | ||
| "BaseUrl": "http://localhost:5101" | ||
| } | ||
| } |
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,19 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net10.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\AspireApp.ServiceDefaults\AspireApp.ServiceDefaults.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="9.5.2" /> | ||
| <PackageReference Include="Bogus" Version="35.6.5" /> | ||
| <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.15" /> | ||
| </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,69 @@ | ||
| using System.Text.Json.Serialization; | ||
|
|
||
| namespace AspireApp.ApiService.Entities; | ||
|
|
||
| /// <summary> | ||
| /// Товар на складе | ||
| /// </summary> | ||
| public class Warehouse | ||
| { | ||
| /// <summary> | ||
| /// Идентификатор | ||
| /// </summary> | ||
| [JsonPropertyName("id")] | ||
| public int Id { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Наименование товара | ||
| /// </summary> | ||
| [JsonPropertyName("name")] | ||
| public string? Name { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Категория товара | ||
| /// </summary> | ||
| [JsonPropertyName("category")] | ||
| public string? Category { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Количество на складе | ||
| /// </summary> | ||
| [JsonPropertyName("stockQuantity")] | ||
| public int StockQuantity { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Цена за единицу товара | ||
| /// </summary> | ||
| [JsonPropertyName("price")] | ||
| public decimal Price { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Вес единицы товара | ||
| /// </summary> | ||
| [JsonPropertyName("weight")] | ||
| public double Weight { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Габариты единицы товара | ||
| /// </summary> | ||
| [JsonPropertyName("dimensions")] | ||
| public string? Dimensions { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Хрупкий ли товар | ||
| /// </summary> | ||
| [JsonPropertyName("isFragile")] | ||
| public bool IsFragile { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Дата последней поставки | ||
| /// </summary> | ||
| [JsonPropertyName("lastDeliveryDate")] | ||
| public DateOnly LastDeliveryDate { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Дата следующей планируемой поставки | ||
| /// </summary> | ||
| [JsonPropertyName("nextDeliveryDate")] | ||
| public DateOnly NextDeliveryDate { get; set; } | ||
| } |
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,19 @@ | ||
| using AspireApp.ApiService.Entities; | ||
|
|
||
| namespace AspireApp.ApiService.Generator; | ||
|
|
||
| /// <summary> | ||
| /// Интерфейс для работы с кэшем товаров | ||
| /// </summary> | ||
| public interface IWarehouseCache | ||
| { | ||
| /// <summary> | ||
| /// Получить товар из кэша по идентификатору | ||
| /// </summary> | ||
| Task<Warehouse?> GetAsync(int id); | ||
|
|
||
| /// <summary> | ||
| /// Сохранить товар в кэш | ||
| /// </summary> | ||
| Task SetAsync(Warehouse warehouse); | ||
| } |
11 changes: 11 additions & 0 deletions
11
AspireApp.ApiService/Generator/IWarehouseGeneratorService.cs
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,11 @@ | ||
| using AspireApp.ApiService.Entities; | ||
|
|
||
| namespace AspireApp.ApiService.Generator; | ||
|
|
||
| /// <summary> | ||
| /// Сервис обработки товаров на складе | ||
| /// </summary> | ||
| public interface IWarehouseGeneratorService | ||
| { | ||
| Task<Warehouse> ProcessWarehouse(int id); | ||
| } |
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,47 @@ | ||
| using Microsoft.Extensions.Caching.Distributed; | ||
| using System.Text.Json; | ||
| using AspireApp.ApiService.Entities; | ||
|
|
||
| namespace AspireApp.ApiService.Generator; | ||
|
|
||
| /// <summary> | ||
| /// Кэширование товаров | ||
| /// </summary> | ||
| public class WarehouseCache( | ||
| IDistributedCache cache, | ||
| ILogger<WarehouseCache> logger, | ||
| IConfiguration configuration) : IWarehouseCache | ||
| { | ||
| private readonly TimeSpan _defaultExpiration = int.TryParse(configuration["CacheExpiration"], out var seconds) | ||
| ? TimeSpan.FromSeconds(seconds) | ||
| : TimeSpan.FromSeconds(3600); | ||
|
|
||
| public async Task<Warehouse?> GetAsync(int id) | ||
| { | ||
| var key = $"warehouse_{id}"; | ||
| var cached = await cache.GetStringAsync(key); | ||
| if (cached == null) | ||
| return null; | ||
|
|
||
| try | ||
| { | ||
| return JsonSerializer.Deserialize<Warehouse>(cached); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Ошибка десериализации товара {Id} из кэша", id); | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| public async Task SetAsync(Warehouse warehouse) | ||
| { | ||
| var key = $"warehouse_{warehouse.Id}"; | ||
| var options = new DistributedCacheEntryOptions | ||
| { | ||
| AbsoluteExpirationRelativeToNow = _defaultExpiration | ||
| }; | ||
| var serialized = JsonSerializer.Serialize(warehouse); | ||
| await cache.SetStringAsync(key, serialized, options); | ||
| } | ||
| } |
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 Bogus; | ||
| using AspireApp.ApiService.Entities; | ||
|
|
||
| namespace AspireApp.ApiService.Generator; | ||
|
|
||
| /// <summary> | ||
| /// Генератор случайных товаров с использованием Bogus | ||
| /// </summary> | ||
| public class WarehouseGenerator | ||
| { | ||
| private readonly Faker<Warehouse> _faker; | ||
|
|
||
| public WarehouseGenerator() | ||
| { | ||
| _faker = new Faker<Warehouse>() | ||
| .RuleFor(w => w.Id, f => f.IndexFaker + 1) // будет перезаписан позже | ||
| .RuleFor(w => w.Name, f => f.Commerce.ProductName()) | ||
| .RuleFor(w => w.Category, f => f.Commerce.Categories(1)[0]) | ||
| .RuleFor(w => w.StockQuantity, f => f.Random.Int(0, 1000)) | ||
| .RuleFor(w => w.Price, f => decimal.Parse(f.Commerce.Price())) | ||
| .RuleFor(w => w.Weight, f => f.Random.Double(0.1, 50.0)) | ||
| .RuleFor(w => w.Dimensions, f => $"{f.Random.Int(10, 100)}x{f.Random.Int(10, 100)}x{f.Random.Int(10, 100)}") | ||
| .RuleFor(w => w.IsFragile, f => f.Random.Bool(0.3f)) | ||
| .RuleFor(w => w.LastDeliveryDate, f => DateOnly.FromDateTime(f.Date.Past(30))) | ||
| .RuleFor(w => w.NextDeliveryDate, f => DateOnly.FromDateTime(f.Date.Future(30))); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Генерирует один случайный товар (Id будет перезаписан вызывающим кодом) | ||
| /// </summary> | ||
| public Warehouse Generate() => _faker.Generate(); | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Добавить сюда
corsи убрать из сервиса