From 0bde0541e34176ad21312a8667cc424a5509d7fa Mon Sep 17 00:00:00 2001 From: Daryaskhrv Date: Thu, 19 Feb 2026 22:16:27 +0400 Subject: [PATCH 1/5] lab1 --- Client.Wasm/Components/StudentCard.razor | 8 +- Client.Wasm/wwwroot/appsettings.json | 2 +- CloudDevelopment.sln | 28 +++- CourseApp.Api/Controllers/CourseController.cs | 22 ++++ CourseApp.Api/CourseApp.Api.csproj | 20 +++ CourseApp.Api/Program.cs | 39 ++++++ CourseApp.Api/Properties/launchSettings.json | 41 ++++++ CourseApp.Api/Services/CourseGenerator.cs | 40 ++++++ CourseApp.Api/Services/CourseService.cs | 51 ++++++++ CourseApp.Api/appsettings.Development.json | 8 ++ CourseApp.Api/appsettings.json | 12 ++ CourseApp.AppHost/AppHost.cs | 23 ++++ CourseApp.AppHost/CourseApp.AppHost.csproj | 22 ++++ .../Properties/launchSettings.json | 31 +++++ .../appsettings.Development.json | 8 ++ CourseApp.AppHost/appsettings.json | 9 ++ CourseApp.Domain/CourseApp.Domain.csproj | 9 ++ CourseApp.Domain/Entity/CourseApp.cs | 57 +++++++++ .../CourseApp.ServiceDefaults.csproj | 24 ++++ CourseApp.ServiceDefaults/Extensions.cs | 120 ++++++++++++++++++ 20 files changed, 567 insertions(+), 7 deletions(-) create mode 100644 CourseApp.Api/Controllers/CourseController.cs create mode 100644 CourseApp.Api/CourseApp.Api.csproj create mode 100644 CourseApp.Api/Program.cs create mode 100644 CourseApp.Api/Properties/launchSettings.json create mode 100644 CourseApp.Api/Services/CourseGenerator.cs create mode 100644 CourseApp.Api/Services/CourseService.cs create mode 100644 CourseApp.Api/appsettings.Development.json create mode 100644 CourseApp.Api/appsettings.json create mode 100644 CourseApp.AppHost/AppHost.cs create mode 100644 CourseApp.AppHost/CourseApp.AppHost.csproj create mode 100644 CourseApp.AppHost/Properties/launchSettings.json create mode 100644 CourseApp.AppHost/appsettings.Development.json create mode 100644 CourseApp.AppHost/appsettings.json create mode 100644 CourseApp.Domain/CourseApp.Domain.csproj create mode 100644 CourseApp.Domain/Entity/CourseApp.cs create mode 100644 CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj create mode 100644 CourseApp.ServiceDefaults/Extensions.cs diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 661f1181..8acfba9d 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,10 +4,10 @@ - Номер №X "Название лабораторной" - Вариант №Х "Название варианта" - Выполнена Фамилией Именем 65ХХ - Ссылка на форк + Номер №1 Кэширование + Вариант №50 "Учебный курс" + Выполнена Сахаровой Дарьей 6513 + Ссылка на форк diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index d1fe7ab3..3e8284f6 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "" + "BaseAddress": "https://localhost:7068/api/course" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index cb48241d..c0634a98 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -1,10 +1,18 @@  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 d18.3 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 Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +23,22 @@ 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 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CourseApp.Api/Controllers/CourseController.cs b/CourseApp.Api/Controllers/CourseController.cs new file mode 100644 index 00000000..ac561bba --- /dev/null +++ b/CourseApp.Api/Controllers/CourseController.cs @@ -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 +{ + /// + /// Получить курс по идентификатору + /// + /// Идентификатор курса + /// Информация о курсе + [HttpGet] + public async Task> Get(int id) + { + var course = await _courseService.GetCourseAsync(id); + return Ok(course); + } +} \ No newline at end of file diff --git a/CourseApp.Api/CourseApp.Api.csproj b/CourseApp.Api/CourseApp.Api.csproj new file mode 100644 index 00000000..4fec257e --- /dev/null +++ b/CourseApp.Api/CourseApp.Api.csproj @@ -0,0 +1,20 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + + diff --git a/CourseApp.Api/Program.cs b/CourseApp.Api/Program.cs new file mode 100644 index 00000000..75c1fb87 --- /dev/null +++ b/CourseApp.Api/Program.cs @@ -0,0 +1,39 @@ +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.AddCors(options => +{ + options.AddPolicy("wasm", policy => + { + policy.AllowAnyOrigin() + .WithMethods("GET", "POST") + .WithHeaders("Content-Type"); + }); +}); + +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapDefaultEndpoints(); +app.UseHttpsRedirection(); +app.UseCors("wasm"); +app.UseAuthorization(); +app.MapControllers(); +app.Run(); \ No newline at end of file diff --git a/CourseApp.Api/Properties/launchSettings.json b/CourseApp.Api/Properties/launchSettings.json new file mode 100644 index 00000000..da1c7f77 --- /dev/null +++ b/CourseApp.Api/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:19002", + "sslPort": 44340 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5083", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7068;http://localhost:5083", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/CourseApp.Api/Services/CourseGenerator.cs b/CourseApp.Api/Services/CourseGenerator.cs new file mode 100644 index 00000000..4b758d70 --- /dev/null +++ b/CourseApp.Api/Services/CourseGenerator.cs @@ -0,0 +1,40 @@ +using Bogus; +using CourseApp.Domain.Entity; + +namespace CourseApp.Api.Services; + +public class CourseGenerator +{ + private static readonly string[] _courseNames = + [ + "C# для начинающих", + "Python для анализа данных", + "Микросервисная архитектура", + "Docker", + "Алгоритмы и структуры данных", + "SQL и базы данных", + "Автоматизированное тестирование", + "HTML+CSS Вёрстка сайтов" + ]; + + public Course Generate(int id) + { + var faker = new Faker("ru") + .RuleFor(c => c.Id, _ => id) + .RuleFor(c => c.Name, f => f.PickRandom(_courseNames)) + .RuleFor(c => c.TeacherFullName, f => f.Name.FullName()) + //f => $"{f.Name.LastName()} {f.Name.FirstName()} {f.Name.}") + .RuleFor(c => c.StartDate, f => f.Date.SoonDateOnly(30)) + .RuleFor(c => c.EndDate, (f, c) => + c.StartDate.AddDays(f.Random.Int(30, 180))) + .RuleFor(c => c.MaxStudents, f => f.Random.Int(10, 50)) + .RuleFor(c => c.CurrentStudents, (f, c) => + f.Random.Int(0, c.MaxStudents)) + .RuleFor(c => c.HasCertificate, f => f.Random.Bool()) + .RuleFor(c => c.Price, + f => Math.Round(f.Random.Decimal(5000, 10000), 2)) + .RuleFor(c => c.Rating, f => f.Random.Int(1, 5)); + + return faker.Generate(); + } +} \ No newline at end of file diff --git a/CourseApp.Api/Services/CourseService.cs b/CourseApp.Api/Services/CourseService.cs new file mode 100644 index 00000000..4a3afea7 --- /dev/null +++ b/CourseApp.Api/Services/CourseService.cs @@ -0,0 +1,51 @@ +using System.Text.Json; +using CourseApp.Domain.Entity; +using Microsoft.Extensions.Caching.Distributed; + +namespace CourseApp.Api.Services; + +public class CourseService(IDistributedCache _cache, IConfiguration _configuration, + ILogger _logger, CourseGenerator _generator) +{ + public async Task GetCourseAsync(int id) + { + + var cacheKey = $"course-{id}"; + _logger.LogInformation("Попытка получить курс {CourseId} из кэша",id); + var cachedData = await _cache.GetStringAsync(cacheKey); + + if (!string.IsNullOrEmpty(cachedData)) + { + try + { + var cachedCourse = JsonSerializer.Deserialize(cachedData); + + if (cachedCourse != null) + { + _logger.LogInformation("Курс {CourseId} успешно получен из кэша", id); + return cachedCourse; + } + _logger.LogWarning("Курс {CourseId} найден в кэше, но десериализация вернула null", id); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка десериализации курса {CourseId} из кэша", id); + } + } + + _logger.LogInformation("Курс {CourseId} отсутствует в кэше. Начинаем генерацию", id); + + var course = _generator.Generate(id); + var expirationMinutes = _configuration.GetValue("CacheSettings:ExpirationMinutes", 5); + + var cacheOptions = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes) + }; + + await _cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(course), cacheOptions); + _logger.LogInformation("Курс {CourseId} сгенерирован и сохранён в кэш", id); + + return course; + } +} \ No newline at end of file diff --git a/CourseApp.Api/appsettings.Development.json b/CourseApp.Api/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CourseApp.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CourseApp.Api/appsettings.json b/CourseApp.Api/appsettings.json new file mode 100644 index 00000000..0d4ec8d7 --- /dev/null +++ b/CourseApp.Api/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "CacheSettings": { + "ExpirationMinutes": 10 + }, + "AllowedHosts": "*" +} diff --git a/CourseApp.AppHost/AppHost.cs b/CourseApp.AppHost/AppHost.cs new file mode 100644 index 00000000..83ec3b84 --- /dev/null +++ b/CourseApp.AppHost/AppHost.cs @@ -0,0 +1,23 @@ +var builder = DistributedApplication.CreateBuilder(args); + +var redis = builder.AddRedis("redis"); + +var redisCommander = builder.AddContainer( + name: "redis-commander", + image: "rediscommander/redis-commander") + .WithEnvironment("REDIS_HOSTS", "local:redis:6379") + .WithReference(redis) + .WaitFor(redis) + .WithEndpoint(port: 8081, targetPort: 8081); + +var api = builder.AddProject("courseapp-api") + .WithReference(redis) + .WaitFor(redis) + .WithExternalHttpEndpoints(); + +builder.AddProject("client") + .WithReference(api) + .WaitFor(api) + .WithExternalHttpEndpoints(); + +builder.Build().Run(); \ No newline at end of file diff --git a/CourseApp.AppHost/CourseApp.AppHost.csproj b/CourseApp.AppHost/CourseApp.AppHost.csproj new file mode 100644 index 00000000..6c4a9501 --- /dev/null +++ b/CourseApp.AppHost/CourseApp.AppHost.csproj @@ -0,0 +1,22 @@ + + + + Exe + net8.0 + enable + enable + c086dba3-3e81-4540-916e-ccad1674fa30 + + + + + + + + + + + + + + diff --git a/CourseApp.AppHost/Properties/launchSettings.json b/CourseApp.AppHost/Properties/launchSettings.json new file mode 100644 index 00000000..ebedba73 --- /dev/null +++ b/CourseApp.AppHost/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:17164;http://localhost:15271", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21251", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23029", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22151" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:15271", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19248", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18141", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20080" + } + } + } +} diff --git a/CourseApp.AppHost/appsettings.Development.json b/CourseApp.AppHost/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/CourseApp.AppHost/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/CourseApp.AppHost/appsettings.json b/CourseApp.AppHost/appsettings.json new file mode 100644 index 00000000..31c092aa --- /dev/null +++ b/CourseApp.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/CourseApp.Domain/CourseApp.Domain.csproj b/CourseApp.Domain/CourseApp.Domain.csproj new file mode 100644 index 00000000..fa71b7ae --- /dev/null +++ b/CourseApp.Domain/CourseApp.Domain.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/CourseApp.Domain/Entity/CourseApp.cs b/CourseApp.Domain/Entity/CourseApp.cs new file mode 100644 index 00000000..4a618fdc --- /dev/null +++ b/CourseApp.Domain/Entity/CourseApp.cs @@ -0,0 +1,57 @@ +namespace CourseApp.Domain.Entity; + +/// +/// Модель учебного курса +/// +public class Course +{ + /// + /// Идентификатор курса в системе + /// + public int Id { get; set; } + + /// + /// Наименование курса + /// + public string Name { get; set; } = string.Empty; + + /// + /// ФИО преподавателя + /// + public string TeacherFullName { get; set; } = string.Empty; + + /// + /// Дата начала курса + /// + public DateOnly StartDate { get; set; } + + /// + /// Дата окончания курса + /// + public DateOnly EndDate { get; set; } + + /// + /// Максимальное количество студентов + /// + public int MaxStudents { get; set; } + + /// + /// Текущее количество записанных студентов + /// + public int CurrentStudents { get; set; } + + /// + /// Выдача сертификата + /// + public bool HasCertificate { get; set; } + + /// + /// Стоимость + /// + public decimal Price { get; set; } + + /// + /// Рейтинг + /// + public int Rating { get; set; } +} \ No newline at end of file diff --git a/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj b/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj new file mode 100644 index 00000000..7d677a24 --- /dev/null +++ b/CourseApp.ServiceDefaults/CourseApp.ServiceDefaults.csproj @@ -0,0 +1,24 @@ + + + + net8.0 + enable + enable + true + + + + + + + + + + + + + + + + + diff --git a/CourseApp.ServiceDefaults/Extensions.cs b/CourseApp.ServiceDefaults/Extensions.cs new file mode 100644 index 00000000..352a2abd --- /dev/null +++ b/CourseApp.ServiceDefaults/Extensions.cs @@ -0,0 +1,120 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace CourseApp.ServiceDefaults; + +/// +/// Общие настройки для сервисов Aspire: OpenTelemetry, Структурное логирование, Health checks +/// +public static class Extensions +{ + private const string HealthEndpointPath = "/health"; + private const string AlivenessEndpointPath = "/alive"; + + /// + /// Подключение всех стандартных сервисов Aspire + /// + public static TBuilder AddServiceDefaults(this TBuilder builder) + where TBuilder : IHostApplicationBuilder + { + builder.ConfigureOpenTelemetry(); + builder.AddDefaultHealthChecks(); + builder.Services.AddServiceDiscovery(); + + builder.Services.ConfigureHttpClientDefaults(http => + { + http.AddStandardResilienceHandler(); + http.AddServiceDiscovery(); + }); + + return builder; + } + + /// + /// Настройка OpenTelemetry (логирование, метрики, трейсинг) + /// + public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) + where TBuilder : IHostApplicationBuilder + { + builder.Logging.AddOpenTelemetry(logging => + { + logging.IncludeFormattedMessage = true; + logging.IncludeScopes = true; + }); + + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddAspNetCoreInstrumentation() + .AddHttpClientInstrumentation() + .AddRuntimeInstrumentation(); + }) + .WithTracing(tracing => + { + tracing.AddSource(builder.Environment.ApplicationName) + .AddAspNetCoreInstrumentation(options => + { + options.Filter = context => + !context.Request.Path.StartsWithSegments(HealthEndpointPath) && + !context.Request.Path.StartsWithSegments(AlivenessEndpointPath); + }) + .AddHttpClientInstrumentation(); + }); + + builder.AddOpenTelemetryExporters(); + + return builder; + } + + private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) + where TBuilder : IHostApplicationBuilder + { + var useOtlpExporter = + !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); + + if (useOtlpExporter) + { + builder.Services.AddOpenTelemetry() + .UseOtlpExporter(); + } + + return builder; + } + + /// + /// Добавление стандартных health checks + /// + public static TBuilder AddDefaultHealthChecks(this TBuilder builder) + where TBuilder : IHostApplicationBuilder + { + builder.Services.AddHealthChecks() + .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); + + return builder; + } + + /// + /// Подключение стандартных endpoint'ов (health) + /// + public static WebApplication MapDefaultEndpoints(this WebApplication app) + { + if (app.Environment.IsDevelopment()) + { + app.MapHealthChecks(HealthEndpointPath); + + app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions + { + Predicate = r => r.Tags.Contains("live") + }); + } + + return app; + } +} \ No newline at end of file From 79f2a2427293a70f634f1ddc2daf36ba869aa477 Mon Sep 17 00:00:00 2001 From: daryaskhrv <113370290+daryaskhrv@users.noreply.github.com> Date: Thu, 19 Feb 2026 22:21:40 +0400 Subject: [PATCH 2/5] Update README.md --- README.md | 133 ++---------------------------------------------------- 1 file changed, 5 insertions(+), 128 deletions(-) diff --git a/README.md b/README.md index dcaa5eb7..500a4c67 100644 --- a/README.md +++ b/README.md @@ -1,128 +1,5 @@ -# Современные технологии разработки программного обеспечения -[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing) - -## Задание -### Цель -Реализация проекта микросервисного бекенда. - -### Задачи -* Реализация межсервисной коммуникации, -* Изучение работы с брокерами сообщений, -* Изучение архитектурных паттернов, -* Изучение работы со средствами оркестрации на примере .NET Aspire, -* Повторение основ работы с системами контроля версий, -* Интеграционное тестирование. - -### Лабораторные работы -
-1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов -
- -В рамках первой лабораторной работы необходимо: -* Реализовать сервис генерации контрактов на основе Bogus, -* Реализовать кеширование при помощи IDistributedCache и Redis, -* Реализовать структурное логирование сервиса генерации, -* Настроить оркестрацию Aspire. - -
-
-2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы -
- -В рамках второй лабораторной работы необходимо: -* Настроить оркестрацию на запуск нескольких реплик сервиса генерации, -* Реализовать апи гейтвей на основе Ocelot, -* Имплементировать алгоритм балансировки нагрузки согласно варианту. - -
-
-
-3. «Интеграционное тестирование» - Реализация файлового сервиса и объектного хранилища, интеграционное тестирование бекенда -
- -В рамках третьей лабораторной работы необходимо: -* Добавить в оркестрацию объектное хранилище, -* Реализовать файловый сервис, сериализующий сгенерированные данные в файлы и сохраняющий их в объектном хранилище, -* Реализовать отправку генерируемых данных в файловый сервис посредством брокера, -* Реализовать интеграционные тесты, проверяющие корректность работы всех сервисов бекенда вместе. - -
-
-
-4. (Опционально) «Переход на облачную инфраструктуру» - Перенос бекенда в Yandex Cloud -
- -В рамках четвертой лабораторной работы необходимо перенестиервисы на облако все ранее разработанные сервисы: -* Клиент - в хостинг через отдельный бакет Object Storage, -* Сервис генерации - в Cloud Function, -* Апи гейтвей - в Serverless Integration как API Gateway, -* Брокер сообщений - в Message Queue, -* Файловый сервис - в Cloud Function, -* Объектное хранилище - в отдельный бакет Object Storage, - -
-
- -## Задание. Общая часть -**Обязательно**: -* Реализация серверной части на [.NET 8](https://learn.microsoft.com/ru-ru/dotnet/core/whats-new/dotnet-8/overview). -* Оркестрация проектов при помощи [.NET Aspire](https://learn.microsoft.com/ru-ru/dotnet/aspire/get-started/aspire-overview). -* Реализация сервиса генерации данных при помощи [Bogus](https://github.com/bchavez/Bogus). -* Реализация тестов с использованием [xUnit](https://xunit.net/?tabs=cs). -* Создание минимальной документации к проекту: страница на GitHub с информацией о задании, скриншоты приложения и прочая информация. - -**Факультативно**: -* Перенос бекенда на облачную инфраструктуру Yandex Cloud - -Внимательно прочитайте [дискуссии](https://github.com/itsecd/cloud-development/discussions/1) о том, как работает автоматическое распределение на ревью. -Сразу корректно называйте свои pr, чтобы они попали на ревью нужному преподавателю. - -По итогу работы в семестре должна получиться следующая информационная система: -
-C4 диаграмма -Современные_технологии_разработки_ПО_drawio -
- -## Варианты заданий -Номер варианта задания присваивается в начале семестра. Изменить его нельзя. Каждый вариант имеет уникальную комбинацию из предметной области, базы данных и технологии для общения сервиса генерации данных и сервера апи. - -[Список вариантов](https://docs.google.com/document/d/1WGmLYwffTTaAj4TgFCk5bUyW3XKbFMiBm-DHZrfFWr4/edit?usp=sharing) -[Список предметных областей и алгоритмов балансировки](https://docs.google.com/document/d/1PLn2lKe4swIdJDZhwBYzxqFSu0AbY2MFY1SUPkIKOM4/edit?usp=sharing) - -## Схема сдачи - -На каждую из лабораторных работ необходимо сделать отдельный [Pull Request (PR)](https://docs.github.com/en/pull-requests). - -Общая схема: -1. Сделать форк данного репозитория -2. Выполнить задание -3. Сделать PR в данный репозиторий -4. Исправить замечания после code review -5. Получить approve - -## Критерии оценивания - -Конкурентный принцип. -Так как задания в первой лабораторной будут повторяться между студентами, то выделяются следующие показатели для оценки: -1. Скорость разработки -2. Качество разработки -3. Полнота выполнения задания - -Быстрее делаете PR - у вас преимущество. -Быстрее получаете Approve - у вас преимущество. -Выполните нечто немного выходящее за рамки проекта - у вас преимущество. -Не укладываетесь в дедлайн - получаете минимально возможный балл. - -### Шкала оценивания - -- **3 балла** за качество кода, из них: - - 2 балла - базовая оценка - - 1 балл (но не более) можно получить за выполнение любого из следующих пунктов: - - Реализация факультативного функционала - - Выполнение работы раньше других: первые 5 человек из каждой группы, которые сделали PR и получили approve, получают дополнительный балл - -## Вопросы и обратная связь по курсу - -Чтобы задать вопрос по лабораторной, воспользуйтесь [соответствующим разделом дискуссий](https://github.com/itsecd/cloud-development/discussions/categories/questions) или заведите [ишью](https://github.com/itsecd/cloud-development/issues/new). -Если у вас появились идеи/пожелания/прочие полезные мысли по преподаваемой дисциплине, их можно оставить [здесь](https://github.com/itsecd/cloud-development/discussions/categories/ideas). - +# Сахарова Дарья 6513 +## Вариант 50 - Учебный курс +### Лабораторная работа №1 - Кэширование +Снимок экрана 2026-02-19 221447 +Снимок экрана 2026-02-19 221527 From ad3008c04e702727b32dff460a7580aa84cef09e Mon Sep 17 00:00:00 2001 From: Daryaskhrv Date: Thu, 19 Feb 2026 22:31:31 +0400 Subject: [PATCH 3/5] fix --- CourseApp.AppHost/AppHost.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/CourseApp.AppHost/AppHost.cs b/CourseApp.AppHost/AppHost.cs index 83ec3b84..99312342 100644 --- a/CourseApp.AppHost/AppHost.cs +++ b/CourseApp.AppHost/AppHost.cs @@ -12,12 +12,10 @@ var api = builder.AddProject("courseapp-api") .WithReference(redis) - .WaitFor(redis) - .WithExternalHttpEndpoints(); + .WaitFor(redis); builder.AddProject("client") .WithReference(api) - .WaitFor(api) - .WithExternalHttpEndpoints(); + .WaitFor(api); builder.Build().Run(); \ No newline at end of file From ca2d91ef53e670b35c6a9946d44de86837ffbc4d Mon Sep 17 00:00:00 2001 From: Daryaskhrv Date: Fri, 20 Feb 2026 18:15:00 +0400 Subject: [PATCH 4/5] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=87=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CourseApp.Api/Program.cs | 4 +-- CourseApp.Api/Services/CourseGenerator.cs | 40 +++++++++++++---------- CourseApp.Api/Services/CourseService.cs | 25 ++++++++++---- 3 files changed, 44 insertions(+), 25 deletions(-) diff --git a/CourseApp.Api/Program.cs b/CourseApp.Api/Program.cs index 75c1fb87..3c7c9c40 100644 --- a/CourseApp.Api/Program.cs +++ b/CourseApp.Api/Program.cs @@ -15,12 +15,12 @@ options.AddPolicy("wasm", policy => { policy.AllowAnyOrigin() - .WithMethods("GET", "POST") + .WithMethods("GET") .WithHeaders("Content-Type"); }); }); -builder.Services.AddScoped(); +builder.Services.AddSingleton(); builder.Services.AddScoped(); var app = builder.Build(); diff --git a/CourseApp.Api/Services/CourseGenerator.cs b/CourseApp.Api/Services/CourseGenerator.cs index 4b758d70..54439ae2 100644 --- a/CourseApp.Api/Services/CourseGenerator.cs +++ b/CourseApp.Api/Services/CourseGenerator.cs @@ -3,6 +3,9 @@ namespace CourseApp.Api.Services; +/// +/// Генератор тестовых данных при отсутствии данных в кэше +/// public class CourseGenerator { private static readonly string[] _courseNames = @@ -17,24 +20,27 @@ public class CourseGenerator "HTML+CSS Вёрстка сайтов" ]; + /// + /// Преднастроенный генератор + /// + private static readonly Faker _faker = new Faker("ru") + .RuleFor(c => c.Name, f => f.PickRandom(_courseNames)) + .RuleFor(c => c.TeacherFullName, f => f.Name.FullName()) + .RuleFor(c => c.StartDate, f => f.Date.SoonDateOnly(30)) + .RuleFor(c => c.EndDate, (f, c) => c.StartDate.AddDays(f.Random.Int(30, 180))) + .RuleFor(c => c.MaxStudents, f => f.Random.Int(10, 50)) + .RuleFor(c => c.CurrentStudents, (f, c) => f.Random.Int(0, c.MaxStudents)) + .RuleFor(c => c.HasCertificate, f => f.Random.Bool()) + .RuleFor(c => c.Price, f => Math.Round(f.Random.Decimal(5000, 10000), 2)) + .RuleFor(c => c.Rating, f => f.Random.Int(1, 5)); + + /// + /// Генерирует новый экземпляр курса с указанным идентификатором + /// public Course Generate(int id) { - var faker = new Faker("ru") - .RuleFor(c => c.Id, _ => id) - .RuleFor(c => c.Name, f => f.PickRandom(_courseNames)) - .RuleFor(c => c.TeacherFullName, f => f.Name.FullName()) - //f => $"{f.Name.LastName()} {f.Name.FirstName()} {f.Name.}") - .RuleFor(c => c.StartDate, f => f.Date.SoonDateOnly(30)) - .RuleFor(c => c.EndDate, (f, c) => - c.StartDate.AddDays(f.Random.Int(30, 180))) - .RuleFor(c => c.MaxStudents, f => f.Random.Int(10, 50)) - .RuleFor(c => c.CurrentStudents, (f, c) => - f.Random.Int(0, c.MaxStudents)) - .RuleFor(c => c.HasCertificate, f => f.Random.Bool()) - .RuleFor(c => c.Price, - f => Math.Round(f.Random.Decimal(5000, 10000), 2)) - .RuleFor(c => c.Rating, f => f.Random.Int(1, 5)); - - return faker.Generate(); + var course = _faker.Generate(); + course.Id = id; + return course; } } \ No newline at end of file diff --git a/CourseApp.Api/Services/CourseService.cs b/CourseApp.Api/Services/CourseService.cs index 4a3afea7..357ea8eb 100644 --- a/CourseApp.Api/Services/CourseService.cs +++ b/CourseApp.Api/Services/CourseService.cs @@ -4,9 +4,15 @@ namespace CourseApp.Api.Services; +/// +/// Сервис для получения информации о курсе +/// public class CourseService(IDistributedCache _cache, IConfiguration _configuration, ILogger _logger, CourseGenerator _generator) { + /// + /// Получает курс по идентификатору из кэша или с помощью генератора + /// public async Task GetCourseAsync(int id) { @@ -36,16 +42,23 @@ public async Task GetCourseAsync(int id) _logger.LogInformation("Курс {CourseId} отсутствует в кэше. Начинаем генерацию", id); var course = _generator.Generate(id); - var expirationMinutes = _configuration.GetValue("CacheSettings:ExpirationMinutes", 5); - var cacheOptions = new DistributedCacheEntryOptions + try { - AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes) - }; + var expirationMinutes = _configuration.GetValue("CacheSettings:ExpirationMinutes", 5); - await _cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(course), cacheOptions); - _logger.LogInformation("Курс {CourseId} сгенерирован и сохранён в кэш", id); + var cacheOptions = new DistributedCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes) + }; + await _cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(course), cacheOptions); + _logger.LogInformation("Курс {CourseId} сгенерирован и сохранён в кэш", id); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Не удалось сохранить курс {CourseId} в кэш. Работа продолжается без кэширования.", id); + } return course; } } \ No newline at end of file From 4ac591b6081c5fc61e7378f6cccdd16918b68c41 Mon Sep 17 00:00:00 2001 From: Daryaskhrv Date: Thu, 2 Apr 2026 19:39:20 +0400 Subject: [PATCH 5/5] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Api.Gateway/Api.Gateway.csproj | 17 +++++++ Api.Gateway/LoadBalancers/WeightedRandom.cs | 51 +++++++++++++++++++++ Api.Gateway/Program.cs | 33 +++++++++++++ Api.Gateway/Properties/launchSettings.json | 38 +++++++++++++++ Api.Gateway/appsettings.Development.json | 8 ++++ Api.Gateway/appsettings.json | 12 +++++ Api.Gateway/ocelot.json | 38 +++++++++++++++ Client.Wasm/Components/StudentCard.razor | 2 +- Client.Wasm/Properties/launchSettings.json | 6 +-- Client.Wasm/wwwroot/appsettings.json | 2 +- CloudDevelopment.sln | 8 +++- CourseApp.Api/Program.cs | 11 ----- CourseApp.AppHost/AppHost.cs | 18 +++++--- CourseApp.AppHost/CourseApp.AppHost.csproj | 1 + 14 files changed, 222 insertions(+), 23 deletions(-) create mode 100644 Api.Gateway/Api.Gateway.csproj create mode 100644 Api.Gateway/LoadBalancers/WeightedRandom.cs create mode 100644 Api.Gateway/Program.cs create mode 100644 Api.Gateway/Properties/launchSettings.json create mode 100644 Api.Gateway/appsettings.Development.json create mode 100644 Api.Gateway/appsettings.json create mode 100644 Api.Gateway/ocelot.json diff --git a/Api.Gateway/Api.Gateway.csproj b/Api.Gateway/Api.Gateway.csproj new file mode 100644 index 00000000..522372bf --- /dev/null +++ b/Api.Gateway/Api.Gateway.csproj @@ -0,0 +1,17 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + diff --git a/Api.Gateway/LoadBalancers/WeightedRandom.cs b/Api.Gateway/LoadBalancers/WeightedRandom.cs new file mode 100644 index 00000000..e57f25f8 --- /dev/null +++ b/Api.Gateway/LoadBalancers/WeightedRandom.cs @@ -0,0 +1,51 @@ +using Ocelot.LoadBalancer.Interfaces; +using Ocelot.Responses; +using Ocelot.Values; + +namespace Api.Gateway.LoadBalancers; + +/// +/// Балансировщик нагрузки, выбирающий downstream-сервис случайным образом с учётом весов. +/// Чем больше вес у сервиса, тем выше вероятность его выбора. +/// Веса задаются в конфигурации (WeightedRandom:Weights) и применяются к сервисам в порядке их перечисления в маршруте Ocelot. +/// +/// Фабричная функция получения списка downstream-сервисов. +/// Конфигурация приложения с секцией весов. +public class WeightedRandom(Func>> services, IConfiguration configuration) : ILoadBalancer +{ + private static readonly object _locker = new(); + private readonly int[] _weights = configuration + .GetSection("WeightedRandom:Weights") + .Get() ?? [1, 1, 1, 1, 1]; + private readonly Random _random = new(111); + + public string Type => nameof(WeightedRandom); + + public async Task> 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(serviceList[i].HostAndPort); + } + + return new OkResponse(serviceList[^1].HostAndPort); + } + } + + public void Release(ServiceHostAndPort hostAndPort) { } +} diff --git a/Api.Gateway/Program.cs b/Api.Gateway/Program.cs new file mode 100644 index 00000000..156c46c9 --- /dev/null +++ b/Api.Gateway/Program.cs @@ -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())); + +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(); diff --git a/Api.Gateway/Properties/launchSettings.json b/Api.Gateway/Properties/launchSettings.json new file mode 100644 index 00000000..c94313c8 --- /dev/null +++ b/Api.Gateway/Properties/launchSettings.json @@ -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" + } + } + } +} diff --git a/Api.Gateway/appsettings.Development.json b/Api.Gateway/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/Api.Gateway/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Api.Gateway/appsettings.json b/Api.Gateway/appsettings.json new file mode 100644 index 00000000..45d3fe4d --- /dev/null +++ b/Api.Gateway/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "WeightedRandom": { + "Weights": [ 5, 4, 3, 2, 1 ] + } +} diff --git a/Api.Gateway/ocelot.json b/Api.Gateway/ocelot.json new file mode 100644 index 00000000..4b90a21e --- /dev/null +++ b/Api.Gateway/ocelot.json @@ -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" + } +} diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor index 8acfba9d..b281cc98 100644 --- a/Client.Wasm/Components/StudentCard.razor +++ b/Client.Wasm/Components/StudentCard.razor @@ -4,7 +4,7 @@ - Номер №1 Кэширование + Номер №2 Балансировка нагрузки Вариант №50 "Учебный курс" Выполнена Сахаровой Дарьей 6513 Ссылка на форк diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json index 0d824ea7..60120ec3 100644 --- a/Client.Wasm/Properties/launchSettings.json +++ b/Client.Wasm/Properties/launchSettings.json @@ -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": { @@ -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": { @@ -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" diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json index 3e8284f6..e8ac606e 100644 --- a/Client.Wasm/wwwroot/appsettings.json +++ b/Client.Wasm/wwwroot/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "BaseAddress": "https://localhost:7068/api/course" + "BaseAddress": "https://localhost:7186/course" } diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln index c0634a98..f8762c78 100644 --- a/CloudDevelopment.sln +++ b/CloudDevelopment.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 18 -VisualStudioVersion = 18.3.11505.172 d18.3 +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 @@ -13,6 +13,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CourseApp.ServiceDefaults", 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 @@ -39,6 +41,10 @@ Global {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 diff --git a/CourseApp.Api/Program.cs b/CourseApp.Api/Program.cs index 3c7c9c40..69a8a862 100644 --- a/CourseApp.Api/Program.cs +++ b/CourseApp.Api/Program.cs @@ -10,16 +10,6 @@ builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); -builder.Services.AddCors(options => -{ - options.AddPolicy("wasm", policy => - { - policy.AllowAnyOrigin() - .WithMethods("GET") - .WithHeaders("Content-Type"); - }); -}); - builder.Services.AddSingleton(); builder.Services.AddScoped(); @@ -33,7 +23,6 @@ app.MapDefaultEndpoints(); app.UseHttpsRedirection(); -app.UseCors("wasm"); app.UseAuthorization(); app.MapControllers(); app.Run(); \ No newline at end of file diff --git a/CourseApp.AppHost/AppHost.cs b/CourseApp.AppHost/AppHost.cs index 99312342..e838d96b 100644 --- a/CourseApp.AppHost/AppHost.cs +++ b/CourseApp.AppHost/AppHost.cs @@ -2,7 +2,7 @@ var redis = builder.AddRedis("redis"); -var redisCommander = builder.AddContainer( +builder.AddContainer( name: "redis-commander", image: "rediscommander/redis-commander") .WithEnvironment("REDIS_HOSTS", "local:redis:6379") @@ -10,12 +10,18 @@ .WaitFor(redis) .WithEndpoint(port: 8081, targetPort: 8081); -var api = builder.AddProject("courseapp-api") - .WithReference(redis) - .WaitFor(redis); +var gateway = builder.AddProject("api-gateway"); + +for (var i = 0; i < 5; i++) +{ + var api = builder.AddProject($"courseapp-api-{i}", launchProfileName: null) + .WithReference(redis) + .WaitFor(redis) + .WithHttpsEndpoint(port: 8000 + i); + gateway.WaitFor(api); +} builder.AddProject("client") - .WithReference(api) - .WaitFor(api); + .WaitFor(gateway); builder.Build().Run(); \ No newline at end of file diff --git a/CourseApp.AppHost/CourseApp.AppHost.csproj b/CourseApp.AppHost/CourseApp.AppHost.csproj index 6c4a9501..3a23b25b 100644 --- a/CourseApp.AppHost/CourseApp.AppHost.csproj +++ b/CourseApp.AppHost/CourseApp.AppHost.csproj @@ -14,6 +14,7 @@ +