-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path05_RoundRobin.cs
More file actions
52 lines (46 loc) · 1.71 KB
/
05_RoundRobin.cs
File metadata and controls
52 lines (46 loc) · 1.71 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
48
49
50
51
52
using System;
using System.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace ProxyKit.Recipes
{
public class RoundRobinLoadBalancer : Recipe<RoundRobinLoadBalancer.Startup>
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
//Client timeouts if upstream host doesn't respond in 5 seconds
services.AddProxy(
httpClientBuilder => httpClientBuilder
.ConfigureHttpClient(client => client.Timeout = TimeSpan.FromSeconds(5)));
}
public void Configure(IApplicationBuilder app)
{
var roundRobin = new RoundRobin
{
new UpstreamHost("http://localhost:5001", weight: 1),
new UpstreamHost("http://localhost:5002", weight: 2)
};
app.RunProxy(
async context =>
{
var host = roundRobin.Next();
var response = await context
.ForwardTo(host)
.AddXForwardedHeaders()
.Send();
// failover
if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
{
return await context
.ForwardTo(host)
.AddXForwardedHeaders()
.Send();
}
return response;
});
}
}
}
}