Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added 1.PNG
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions ApiGateway/ApiGateway.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>ApiGateway</AssemblyName>
<RootNamespace>ApiGateway</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Ocelot" Version="24.1.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\AspireApp\AspireApp.ServiceDefaults\AspireApp.ServiceDefaults.csproj" />
</ItemGroup>

<ItemGroup>
<Content Update="ocelot.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>

</Project>
16 changes: 16 additions & 0 deletions ApiGateway/Configuration/WeightedRoundRobinOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace ApiGateway.Configuration;

public sealed class WeightedRoundRobinOptions
{
public const string SectionName = "WeightedRoundRobin";

public List<ReplicaNodeOptions> Nodes { get; init; } = new();
}

public sealed class ReplicaNodeOptions
{
public string Host { get; init; } = string.Empty;
public int Port { get; init; }
public int Weight { get; init; } = 1;
public string ReplicaId { get; init; } = string.Empty;
}
72 changes: 72 additions & 0 deletions ApiGateway/LoadBalancing/WeightedRoundRobinBalancer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using ApiGateway.Configuration;
using Microsoft.Extensions.Options;
using Ocelot.LoadBalancer.Interfaces;
using Ocelot.Responses;
using Ocelot.Values;

namespace ApiGateway.LoadBalancing;

public sealed class WeightedRoundRobinBalancer : ILoadBalancer
{
private static readonly object Sync = new();
private readonly ILogger<WeightedRoundRobinBalancer> _logger;
private readonly List<ServiceHostAndPort> _rotation;
private int _currentIndex;

public WeightedRoundRobinBalancer(
IOptions<WeightedRoundRobinOptions> options,
ILogger<WeightedRoundRobinBalancer> logger)
{
_logger = logger;
_rotation = BuildRotation(options.Value.Nodes);

if (_rotation.Count == 0)
{
throw new InvalidOperationException("Не настроены узлы для Weighted Round Robin балансировки.");
}
}

public string Type => nameof(WeightedRoundRobinBalancer);

public Task<Response<ServiceHostAndPort>> LeaseAsync(HttpContext context)
{
lock (Sync)
{
if (_currentIndex >= _rotation.Count)
{
_currentIndex = 0;
}

var next = _rotation[_currentIndex++];

_logger.LogInformation(
"Gateway routed request to {ReplicaAddress} by {BalancerType}",
next,
Type);

return Task.FromResult<Response<ServiceHostAndPort>>(
new OkResponse<ServiceHostAndPort>(next));
}
}

public void Release(ServiceHostAndPort hostAndPort)
{
}

private static List<ServiceHostAndPort> BuildRotation(IEnumerable<ReplicaNodeOptions> nodes)
{
var rotation = new List<ServiceHostAndPort>();

foreach (var node in nodes.Where(static n => !string.IsNullOrWhiteSpace(n.Host) && n.Port > 0))
{
var normalizedWeight = Math.Max(1, node.Weight);

for (var i = 0; i < normalizedWeight; i++)
{
rotation.Add(new ServiceHostAndPort(node.Host, node.Port));
}
}

return rotation;
}
}
43 changes: 43 additions & 0 deletions ApiGateway/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using ApiGateway.Configuration;
using ApiGateway.LoadBalancing;
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.Logging.ClearProviders();
builder.Logging.AddJsonConsole(options =>
{
options.IncludeScopes = true;
options.TimestampFormat = "yyyy-MM-ddTHH:mm:ss.fffZ ";
});

builder.Services.Configure<WeightedRoundRobinOptions>(
builder.Configuration.GetSection(WeightedRoundRobinOptions.SectionName));

builder.Services.AddOcelot(builder.Configuration)
.AddCustomLoadBalancer<WeightedRoundRobinBalancer>(sp =>
new WeightedRoundRobinBalancer(
sp.GetRequiredService<Microsoft.Extensions.Options.IOptions<WeightedRoundRobinOptions>>(),
sp.GetRequiredService<ILogger<WeightedRoundRobinBalancer>>()));

builder.Services.AddCors(options => options.AddDefaultPolicy(policy =>
{
policy.WithOrigins(["http://localhost:5127", "https://localhost:7282"]);
policy.WithMethods("GET");
policy.WithHeaders("Content-Type");
policy.WithExposedHeaders("X-Service-Replica", "X-Service-Weight");
}));

