diff --git a/Api.Gateway/Api.Gateway.csproj b/Api.Gateway/Api.Gateway.csproj
new file mode 100644
index 00000000..23e8e8cf
--- /dev/null
+++ b/Api.Gateway/Api.Gateway.csproj
@@ -0,0 +1,15 @@
+
+
+
+ net8.0
+ enable
+ enable
+
+
+
+
+
+
+
+
+
diff --git a/Api.Gateway/LoadBalancer/WeightedRandom.cs b/Api.Gateway/LoadBalancer/WeightedRandom.cs
new file mode 100644
index 00000000..2e7ac2c5
--- /dev/null
+++ b/Api.Gateway/LoadBalancer/WeightedRandom.cs
@@ -0,0 +1,35 @@
+using Ocelot.LoadBalancer.Interfaces;
+using Ocelot.Responses;
+using Ocelot.Values;
+
+namespace Api.Gateway.LoadBalancer;
+
+///
+/// Балансировка случайным образом с весами
+///
+public class WeightedRandom : ILoadBalancer
+{
+ private readonly Func>> _services = null!;
+ private static readonly object _locker = new();
+ private readonly int[] _values = null!;
+ public string Type => nameof(WeightedRandom);
+
+ public WeightedRandom(Func>> services)
+ {
+ _services = services;
+ int[] frequencies = [1, 2, 3, 2, 1];
+ _values = [.. Enumerable.Range(0, 5).Zip(frequencies, (val, freq) => Enumerable.Repeat(val, freq)).SelectMany(x => x)];
+ }
+
+ public async Task> LeaseAsync(HttpContext httpContext)
+ {
+ var services = await _services.Invoke();
+ lock (_locker)
+ {
+ Random.Shared.Shuffle(_values);
+ return new OkResponse(services[_values.First()].HostAndPort);
+ }
+ }
+
+ public void Release(ServiceHostAndPort hostAndPort) { }
+}
\ No newline at end of file
diff --git a/Api.Gateway/Program.cs b/Api.Gateway/Program.cs
new file mode 100644
index 00000000..2b6f7ff0
--- /dev/null
+++ b/Api.Gateway/Program.cs
@@ -0,0 +1,29 @@
+using Api.Gateway.LoadBalancer;
+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((_, _, dicoveryProvider) => new(dicoveryProvider.GetAsync));
+
+builder.Services.AddCors(options =>
+{
+ options.AddDefaultPolicy(policy =>
+ {
+ policy.WithOrigins(
+ "https://localhost:5127",
+ "http://localhost:5127",
+ "https://localhost:7282"
+ )
+ .WithMethods("GET")
+ .AllowAnyHeader();
+ });
+});
+var app = builder.Build();
+app.UseCors();
+await app.UseOcelot();
+app.Run();
\ No newline at end of file
diff --git a/Api.Gateway/Properties/launchSettings.json b/Api.Gateway/Properties/launchSettings.json
new file mode 100644
index 00000000..616bee86
--- /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:54707",
+ "sslPort": 44338
+ }
+ },
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:5124",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:7185;http://localhost:5124",
+ "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..10f68b8c
--- /dev/null
+++ b/Api.Gateway/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*"
+}
diff --git a/Api.Gateway/ocelot.json b/Api.Gateway/ocelot.json
new file mode 100644
index 00000000..958e88b8
--- /dev/null
+++ b/Api.Gateway/ocelot.json
@@ -0,0 +1,23 @@
+{
+ "Routes": [
+ {
+ "UpstreamPathTemplate": "/training-course",
+ "UpstreamHttpMethod": [ "GET" ],
+ "DownstreamPathTemplate": "/training-course",
+ "DownstreamScheme": "http",
+ "DownstreamHostAndPorts": [
+ { "Host": "localhost", "Port": 4000 },
+ { "Host": "localhost", "Port": 4001 },
+ { "Host": "localhost", "Port": 4002 },
+ { "Host": "localhost", "Port": 4003 },
+ { "Host": "localhost", "Port": 4004 }
+ ],
+ "LoadBalancerOptions": {
+ "Type": "WeightedRandom"
+ }
+ }
+ ],
+ "GlobalConfiguration": {
+ "BaseUrl": "http://localhost:7185"
+ }
+}
\ No newline at end of file
diff --git a/AspireApp/AspireApp.AppHost/AspireApp.AppHost.csproj b/AspireApp/AspireApp.AppHost/AspireApp.AppHost.csproj
new file mode 100644
index 00000000..6fb8a82e
--- /dev/null
+++ b/AspireApp/AspireApp.AppHost/AspireApp.AppHost.csproj
@@ -0,0 +1,25 @@
+
+
+
+
+
+ Exe
+ net8.0
+ enable
+ enable
+ true
+ 3cec140f-e46f-4c50-ade0-6bd5134c5831
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/AspireApp/AspireApp.AppHost/Program.cs b/AspireApp/AspireApp.AppHost/Program.cs
new file mode 100644
index 00000000..bdb81216
--- /dev/null
+++ b/AspireApp/AspireApp.AppHost/Program.cs
@@ -0,0 +1,23 @@
+var builder = DistributedApplication.CreateBuilder(args);
+
+var cache = builder.AddRedis("course-cache")
+ .WithImageTag("latest")
+ .WithRedisInsight(containerName: "course-insight");
+
+var gateway = builder.AddProject("api-gateway");
+
+for (var i = 0; i < 5; i++)
+{
+ var service = builder.AddProject($"training-course-api-{i + 1}", launchProfileName: null)
+ .WithHttpEndpoint(4000 + i)
+ .WithReference(cache, "RedisCache")
+ .WaitFor(cache);
+ gateway.WaitFor(service);
+}
+
+
+builder.AddProject("training-course")
+ .WaitFor(gateway);
+
+
+builder.Build().Run();
diff --git a/AspireApp/AspireApp.AppHost/Properties/launchSettings.json b/AspireApp/AspireApp.AppHost/Properties/launchSettings.json
new file mode 100644
index 00000000..d6134b49
--- /dev/null
+++ b/AspireApp/AspireApp.AppHost/Properties/launchSettings.json
@@ -0,0 +1,29 @@
+{
+ "$schema": "https://json.schemastore.org/launchsettings.json",
+ "profiles": {
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:17145;http://localhost:15026",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21138",
+ "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22278"
+ }
+ },
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:15026",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19066",
+ "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20044"
+ }
+ }
+ }
+}
diff --git a/AspireApp/AspireApp.AppHost/appsettings.Development.json b/AspireApp/AspireApp.AppHost/appsettings.Development.json
new file mode 100644
index 00000000..0c208ae9
--- /dev/null
+++ b/AspireApp/AspireApp.AppHost/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/AspireApp/AspireApp.AppHost/appsettings.json b/AspireApp/AspireApp.AppHost/appsettings.json
new file mode 100644
index 00000000..31c092aa
--- /dev/null
+++ b/AspireApp/AspireApp.AppHost/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning",
+ "Aspire.Hosting.Dcp": "Warning"
+ }
+ }
+}
diff --git a/AspireApp/AspireApp.ServiceDefaults/AspireApp.ServiceDefaults.csproj b/AspireApp/AspireApp.ServiceDefaults/AspireApp.ServiceDefaults.csproj
new file mode 100644
index 00000000..da24936e
--- /dev/null
+++ b/AspireApp/AspireApp.ServiceDefaults/AspireApp.ServiceDefaults.csproj
@@ -0,0 +1,26 @@
+
+
+
+ net8.0
+ enable
+ enable
+ true
+
+
+
+ NU1603
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/AspireApp/AspireApp.ServiceDefaults/Extensions.cs b/AspireApp/AspireApp.ServiceDefaults/Extensions.cs
new file mode 100644
index 00000000..13151bf4
--- /dev/null
+++ b/AspireApp/AspireApp.ServiceDefaults/Extensions.cs
@@ -0,0 +1,119 @@
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Diagnostics.HealthChecks;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.ServiceDiscovery;
+using OpenTelemetry;
+using OpenTelemetry.Metrics;
+using OpenTelemetry.Trace;
+
+namespace Microsoft.Extensions.Hosting;
+
+// Adds common .NET Aspire services: service discovery, resilience, health checks, and OpenTelemetry.
+// This project should be referenced by each service project in your solution.
+// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults
+public static class Extensions
+{
+ public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder
+ {
+ builder.ConfigureOpenTelemetry();
+
+ builder.AddDefaultHealthChecks();
+
+ builder.Services.AddServiceDiscovery();
+
+ builder.Services.ConfigureHttpClientDefaults(http =>
+ {
+ // Turn on resilience by default
+ http.AddStandardResilienceHandler();
+
+ // Turn on service discovery by default
+ http.AddServiceDiscovery();
+ });
+
+ // Uncomment the following to restrict the allowed schemes for service discovery.
+ // builder.Services.Configure(options =>
+ // {
+ // options.AllowedSchemes = ["https"];
+ // });
+
+ return builder;
+ }
+
+ 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()
+ // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package)
+ //.AddGrpcClientInstrumentation()
+ .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();
+ }
+
+ // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package)
+ //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]))
+ //{
+ // builder.Services.AddOpenTelemetry()
+ // .UseAzureMonitor();
+ //}
+
+ return builder;
+ }
+
+ public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder
+ {
+ builder.Services.AddHealthChecks()
+ // Add a default liveness check to ensure app is responsive
+ .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);
+
+ return builder;
+ }
+
+ public static WebApplication MapDefaultEndpoints(this WebApplication app)
+ {
+ // Adding health checks endpoints to applications in non-development environments has security implications.
+ // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments.
+ if (app.Environment.IsDevelopment())
+ {
+ // All health checks must pass for app to be considered ready to accept traffic after starting
+ app.MapHealthChecks("/health");
+
+ // Only health checks tagged with the "live" tag must pass for app to be considered alive
+ app.MapHealthChecks("/alive", new HealthCheckOptions
+ {
+ Predicate = r => r.Tags.Contains("live")
+ });
+ }
+
+ return app;
+ }
+}
diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor
index 661f1181..da365b11 100644
--- a/Client.Wasm/Components/StudentCard.razor
+++ b/Client.Wasm/Components/StudentCard.razor
@@ -4,10 +4,10 @@
- Номер №X "Название лабораторной"
- Вариант №Х "Название варианта"
- Выполнена Фамилией Именем 65ХХ
- Ссылка на форк
+ Номер №2 "Балансировка нагрузки"
+ Вариант №26 "Учебный курс"
+ Выполнена Куспанова Дания 6512
+ Ссылка на форк
diff --git a/Client.Wasm/Program.cs b/Client.Wasm/Program.cs
index a182a920..cf43fc02 100644
--- a/Client.Wasm/Program.cs
+++ b/Client.Wasm/Program.cs
@@ -9,6 +9,7 @@
builder.RootComponents.Add("#app");
builder.RootComponents.Add("head::after");
+var apiBaseUrl = builder.Configuration["ApiBaseUrl"] ?? "https://localhost:7185/training-course/";
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddBlazorise(options => { options.Immediate = true; })
.AddBootstrapProviders()
diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json
index d1fe7ab3..b97c3ac5 100644
--- a/Client.Wasm/wwwroot/appsettings.json
+++ b/Client.Wasm/wwwroot/appsettings.json
@@ -6,5 +6,5 @@
}
},
"AllowedHosts": "*",
- "BaseAddress": ""
+ "BaseAddress": "https://localhost:7185/training-course"
}
diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln
index cb48241d..ba44d3b4 100644
--- a/CloudDevelopment.sln
+++ b/CloudDevelopment.sln
@@ -5,6 +5,14 @@ VisualStudioVersion = 17.14.36811.4
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}") = "AspireApp.AppHost", "AspireApp\AspireApp.AppHost\AspireApp.AppHost.csproj", "{A29837DE-20C1-485D-8A15-20290F913552}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspireApp.ServiceDefaults", "AspireApp\AspireApp.ServiceDefaults\AspireApp.ServiceDefaults.csproj", "{792C7D55-018A-45EC-8437-5A96B7E2B23F}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Service.Api", "Service.Api\Service.Api.csproj", "{6AA6D305-55E5-4379-87E5-F0ED5E347B49}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api.Gateway", "Api.Gateway\Api.Gateway.csproj", "{918C028A-F3FC-4A78-B9F2-199193B8949E}"
+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
+ {A29837DE-20C1-485D-8A15-20290F913552}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {A29837DE-20C1-485D-8A15-20290F913552}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {A29837DE-20C1-485D-8A15-20290F913552}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {A29837DE-20C1-485D-8A15-20290F913552}.Release|Any CPU.Build.0 = Release|Any CPU
+ {792C7D55-018A-45EC-8437-5A96B7E2B23F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {792C7D55-018A-45EC-8437-5A96B7E2B23F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {792C7D55-018A-45EC-8437-5A96B7E2B23F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {792C7D55-018A-45EC-8437-5A96B7E2B23F}.Release|Any CPU.Build.0 = Release|Any CPU
+ {6AA6D305-55E5-4379-87E5-F0ED5E347B49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {6AA6D305-55E5-4379-87E5-F0ED5E347B49}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {6AA6D305-55E5-4379-87E5-F0ED5E347B49}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {6AA6D305-55E5-4379-87E5-F0ED5E347B49}.Release|Any CPU.Build.0 = Release|Any CPU
+ {918C028A-F3FC-4A78-B9F2-199193B8949E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {918C028A-F3FC-4A78-B9F2-199193B8949E}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {918C028A-F3FC-4A78-B9F2-199193B8949E}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {918C028A-F3FC-4A78-B9F2-199193B8949E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/Service.Api/Entities/TrainingCourse.cs b/Service.Api/Entities/TrainingCourse.cs
new file mode 100644
index 00000000..8e179703
--- /dev/null
+++ b/Service.Api/Entities/TrainingCourse.cs
@@ -0,0 +1,69 @@
+using System.Text.Json.Serialization;
+
+namespace Service.Api.Entities;
+
+///
+/// Учебный курс
+///
+public class TrainingCourse
+{
+ ///
+ /// Идентификатор курса в системе
+ ///
+ [JsonPropertyName("id")]
+ public int Id { get; set; }
+
+ ///
+ /// Наименование курса
+ ///
+ [JsonPropertyName("name")]
+ public string Name { get; set; } = string.Empty;
+
+ ///
+ /// ФИО преподавателя (фамилия, имя, отчество через пробел)
+ ///
+ [JsonPropertyName("teacherFullName")]
+ public string TeacherFullName { get; set; } = string.Empty;
+
+ ///
+ /// Дата начала курса
+ ///
+ [JsonPropertyName("startDate")]
+ public DateOnly StartDate { get; set; }
+
+ ///
+ /// Дата окончания курса
+ ///
+ [JsonPropertyName("endDate")]
+ public DateOnly EndDate { get; set; }
+
+ ///
+ /// Максимальное число студентов
+ ///
+ [JsonPropertyName("maxStudents")]
+ public int MaxStudents { get; set; }
+
+ ///
+ /// Текущее число студентов
+ ///
+ [JsonPropertyName("currentStudents")]
+ public int CurrentStudents { get; set; }
+
+ ///
+ /// Выдача сертификата по окончании
+ ///
+ [JsonPropertyName("hasCertificate")]
+ public bool HasCertificate { get; set; }
+
+ ///
+ /// Стоимость курса
+ ///
+ [JsonPropertyName("price")]
+ public decimal Price { get; set; }
+
+ ///
+ /// Рейтинг курса (от 1 до 5)
+ ///
+ [JsonPropertyName("rating")]
+ public int Rating { get; set; }
+}
\ No newline at end of file
diff --git a/Service.Api/Generator/GeneratorService.cs b/Service.Api/Generator/GeneratorService.cs
new file mode 100644
index 00000000..0e5ed904
--- /dev/null
+++ b/Service.Api/Generator/GeneratorService.cs
@@ -0,0 +1,70 @@
+using System.Text.Json;
+using Microsoft.Extensions.Caching.Distributed;
+using Service.Api.Entities;
+
+namespace Service.Api.Generator;
+
+///
+/// Сервис для генерации и кэширования учебных курсов
+///
+public class GeneratorService (IDistributedCache cache, IConfiguration configuration, ILogger logger): IGeneratorService
+{
+ private readonly TimeSpan _cacheExpiration = int.TryParse(configuration["CacheExpiration"], out var sec)
+ ? TimeSpan.FromSeconds(sec)
+ : TimeSpan.FromSeconds(3600);
+
+ ///
+ /// Генерирует один случайный учебный курс и сохраняет в кэш
+ ///
+ public async Task ProcessTrainingCourse(int id)
+ {
+ try
+ {
+ logger.LogInformation("Начало генерации учебного курса");
+ var trainingCourse = await GetCourseFromCacheAsync(id);
+ if (trainingCourse != null)
+ {
+ return trainingCourse;
+ }
+ trainingCourse = TrainingCourseGenerator.GenerateOne(id);
+ logger.LogInformation("Курс успешно сгенерирован. ID: {CourseId}", trainingCourse.Id);
+ await SaveCourseToCacheAsync(trainingCourse);
+ return trainingCourse;
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Ошибка при генерации курса c {CourseId}", id);
+ return null;
+ }
+ }
+
+ ///
+ /// Получает курс по ID из кэша
+ ///
+ private async Task GetCourseFromCacheAsync(int id)
+ {
+ var cachedData = await cache.GetStringAsync(id.ToString());
+ if (string.IsNullOrEmpty(cachedData))
+ {
+ logger.LogWarning("Не было найдено курса с ID {CourseId} в кэше", id);
+ return null;
+ }
+ var course = JsonSerializer.Deserialize(cachedData);
+ logger.LogInformation("Курс с ID {CourseId} был найден в кэше", id);
+ return course;
+ }
+
+ ///
+ /// Сохраняет курс в кэш
+ ///
+ private async Task SaveCourseToCacheAsync(TrainingCourse course)
+ {
+ logger.LogInformation("Курс с ID: {CourseId} успешно добавлен в кэш", course.Id);
+ var jsonData = JsonSerializer.Serialize(course);
+ await cache.SetStringAsync(course.Id.ToString(), jsonData,
+ new DistributedCacheEntryOptions
+ {
+ AbsoluteExpirationRelativeToNow = _cacheExpiration
+ });
+ }
+}
\ No newline at end of file
diff --git a/Service.Api/Generator/IGeneratorService.cs b/Service.Api/Generator/IGeneratorService.cs
new file mode 100644
index 00000000..3a380872
--- /dev/null
+++ b/Service.Api/Generator/IGeneratorService.cs
@@ -0,0 +1,15 @@
+using Service.Api.Entities;
+
+namespace Service.Api.Generator;
+
+///
+/// Интерфейс для запуска юзкейса по обработке учебного курса
+///
+public interface IGeneratorService
+{
+ ///
+ /// Генерирует один случайный учебный курс
+ ///
+ /// Сгенерированный курс
+ Task ProcessTrainingCourse(int id);
+}
diff --git a/Service.Api/Generator/TrainingCourseGenerator.cs b/Service.Api/Generator/TrainingCourseGenerator.cs
new file mode 100644
index 00000000..c00dcef6
--- /dev/null
+++ b/Service.Api/Generator/TrainingCourseGenerator.cs
@@ -0,0 +1,90 @@
+using Bogus;
+using Bogus.DataSets;
+using Service.Api.Entities;
+
+namespace Service.Api.Generator;
+
+///
+/// Генератор тестовых данных для учебных курсов
+///
+public static class TrainingCourseGenerator
+{
+ private static readonly Faker _courseFaker;
+
+ ///
+ /// Инициализирует генератор
+ ///
+ static TrainingCourseGenerator()
+ {
+ var courseNames = new[]
+ {
+ "ASP.NET Core разработка",
+ "Blazor WebAssembly",
+ "Entity Framework Core",
+ "React для начинающих",
+ "Angular продвинутый",
+ "Python для анализа данных",
+ "Java Spring Boot",
+ "Go для микросервисов",
+ "Docker и Kubernetes",
+ "SQL оптимизация запросов",
+ "TypeScript с нуля",
+ "Vue.js практикум",
+ "C# алгоритмы",
+ "Azure DevOps",
+ "Git и CI/CD"
+ };
+ _courseFaker = new Faker("ru")
+ .RuleFor(c => c.Id, f => f.IndexFaker + 1)
+ .RuleFor(c => c.Name, f => f.PickRandom(courseNames))
+ .RuleFor(c => c.TeacherFullName, f =>
+ {
+ var gender = f.PickRandom();
+
+ var firstName = f.Name.FirstName(gender);
+ var lastName = f.Name.LastName(gender);
+
+ var patronymicSuffix = gender == Name.Gender.Male ? "ович" : "овна";
+ var patronymic = f.Name.FirstName(Name.Gender.Male) + patronymicSuffix;
+
+ return $"{lastName} {firstName} {patronymic}";
+ })
+ .RuleFor(c => c.StartDate, f =>
+ {
+ var daysToStart = f.Random.Int(3, 60);
+ return f.Date.SoonDateOnly(daysToStart);
+ })
+ .RuleFor(c => c.EndDate, (f, c) =>
+ {
+ var durationDays = f.Random.Int(10, 90);
+ return c.StartDate.AddDays(durationDays);
+ })
+ .RuleFor(c => c.MaxStudents, f => f.Random.Int(5, 30))
+ .RuleFor(c => c.CurrentStudents, (f, c) =>
+ {
+ var today = DateOnly.FromDateTime(DateTime.Now);
+ if (c.StartDate <= today)
+ {
+ return f.Random.Int(0, c.MaxStudents);
+ }
+ return f.Random.Int(0, c.MaxStudents / 2);
+ })
+ .RuleFor(c => c.HasCertificate, f => f.Random.Bool(0.9f))
+ .RuleFor(c => c.Price, f =>
+ {
+ var price = f.Random.Decimal(5000, 150000);
+ return Math.Round(price, 2);
+ })
+ .RuleFor(c => c.Rating, f => f.Random.Int(1, 5));
+ }
+
+ ///
+ /// Генерирует один учебный курс с конкретным id
+ ///
+ public static TrainingCourse GenerateOne(int id)
+ {
+ var course = _courseFaker.Generate();
+ course.Id = id;
+ return course;
+ }
+}
\ No newline at end of file
diff --git a/Service.Api/Program.cs b/Service.Api/Program.cs
new file mode 100644
index 00000000..fefd0977
--- /dev/null
+++ b/Service.Api/Program.cs
@@ -0,0 +1,13 @@
+using Service.Api.Generator;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.AddServiceDefaults();
+builder.AddRedisDistributedCache("RedisCache");
+builder.Services.AddScoped();
+
+
+var app = builder.Build();
+app.MapDefaultEndpoints();
+app.MapGet("/training-course", (IGeneratorService service, int id) => service.ProcessTrainingCourse(id));
+app.Run();
diff --git a/Service.Api/Properties/launchSettings.json b/Service.Api/Properties/launchSettings.json
new file mode 100644
index 00000000..9e10b559
--- /dev/null
+++ b/Service.Api/Properties/launchSettings.json
@@ -0,0 +1,38 @@
+{
+ "$schema": "http://json.schemastore.org/launchsettings.json",
+ "iisSettings": {
+ "windowsAuthentication": false,
+ "anonymousAuthentication": true,
+ "iisExpress": {
+ "applicationUrl": "http://localhost:21995",
+ "sslPort": 44360
+ }
+ },
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:5241",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "https://localhost:7077;http://localhost:5241",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/Service.Api/Service.Api.csproj b/Service.Api/Service.Api.csproj
new file mode 100644
index 00000000..0c73a37d
--- /dev/null
+++ b/Service.Api/Service.Api.csproj
@@ -0,0 +1,18 @@
+
+
+
+ net8.0
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Service.Api/appsettings.Development.json b/Service.Api/appsettings.Development.json
new file mode 100644
index 00000000..0c208ae9
--- /dev/null
+++ b/Service.Api/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/Service.Api/appsettings.json b/Service.Api/appsettings.json
new file mode 100644
index 00000000..10f68b8c
--- /dev/null
+++ b/Service.Api/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*"
+}