-
Notifications
You must be signed in to change notification settings - Fork 24
Сахарова Дарья Лаб. 1 Группа 6513 #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+589
−135
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,5 +6,5 @@ | |
| } | ||
| }, | ||
| "AllowedHosts": "*", | ||
| "BaseAddress": "" | ||
| "BaseAddress": "https://localhost:7068/api/course" | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
| { | ||
| /// <summary> | ||
| /// Получить курс по идентификатору | ||
| /// </summary> | ||
| /// <param name="id">Идентификатор курса</param> | ||
| /// <returns>Информация о курсе</returns> | ||
| [HttpGet] | ||
| public async Task<ActionResult<Course>> Get(int id) | ||
| { | ||
| var course = await _courseService.GetCourseAsync(id); | ||
| return Ok(course); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="13.1.1" /> | ||
| <PackageReference Include="Bogus" Version="35.6.5" /> | ||
| <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\CourseApp.Domain\CourseApp.Domain.csproj" /> | ||
| <ProjectReference Include="..\CourseApp.ServiceDefaults\CourseApp.ServiceDefaults.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,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") | ||
| .WithHeaders("Content-Type"); | ||
| }); | ||
| }); | ||
|
|
||
| builder.Services.AddSingleton<CourseGenerator>(); | ||
| builder.Services.AddScoped<CourseService>(); | ||
|
|
||
| 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(); |
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,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" | ||
| } | ||
| } | ||
| } | ||
| } |
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,46 @@ | ||
| using Bogus; | ||
| using CourseApp.Domain.Entity; | ||
|
|
||
| namespace CourseApp.Api.Services; | ||
|
|
||
| /// <summary> | ||
| /// Генератор тестовых данных при отсутствии данных в кэше | ||
| /// </summary> | ||
| public class CourseGenerator | ||
| { | ||
| private static readonly string[] _courseNames = | ||
| [ | ||
| "C# для начинающих", | ||
| "Python для анализа данных", | ||
| "Микросервисная архитектура", | ||
| "Docker", | ||
| "Алгоритмы и структуры данных", | ||
| "SQL и базы данных", | ||
| "Автоматизированное тестирование", | ||
| "HTML+CSS Вёрстка сайтов" | ||
| ]; | ||
|
|
||
| /// <summary> | ||
| /// Преднастроенный генератор | ||
| /// </summary> | ||
| private static readonly Faker<Course> _faker = new Faker<Course>("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)); | ||
|
|
||
| /// <summary> | ||
| /// Генерирует новый экземпляр курса с указанным идентификатором | ||
| /// </summary> | ||
| public Course Generate(int id) | ||
| { | ||
| var course = _faker.Generate(); | ||
| course.Id = id; | ||
| return course; | ||
| } | ||
| } |
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,64 @@ | ||
| using System.Text.Json; | ||
| using CourseApp.Domain.Entity; | ||
| using Microsoft.Extensions.Caching.Distributed; | ||
|
|
||
| namespace CourseApp.Api.Services; | ||
|
|
||
| /// <summary> | ||
| /// Сервис для получения информации о курсе | ||
| /// </summary> | ||
| public class CourseService(IDistributedCache _cache, IConfiguration _configuration, | ||
| ILogger<CourseService> _logger, CourseGenerator _generator) | ||
| { | ||
| /// <summary> | ||
| /// Получает курс по идентификатору из кэша или с помощью генератора | ||
| /// </summary> | ||
| public async Task<Course> 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<Course>(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); | ||
|
|
||
| try | ||
| { | ||
| 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); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogWarning(ex, "Не удалось сохранить курс {CourseId} в кэш. Работа продолжается без кэширования.", id); | ||
| } | ||
| return course; | ||
| } | ||
| } |
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,12 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| }, | ||
| "CacheSettings": { | ||
| "ExpirationMinutes": 10 | ||
| }, | ||
| "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,21 @@ | ||
| 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); | ||
alxmcs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| var api = builder.AddProject<Projects.CourseApp_Api>("courseapp-api") | ||
| .WithReference(redis) | ||
| .WaitFor(redis); | ||
|
|
||
| builder.AddProject<Projects.Client_Wasm>("client") | ||
| .WithReference(api) | ||
| .WaitFor(api); | ||
|
|
||
| builder.Build().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,22 @@ | ||
| <Project Sdk="Aspire.AppHost.Sdk/13.1.0"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| <UserSecretsId>c086dba3-3e81-4540-916e-ccad1674fa30</UserSecretsId> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Aspire.Hosting.AppHost" Version="13.1.1" /> | ||
| <PackageReference Include="Aspire.Hosting.Redis" Version="13.1.1" /> | ||
alxmcs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\Client.Wasm\Client.Wasm.csproj" /> | ||
| <ProjectReference Include="..\CourseApp.Api\CourseApp.Api.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
|
|
||
| </Project> | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.