var app = builder.Build();

app.UseCors();
app.MapDefaultEndpoints();

await app.UseOcelot();

app.Run();
14 changes: 14 additions & 0 deletions ApiGateway/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:7200",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
9 changes: 9 additions & 0 deletions ApiGateway/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Ocelot": "Information"
}
}
}
10 changes: 10 additions & 0 deletions ApiGateway/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Ocelot": "Information"
}
},
"AllowedHosts": "*"
}
32 changes: 32 additions & 0 deletions ApiGateway/ocelot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"Routes": [
{
"UpstreamPathTemplate": "/employee",
"UpstreamHttpMethod": [ "GET" ],
"DownstreamPathTemplate": "/employee",
"DownstreamScheme": "https",
"LoadBalancerOptions": {
"Type": "WeightedRoundRobinBalancer"
},
"DownstreamHostAndPorts": [
{ "Host": "localhost", "Port": 15000 },
{ "Host": "localhost", "Port": 15001 },
{ "Host": "localhost", "Port": 15002 },
{ "Host": "localhost", "Port": 15003 },
{ "Host": "localhost", "Port": 15004 }
]
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost:7200"
},
"WeightedRoundRobin": {
"Nodes": [
{ "ReplicaId": "R1", "Host": "localhost", "Port": 15000, "Weight": 1 },
{ "ReplicaId": "R2", "Host": "localhost", "Port": 15001, "Weight": 2 },
{ "ReplicaId": "R3", "Host": "localhost", "Port": 15002, "Weight": 3 },
{ "ReplicaId": "R4", "Host": "localhost", "Port": 15003, "Weight": 2 },
{ "ReplicaId": "R5", "Host": "localhost", "Port": 15004, "Weight": 1 }
]
}
}
25 changes: 25 additions & 0 deletions AspireApp/AspireApp.AppHost/AppHost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddRedis("employee-cache")
.WithRedisInsight(containerName: "employee-insight");

var gateway = builder.AddProject<Projects.ApiGateway>("api-gateway");

var replicaWeights = new[] { 1, 2, 3, 2, 1 };

for (var i = 0; i < 5; i++)
{
var service = builder.AddProject<Projects.Service_Api>($"service-api-{i}", launchProfileName: null)
.WithHttpsEndpoint(port: 15000 + i)
.WithReference(cache, "RedisCache")
.WithEnvironment("ReplicaId", "R" + (i + 1))
.WithEnvironment("ReplicaWeight", replicaWeights[i].ToString())
.WaitFor(cache);

gateway.WaitFor(service);
}

builder.AddProject<Projects.Client_Wasm>("employee")
.WaitFor(gateway);

builder.Build().Run();
24 changes: 24 additions & 0 deletions AspireApp/AspireApp.AppHost/AspireApp.AppHost.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<Sdk Name="Aspire.AppHost.Sdk" Version="9.0.0" />

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireHost>true</IsAspireHost>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.0.0" />
<PackageReference Include="Aspire.Hosting.Redis" Version="9.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\ApiGateway\ApiGateway.csproj" />
<ProjectReference Include="..\..\Client.Wasm\Client.Wasm.csproj" />
<ProjectReference Include="..\..\ServiceApi\Service.Api.csproj" />
</ItemGroup>

</Project>
32 changes: 32 additions & 0 deletions AspireApp/AspireApp.AppHost/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:17096;http://localhost:15155",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21139",
"DOTNET_DASHBOARD_OTLP_HTTP_ENDPOINT_URL": "https://localhost:21140",
"DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22017"
}
},
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:15155",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"DOTNET_ENVIRONMENT": "Development",
"ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true",
"DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19197",
"DOTNET_DASHBOARD_OTLP_HTTP_ENDPOINT_URL": "http://localhost:19198",
"DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20116"
}
}
}
}
8 changes: 8 additions & 0 deletions AspireApp/AspireApp.AppHost/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Aspire.Hosting": "Information"
}
}
}
8 changes: 8 additions & 0 deletions AspireApp/AspireApp.AppHost/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Aspire.Hosting": "Information"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireSharedProject>true</IsAspireSharedProject>
</PropertyGroup>

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="9.0.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
</ItemGroup>

</Project>
Loading
Loading