diff --git a/Client.Wasm/Components/StudentCard.razor b/Client.Wasm/Components/StudentCard.razor
index 661f1181..3df3c2ce 100644
--- a/Client.Wasm/Components/StudentCard.razor
+++ b/Client.Wasm/Components/StudentCard.razor
@@ -4,10 +4,10 @@
- Номер №X "Название лабораторной"
- Вариант №Х "Название варианта"
- Выполнена Фамилией Именем 65ХХ
- Ссылка на форк
+ Номер №1 "Кэширование"
+ Вариант №2 "Сотрудник компании"
+ Выполнена Беляковой Вероникой 6511
+ Ссылка на форк
diff --git a/Client.Wasm/Properties/launchSettings.json b/Client.Wasm/Properties/launchSettings.json
index 0d824ea7..47b57f1b 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": {
diff --git a/Client.Wasm/wwwroot/appsettings.json b/Client.Wasm/wwwroot/appsettings.json
index d1fe7ab3..da1bc60c 100644
--- a/Client.Wasm/wwwroot/appsettings.json
+++ b/Client.Wasm/wwwroot/appsettings.json
@@ -6,5 +6,5 @@
}
},
"AllowedHosts": "*",
- "BaseAddress": ""
+ "BaseAddress": "http://localhost:5200/api/employee"
}
diff --git a/CloudDevelopment.sln b/CloudDevelopment.sln
index cb48241d..20cd1d62 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}") = "Employee.ApiService", "Employee.ApiService\Employee.ApiService.csproj", "{3642B4FB-560F-150E-907B-C9C514725E87}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Employee.AppHost", "Employee.AppHost\Employee.AppHost.csproj", "{BEB73446-37AA-8D05-2D56-A35572F27A3B}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Employee.ServiceDefaults", "Employee.ServiceDefaults\Employee.ServiceDefaults.csproj", "{D85BA7A1-4E0F-9EEE-41E8-7A478C12984D}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Employee.ApiGateway", "Employee.ApiGateway\Employee.ApiGateway.csproj", "{08732133-D1F2-00C9-671B-4197752A18B0}"
+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
+ {3642B4FB-560F-150E-907B-C9C514725E87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {3642B4FB-560F-150E-907B-C9C514725E87}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {3642B4FB-560F-150E-907B-C9C514725E87}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {3642B4FB-560F-150E-907B-C9C514725E87}.Release|Any CPU.Build.0 = Release|Any CPU
+ {BEB73446-37AA-8D05-2D56-A35572F27A3B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {BEB73446-37AA-8D05-2D56-A35572F27A3B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {BEB73446-37AA-8D05-2D56-A35572F27A3B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {BEB73446-37AA-8D05-2D56-A35572F27A3B}.Release|Any CPU.Build.0 = Release|Any CPU
+ {D85BA7A1-4E0F-9EEE-41E8-7A478C12984D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {D85BA7A1-4E0F-9EEE-41E8-7A478C12984D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {D85BA7A1-4E0F-9EEE-41E8-7A478C12984D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {D85BA7A1-4E0F-9EEE-41E8-7A478C12984D}.Release|Any CPU.Build.0 = Release|Any CPU
+ {08732133-D1F2-00C9-671B-4197752A18B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {08732133-D1F2-00C9-671B-4197752A18B0}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {08732133-D1F2-00C9-671B-4197752A18B0}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {08732133-D1F2-00C9-671B-4197752A18B0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/Employee.ApiGateway/Employee.ApiGateway.csproj b/Employee.ApiGateway/Employee.ApiGateway.csproj
new file mode 100644
index 00000000..172916a0
--- /dev/null
+++ b/Employee.ApiGateway/Employee.ApiGateway.csproj
@@ -0,0 +1,17 @@
+
+
+
+ net8.0
+ enable
+ enable
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Employee.ApiGateway/LoadBalancer/QueryBasedLoadBalanser.cs b/Employee.ApiGateway/LoadBalancer/QueryBasedLoadBalanser.cs
new file mode 100644
index 00000000..f621aef3
--- /dev/null
+++ b/Employee.ApiGateway/LoadBalancer/QueryBasedLoadBalanser.cs
@@ -0,0 +1,69 @@
+using Ocelot.Values;
+using Ocelot.Responses;
+using Ocelot.LoadBalancer.Errors;
+using Ocelot.LoadBalancer.Interfaces;
+using Ocelot.ServiceDiscovery.Providers;
+
+namespace Employee.ApiGateway.LoadBalancer;
+
+///
+/// Балансировщик нагрузки, выбирающий реплику по значению параметра "id"
+///
+/// Провайдер для получения списка доступных сервисов
+public class QueryBasedLoadBalancer(IServiceDiscoveryProvider serviceDiscovery) : ILoadBalancer
+{
+ private const string IdQuery = "id";
+
+ public string Type => nameof(QueryBasedLoadBalancer);
+
+ ///
+ /// Функция выбора сервиса по параметру "id"
+ ///
+ /// Контекст HTTP-запроса
+ /// Адрес выбранного сервиса или ошибка
+ public async Task> LeaseAsync(HttpContext httpContext)
+ {
+ var services = await serviceDiscovery.GetAsync();
+
+ if (services is null || services.Count == 0)
+ {
+ return new ErrorResponse(
+ new ServicesAreNullError("Нет доступных сервисов"));
+ }
+
+ var idResult = TryGetValidId(httpContext.Request.Query);
+
+ if (!idResult.IsSuccess)
+ {
+ return new ErrorResponse(
+ new UnableToFindLoadBalancerError(idResult.ErrorMessage));
+ }
+
+ var id = idResult.Value;
+
+ var index = id % services.Count;
+ var selected = services[index];
+
+ return new OkResponse(selected.HostAndPort);
+ }
+
+ ///
+ /// Функция проверки параметра запроса
+ ///
+ /// Запрос
+ /// Значение id и сообщение об ошибке
+ private static (bool IsSuccess, int Value, string ErrorMessage) TryGetValidId(IQueryCollection query)
+ {
+ if (!query.TryGetValue(IdQuery, out var idValues) || string.IsNullOrWhiteSpace(idValues))
+ return (false, 0, "Отсутствует или пустой параметр 'id'");
+
+ if (!int.TryParse(idValues.First(), out var id))
+ return (false, 0, "Параметр 'id' должен быть числом");
+
+ if (id < 0)
+ return (false, 0, "Параметр 'id' не может быть отрицательным");
+
+ return (true, id, string.Empty);
+ }
+ public void Release(ServiceHostAndPort hostAndPort) { }
+}
\ No newline at end of file
diff --git a/Employee.ApiGateway/Program.cs b/Employee.ApiGateway/Program.cs
new file mode 100644
index 00000000..84b93062
--- /dev/null
+++ b/Employee.ApiGateway/Program.cs
@@ -0,0 +1,44 @@
+using Employee.ApiGateway.LoadBalancer;
+using Ocelot.DependencyInjection;
+using Ocelot.Middleware;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
+
+var generators = builder.Configuration.GetSection("Generators").Get() ?? [];
+
+var overrides = new List>();
+
+for (var i = 0; i < generators.Length; i++)
+{
+ var serviceName = generators[i];
+ var url = builder.Configuration[$"services:{serviceName}:http:0"];
+
+ if (string.IsNullOrWhiteSpace(url))
+ continue;
+
+ if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
+ continue;
+
+ overrides.Add(new KeyValuePair(
+ $"Routes:0:DownstreamHostAndPorts:{i}:Host", uri.Host));
+
+ overrides.Add(new KeyValuePair(
+ $"Routes:0:DownstreamHostAndPorts:{i}:Port", uri.Port.ToString()));
+}
+
+if (overrides.Any())
+{
+ builder.Configuration.AddInMemoryCollection(overrides);
+}
+
+builder.Services
+ .AddOcelot(builder.Configuration)
+ .AddCustomLoadBalancer((route, sp) =>
+ new QueryBasedLoadBalancer(sp));
+
+var app = builder.Build();
+
+await app.UseOcelot();
+await app.RunAsync();
\ No newline at end of file
diff --git a/Employee.ApiGateway/Properties/launchSettings.json b/Employee.ApiGateway/Properties/launchSettings.json
new file mode 100644
index 00000000..1c654edc
--- /dev/null
+++ b/Employee.ApiGateway/Properties/launchSettings.json
@@ -0,0 +1,38 @@
+{
+ "$schema": "http://json.schemastore.org/launchsettings.json",
+ "iisSettings": {
+ "windowsAuthentication": false,
+ "anonymousAuthentication": true,
+ "iisExpress": {
+ "applicationUrl": "http://localhost:50608",
+ "sslPort": 44382
+ }
+ },
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": false,
+ "applicationUrl": "http://localhost:5200",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": false,
+ "applicationUrl": "https://localhost:7041;http://localhost:5200",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/Employee.ApiGateway/appsettings.Development.json b/Employee.ApiGateway/appsettings.Development.json
new file mode 100644
index 00000000..32dc94eb
--- /dev/null
+++ b/Employee.ApiGateway/appsettings.Development.json
@@ -0,0 +1,11 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "GlobalConfiguration": {
+ "BaseUrl": "http://localhost:5200"
+ }
+}
diff --git a/Employee.ApiGateway/appsettings.json b/Employee.ApiGateway/appsettings.json
new file mode 100644
index 00000000..10f68b8c
--- /dev/null
+++ b/Employee.ApiGateway/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*"
+}
diff --git a/Employee.ApiGateway/ocelot.json b/Employee.ApiGateway/ocelot.json
new file mode 100644
index 00000000..c212a905
--- /dev/null
+++ b/Employee.ApiGateway/ocelot.json
@@ -0,0 +1,28 @@
+{
+ "Generators": [ "generator-1", "generator-2", "generator-3" ],
+ "Routes": [
+ {
+ "DownstreamPathTemplate": "/api/employee",
+ "DownstreamScheme": "http",
+ "DownstreamHostAndPorts": [
+ {
+ "Host": "localhost",
+ "Port": 5201
+ },
+ {
+ "Host": "localhost",
+ "Port": 5202
+ },
+ {
+ "Host": "localhost",
+ "Port": 5203
+ }
+ ],
+ "UpstreamPathTemplate": "/api/employee",
+ "UpstreamHttpMethod": [ "GET" ],
+ "LoadBalancerOptions": {
+ "Type": "QueryBasedLoadBalancer"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/Employee.ApiService/Employee.ApiService.csproj b/Employee.ApiService/Employee.ApiService.csproj
new file mode 100644
index 00000000..0c46690f
--- /dev/null
+++ b/Employee.ApiService/Employee.ApiService.csproj
@@ -0,0 +1,21 @@
+
+
+
+ net8.0
+ enable
+ enable
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Employee.ApiService/Models/EmployeeModel.cs b/Employee.ApiService/Models/EmployeeModel.cs
new file mode 100644
index 00000000..acf8a517
--- /dev/null
+++ b/Employee.ApiService/Models/EmployeeModel.cs
@@ -0,0 +1,58 @@
+namespace Employee.ApiService.Models;
+
+///
+/// Класс сотрудник компании
+///
+public class EmployeeModel
+{
+
+ ///
+ /// Идентификатор сотрудника в системе
+ ///
+ public required int Id { get; set; }
+
+ ///
+ /// ФИО
+ ///
+ public required string Name { get; set; }
+
+ ///
+ /// Должность
+ ///
+ public required string Position { get; set; }
+
+ ///
+ /// Отдел
+ ///
+ public required string Department { get; set; }
+
+ ///
+ /// Дата приема
+ ///
+ public required DateOnly DateAdmission { get; set; }
+
+ ///
+ /// Оклад
+ ///
+ public required decimal Salary { get; set; }
+
+ ///
+ /// Электронная почта
+ ///
+ public required string Email { get; set; }
+
+ ///
+ /// Номер телефона
+ ///
+ public required string Phone { get; set; }
+
+ ///
+ /// Индикатор увольнения
+ ///
+ public bool DismissalIndicator { get; set; } = false;
+
+ ///
+ /// Дата увольнения
+ ///
+ public DateOnly? DateDismissal { get; set; }
+}
diff --git a/Employee.ApiService/Program.cs b/Employee.ApiService/Program.cs
new file mode 100644
index 00000000..5c96b82c
--- /dev/null
+++ b/Employee.ApiService/Program.cs
@@ -0,0 +1,52 @@
+using Employee.ApiService.Models;
+using Employee.ApiService.Services;
+using Employee.ServiceDefaults;
+
+var builder = WebApplication.CreateBuilder(args);
+
+builder.AddServiceDefaults();
+builder.AddRedisDistributedCache("redis");
+
+builder.Services.AddEndpointsApiExplorer();
+builder.Services.AddSwaggerGen(options =>
+{
+ var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
+ var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
+
+ options.IncludeXmlComments(xmlPath);
+});
+
+builder.Services.AddCors(options =>
+{
+ options.AddPolicy("wasm", policy =>
+ {
+ policy.AllowAnyOrigin()
+ .AllowAnyMethod()
+ .AllowAnyHeader();
+ });
+});
+
+builder.Services.AddScoped();
+
+var app = builder.Build();
+
+if (app.Environment.IsDevelopment())
+{
+ app.UseSwagger();
+ app.UseSwaggerUI();
+}
+
+app.MapDefaultEndpoints();
+app.UseHttpsRedirection();
+app.UseCors("wasm");
+app.UseRouting();
+app.MapGet("/api/employee", async (int id, EmployeeService service) =>
+{
+ var employee = await service.GetEmployeeAsync(id);
+ return Results.Ok(employee);
+})
+.WithSummary(" ")
+.WithDescription(" id")
+.Produces(StatusCodes.Status200OK);
+
+app.Run();
\ No newline at end of file
diff --git a/Employee.ApiService/Properties/launchSettings.json b/Employee.ApiService/Properties/launchSettings.json
new file mode 100644
index 00000000..09b1f87b
--- /dev/null
+++ b/Employee.ApiService/Properties/launchSettings.json
@@ -0,0 +1,23 @@
+{
+ "$schema": "https://json.schemastore.org/launchsettings.json",
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": false,
+ "applicationUrl": "",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": false,
+ "applicationUrl": "",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/Employee.ApiService/Services/EmployeeGenerator.cs b/Employee.ApiService/Services/EmployeeGenerator.cs
new file mode 100644
index 00000000..364964bf
--- /dev/null
+++ b/Employee.ApiService/Services/EmployeeGenerator.cs
@@ -0,0 +1,115 @@
+using Bogus;
+using Employee.ApiService.Models;
+
+namespace Employee.ApiService.Services;
+
+///
+/// Генератор тестовых сотрудников
+///
+public static class EmployeeGenerator
+{
+ ///
+ /// Справочник профессий
+ ///
+ private static readonly string[] _professions =
+ [
+ "Developer",
+ "Manager",
+ "Analyst",
+ "QA",
+ "DevOps",
+ "Designer"
+ ];
+
+ ///
+ /// Справочник суффиксов должностей и коэффициентов зарплаты
+ ///
+ private static readonly Dictionary _positionLevels = new()
+ {
+ { "Junior", 0.7m },
+ { "Middle", 1.0m },
+ { "Senior", 1.5m },
+ { "Lead", 2.0m }
+ };
+
+ ///
+ /// Константа базовой зарплаты
+ ///
+ private const decimal BaseSalary = 100000m;
+
+ ///
+ /// Генерация зарплаты с учетом коэффициента уровня
+ ///
+ private static decimal GenerateSalary(Faker f, string position)
+ {
+ var level = _positionLevels.Keys.FirstOrDefault(position.Contains);
+
+ decimal coefficient = 1;
+
+ if (level != null)
+ {
+ coefficient = _positionLevels[level];
+ }
+
+ var randomFactor = f.Random.Decimal(0.9m, 1.1m);
+
+ var salary = BaseSalary * coefficient * randomFactor;
+
+ return Math.Round(salary, 2);
+ }
+
+ ///
+ /// Генерация ФИО
+ ///
+ private static string GenerateFullName(Faker f)
+ {
+ var gender = f.PickRandom();
+
+ var firstName = f.Name.FirstName(gender);
+ var lastName = f.Name.LastName(gender);
+
+ // имя отца
+ var fatherName = f.Name.FirstName(Bogus.DataSets.Name.Gender.Male);
+
+ var patronymic = gender == Bogus.DataSets.Name.Gender.Male
+ ? fatherName + "ович"
+ : fatherName + "овна";
+
+ return $"{lastName} {firstName} {patronymic}";
+ }
+
+ ///
+ /// Преднастроенный генератор
+ ///
+ private static readonly Faker _faker = new Faker("ru")
+ .RuleFor(e => e.Name, f => GenerateFullName(f))
+ .RuleFor(e => e.Position, f =>
+ {
+ var level = f.PickRandom(_positionLevels.Keys.ToArray());
+ var profession = f.PickRandom(_professions);
+ return $"{level} {profession}";
+ })
+ .RuleFor(e => e.Department, f => f.Commerce.Department())
+ .RuleFor(e => e.DateAdmission, f => f.Date.PastDateOnly(10))
+ .RuleFor(e => e.Salary, (f, e) => GenerateSalary(f, e.Position))
+ .RuleFor(e => e.Email, f => f.Internet.Email())
+ .RuleFor(e => e.Phone, f => f.Phone.PhoneNumber("+7(###)###-##-##"))
+ .RuleFor(e => e.DismissalIndicator, f => f.Random.Bool(0.2f))
+ .RuleFor(e => e.DateDismissal, (f, e) =>
+ e.DismissalIndicator
+ ? f.Date.BetweenDateOnly(e.DateAdmission, DateOnly.FromDateTime(DateTime.Now))
+ : null
+ );
+
+ ///
+ /// Генерация сотрудника
+ ///
+ public static EmployeeModel Generate(int id)
+ {
+ var employee = _faker.Generate();
+ employee.Id = id;
+
+ return employee;
+ }
+
+}
diff --git a/Employee.ApiService/Services/EmployeeService.cs b/Employee.ApiService/Services/EmployeeService.cs
new file mode 100644
index 00000000..f153f7a0
--- /dev/null
+++ b/Employee.ApiService/Services/EmployeeService.cs
@@ -0,0 +1,84 @@
+using Employee.ApiService.Models;
+using Microsoft.Extensions.Caching.Distributed;
+using System.Text.Json;
+
+namespace Employee.ApiService.Services;
+
+///
+/// Сервис получения сотрудников
+///
+/// кэш
+/// конфигурация
+/// логирование
+public class EmployeeService(
+ IDistributedCache cache,
+ IConfiguration configuration,
+ ILogger logger)
+{
+ ///
+ /// Время жизни записи в кэше
+ ///
+ private readonly TimeSpan _cacheExpiration =
+ TimeSpan.FromMinutes(configuration.GetValue("CacheSettings:ExpirationMinutes", 5));
+
+ ///
+ /// Получение сотрудника по id
+ ///
+ /// идентификатор
+ ///
+ public async Task GetEmployeeAsync(int id)
+ {
+ var cacheKey = $"employee:{id}";
+
+ logger.LogInformation("Attempting to retrieve employee {EmployeeId} from cache", id);
+
+ var cachedData = await cache.GetStringAsync(cacheKey);
+
+ if (!string.IsNullOrEmpty(cachedData))
+ {
+ try
+ {
+ var cachedEmployee = JsonSerializer.Deserialize(cachedData);
+
+ if (cachedEmployee != null)
+ {
+ logger.LogInformation("Employee {EmployeeId} retrieved from cache", id);
+ return cachedEmployee;
+ }
+
+ logger.LogWarning("Employee {EmployeeId} found in cache, but deserialization returned null", id);
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Error deserializing employee {EmployeeId}", id);
+ }
+ }
+
+ logger.LogInformation("Employee {EmployeeId} not found in cache. Generating new one", id);
+
+ var employee = EmployeeGenerator.Generate(id);
+
+ try
+ {
+ var cacheOptions = new DistributedCacheEntryOptions
+ {
+ AbsoluteExpirationRelativeToNow = _cacheExpiration
+ };
+
+ await cache.SetStringAsync(
+ cacheKey,
+ JsonSerializer.Serialize(employee),
+ cacheOptions
+ );
+
+ logger.LogInformation("Employee {EmployeeId} saved to cache", id);
+ }
+ catch (Exception ex)
+ {
+ logger.LogWarning(ex, "Failed to save employee {EmployeeId} to cache", id);
+ }
+
+ return employee;
+ }
+
+}
diff --git a/Employee.ApiService/appsettings.Development.json b/Employee.ApiService/appsettings.Development.json
new file mode 100644
index 00000000..0c208ae9
--- /dev/null
+++ b/Employee.ApiService/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/Employee.ApiService/appsettings.json b/Employee.ApiService/appsettings.json
new file mode 100644
index 00000000..10f68b8c
--- /dev/null
+++ b/Employee.ApiService/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*"
+}
diff --git a/Employee.AppHost/AppHost.cs b/Employee.AppHost/AppHost.cs
new file mode 100644
index 00000000..2b44ed34
--- /dev/null
+++ b/Employee.AppHost/AppHost.cs
@@ -0,0 +1,34 @@
+var builder = DistributedApplication.CreateBuilder(args);
+
+var redis = builder
+ .AddRedis("redis")
+ .WithRedisCommander();
+
+var generators = new List>();
+
+for (var i = 1; i <= 3; i++)
+{
+ var generator = builder
+ .AddProject($"generator-{i}")
+ .WithReference(redis)
+ .WithHttpEndpoint(name: $"http{i}", port: 5200 + i);
+
+ generators.Add(generator);
+}
+
+var apiGateway = builder.AddProject("employee-apigateway")
+ .WithHttpEndpoint(name: "gateway", port: 5200);
+
+foreach (var generator in generators)
+{
+ apiGateway
+ .WithReference(generator)
+ .WaitFor(generator);
+}
+
+builder.AddProject("webfrontend")
+ .WithExternalHttpEndpoints()
+ .WithReference(apiGateway)
+ .WaitFor(apiGateway);
+
+builder.Build().Run();
\ No newline at end of file
diff --git a/Employee.AppHost/Employee.AppHost.csproj b/Employee.AppHost/Employee.AppHost.csproj
new file mode 100644
index 00000000..93b27a05
--- /dev/null
+++ b/Employee.AppHost/Employee.AppHost.csproj
@@ -0,0 +1,24 @@
+
+
+
+
+
+ Exe
+ net8.0
+ enable
+ enable
+ 6ec37d7c-c0fa-45cb-977e-7d69bf172ad2
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Employee.AppHost/Properties/launchSettings.json b/Employee.AppHost/Properties/launchSettings.json
new file mode 100644
index 00000000..1de2e31b
--- /dev/null
+++ b/Employee.AppHost/Properties/launchSettings.json
@@ -0,0 +1,19 @@
+{
+ "$schema": "https://json.schemastore.org/launchsettings.json",
+ "profiles": {
+
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:15137",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development",
+ "DOTNET_ENVIRONMENT": "Development",
+ "ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true",
+ "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19281",
+ "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20030"
+ }
+ }
+ }
+}
diff --git a/Employee.AppHost/appsettings.Development.json b/Employee.AppHost/appsettings.Development.json
new file mode 100644
index 00000000..0c208ae9
--- /dev/null
+++ b/Employee.AppHost/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/Employee.AppHost/appsettings.json b/Employee.AppHost/appsettings.json
new file mode 100644
index 00000000..31c092aa
--- /dev/null
+++ b/Employee.AppHost/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning",
+ "Aspire.Hosting.Dcp": "Warning"
+ }
+ }
+}
diff --git a/Employee.ServiceDefaults/Employee.ServiceDefaults.csproj b/Employee.ServiceDefaults/Employee.ServiceDefaults.csproj
new file mode 100644
index 00000000..1b6e209a
--- /dev/null
+++ b/Employee.ServiceDefaults/Employee.ServiceDefaults.csproj
@@ -0,0 +1,22 @@
+
+
+
+ net8.0
+ enable
+ enable
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Employee.ServiceDefaults/Extensions.cs b/Employee.ServiceDefaults/Extensions.cs
new file mode 100644
index 00000000..cc077fbe
--- /dev/null
+++ b/Employee.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.Hosting;
+using Microsoft.Extensions.Logging;
+using OpenTelemetry;
+using OpenTelemetry.Metrics;
+using OpenTelemetry.Trace;
+
+namespace Employee.ServiceDefaults;
+
+///
+///
+///
+public static class Extensions
+{
+ private const string HealthEndpointPath = "/health";
+ private const string AlivenessEndpointPath = "/alive";
+
+ ///
+ ///
+ ///
+ 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;
+ }
+
+ ///
+ ///
+ ///
+ 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(tracing =>
+ tracing.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;
+ }
+
+ ///
+ ///
+ ///
+ public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder
+ {
+ builder.Services.AddHealthChecks()
+ .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);
+
+ return builder;
+ }
+
+ ///
+ ///
+ ///
+ 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;
+ }
+}
diff --git a/README.md b/README.md
index dcaa5eb7..8c5047e6 100644
--- a/README.md
+++ b/README.md
@@ -1,128 +1,48 @@
-# Современные технологии разработки программного обеспечения
-[Таблица с успеваемостью](https://docs.google.com/spreadsheets/d/1an43o-iqlq4V_kDtkr_y7DC221hY9qdhGPrpII27sH8/edit?usp=sharing)
+## Описание проекта
-## Задание
-### Цель
-Реализация проекта микросервисного бекенда.
+Проект представляет собой распределённую систему для получения информации о сотрудниках с использованием кэширования Redis и балансировки нагрузки по алгоритму Query Based.
-### Задачи
-* Реализация межсервисной коммуникации,
-* Изучение работы с брокерами сообщений,
-* Изучение архитектурных паттернов,
-* Изучение работы со средствами оркестрации на примере .NET Aspire,
-* Повторение основ работы с системами контроля версий,
-* Интеграционное тестирование.
+## Архитектура проекта
-### Лабораторные работы
-
-1. «Кэширование» - Реализация сервиса генерации контрактов, кэширование его ответов
-
-
-В рамках первой лабораторной работы необходимо:
-* Реализовать сервис генерации контрактов на основе Bogus,
-* Реализовать кеширование при помощи IDistributedCache и Redis,
-* Реализовать структурное логирование сервиса генерации,
-* Настроить оркестрацию Aspire.
-
-
-
-2. «Балансировка нагрузки» - Реализация апи гейтвея, настройка его работы
-
-
-В рамках второй лабораторной работы необходимо:
-* Настроить оркестрацию на запуск нескольких реплик сервиса генерации,
-* Реализовать апи гейтвей на основе Ocelot,
-* Имплементировать алгоритм балансировки нагрузки согласно варианту.
+Решение состоит из нескольких проектов:
-
-
-
-3. «Интеграционное тестирование» - Реализация файлового сервиса и объектного хранилища, интеграционное тестирование бекенда
-
+- **Employee.ApiService** – Web API сервис
+- **Employee.ApiGateway** – API Gateway на базе Ocelot
+- **Employee.AppHost** – Aspire orchestrator
+- **Employee.ServiceDefaults** – общие настройки сервисов
+- **Client.Wasm** – клиент
-В рамках третьей лабораторной работы необходимо:
-* Добавить в оркестрацию объектное хранилище,
-* Реализовать файловый сервис, сериализующий сгенерированные данные в файлы и сохраняющий их в объектном хранилище,
-* Реализовать отправку генерируемых данных в файловый сервис посредством брокера,
-* Реализовать интеграционные тесты, проверяющие корректность работы всех сервисов бекенда вместе.
+## Основная логика работы
-
-
-
-4. (Опционально) «Переход на облачную инфраструктуру» - Перенос бекенда в Yandex Cloud
-
+1. Клиент отправляет запрос в API Gateway (`/api/employee?id={id}`).
+2. API Gateway (Ocelot) принимает запрос и передаёт его в один из сервисов генерации.
+3. Выбор сервиса осуществляется с помощью кастомного балансировщика `QueryBasedLoadBalancer`.
+4. Сервис:
+ - проверяет наличие данных в Redis,
+ - если данные есть — возвращает их из кэша,
+ - если нет — генерирует нового сотрудника и сохраняет его в кэш.
-В рамках четвертой лабораторной работы необходимо перенестиервисы на облако все ранее разработанные сервисы:
-* Клиент - в хостинг через отдельный бакет 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 диаграмма
-
-
-
-## Варианты заданий
-Номер варианта задания присваивается в начале семестра. Изменить его нельзя. Каждый вариант имеет уникальную комбинацию из предметной области, базы данных и технологии для общения сервиса генерации данных и сервера апи.
-
-[Список вариантов](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. Полнота выполнения задания
+С помощью Aspire настроен запуск нескольких реплик сервиса генерации:
-Быстрее делаете PR - у вас преимущество.
-Быстрее получаете Approve - у вас преимущество.
-Выполните нечто немного выходящее за рамки проекта - у вас преимущество.
-Не укладываетесь в дедлайн - получаете минимально возможный балл.
+- generator-1 → http://localhost:5201
+- generator-2 → http://localhost:5202
+- generator-3 → http://localhost:5203
-### Шкала оценивания
+## Запуск проекта
-- **3 балла** за качество кода, из них:
- - 2 балла - базовая оценка
- - 1 балл (но не более) можно получить за выполнение любого из следующих пунктов:
- - Реализация факультативного функционала
- - Выполнение работы раньше других: первые 5 человек из каждой группы, которые сделали PR и получили approve, получают дополнительный балл
-
-## Вопросы и обратная связь по курсу
+1. Запустить проект **Employee.AppHost**.
+2. Aspire Dashboard откроется автоматически.
+3. В Dashboard будут запущены:
+ - Redis
+ - Redis Commander
+ - 3 реплики Employee.ApiService
+ - API Gateway
+ - WebFrontend
+ -
+## Пример работы приложения
+
+
-Чтобы задать вопрос по лабораторной, воспользуйтесь [соответствующим разделом дискуссий](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).