RoundRobin loadblancer cause config error https://github.com/TomPallister/Ocelot/issues/103

This commit is contained in:
geffzhang 2017-06-03 22:32:47 +08:00
parent 54db27100d
commit 02162dd7a6
3 changed files with 11 additions and 6 deletions

View File

@ -19,7 +19,7 @@ namespace Ocelot.LoadBalancer.LoadBalancers
switch (reRoute.LoadBalancer) switch (reRoute.LoadBalancer)
{ {
case "RoundRobin": case "RoundRobin":
return new RoundRobinLoadBalancer(await serviceProvider.Get()); return new RoundRobinLoadBalancer(async () => await serviceProvider.Get());
case "LeastConnection": case "LeastConnection":
return new LeastConnectionLoadBalancer(async () => await serviceProvider.Get(), reRoute.ServiceProviderConfiguraion.ServiceName); return new LeastConnectionLoadBalancer(async () => await serviceProvider.Get(), reRoute.ServiceProviderConfiguraion.ServiceName);
default: default:

View File

@ -2,27 +2,31 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Ocelot.Responses; using Ocelot.Responses;
using Ocelot.Values; using Ocelot.Values;
using System;
namespace Ocelot.LoadBalancer.LoadBalancers namespace Ocelot.LoadBalancer.LoadBalancers
{ {
public class RoundRobinLoadBalancer : ILoadBalancer public class RoundRobinLoadBalancer : ILoadBalancer
{ {
private readonly List<Service> _services; private readonly Func<Task<List<Service>>> _services;
private int _last; private int _last;
public RoundRobinLoadBalancer(List<Service> services) public RoundRobinLoadBalancer(Func<Task<List<Service>>> services)
{ {
_services = services; _services = services;
} }
public async Task<Response<HostAndPort>> Lease() public async Task<Response<HostAndPort>> Lease()
{ {
if (_last >= _services.Count) var services = await _services.Invoke();
if (_last >= services.Count)
{ {
_last = 0; _last = 0;
} }
var next = await Task.FromResult(_services[_last]); var next = await Task.FromResult(services[_last]);
_last++; _last++;
return new OkResponse<HostAndPort>(next.HostAndPort); return new OkResponse<HostAndPort>(next.HostAndPort);
} }

View File

@ -6,6 +6,7 @@ using Ocelot.Values;
using Shouldly; using Shouldly;
using TestStack.BDDfy; using TestStack.BDDfy;
using Xunit; using Xunit;
using System.Threading.Tasks;
namespace Ocelot.UnitTests.LoadBalancer namespace Ocelot.UnitTests.LoadBalancer
{ {
@ -24,7 +25,7 @@ namespace Ocelot.UnitTests.LoadBalancer
new Service("product", new HostAndPort("127.0.0.1", 5001), string.Empty, string.Empty, new string[0]) new Service("product", new HostAndPort("127.0.0.1", 5001), string.Empty, string.Empty, new string[0])
}; };
_roundRobin = new RoundRobinLoadBalancer(_services); _roundRobin = new RoundRobinLoadBalancer(() => Task.FromResult(_services));
} }
[Fact] [Fact]