-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathQueryBasedLoadBalancer.cs
More file actions
47 lines (38 loc) · 1.54 KB
/
QueryBasedLoadBalancer.cs
File metadata and controls
47 lines (38 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using Ocelot.LoadBalancer.Interfaces;
using Ocelot.Responses;
using Ocelot.Values;
namespace ProgramProject.Gateway.LoadBalancers;
/// <summary>
/// Балансировщик для алгоритма Query Based
/// </summary>
public class QueryBasedLoadBalancer : ILoadBalancer
{
private readonly List<Service> _services;
private readonly ILogger<QueryBasedLoadBalancer> _logger;
private readonly string _queryParameterName;
public QueryBasedLoadBalancer(List<Service> services, ILogger<QueryBasedLoadBalancer> logger, string queryParameterName = "id")
{
_services = services;
_logger = logger;
_queryParameterName = queryParameterName;
}
public string Type => nameof(QueryBasedLoadBalancer);
public async Task<Response<ServiceHostAndPort>> LeaseAsync(HttpContext httpContext)
{
var idValue = ExtractIdFromQuery(httpContext);
var replicaIndex = Math.Abs(idValue) % _services.Count;
var selectedService = _services[replicaIndex];
_logger.LogInformation("Запрос с id={Id} направлен на реплику {Index}", idValue, replicaIndex);
return new OkResponse<ServiceHostAndPort>(selectedService.HostAndPort);
}
private int ExtractIdFromQuery(HttpContext context)
{
if (context.Request.Query.TryGetValue(_queryParameterName, out var idString))
{
if (int.TryParse(idString, out var id))
return id;
}
return 0;
}
public void Release(ServiceHostAndPort hostAndPort) { }
}