Browse Source

Merge remote-tracking branch 'origin/3.1.x'

pull/1057/merge
Olga Maciaszek-Sharma 3 years ago
parent
commit
66b295529e
  1. 7
      spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RoundRobinLoadBalancer.java
  2. 23
      spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/RoundRobinLoadBalancerTest.java

7
spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RoundRobinLoadBalancer.java

@ -100,10 +100,9 @@ public class RoundRobinLoadBalancer implements ReactorServiceInstanceLoadBalance @@ -100,10 +100,9 @@ public class RoundRobinLoadBalancer implements ReactorServiceInstanceLoadBalance
return new EmptyResponse();
}
int pos = this.position.incrementAndGet();
if (pos < 0) {
pos = pos & Integer.MAX_VALUE;
}
// Ignore the sign bit, this allows pos to loop sequentially from 0 to
// Integer.MAX_VALUE
int pos = this.position.incrementAndGet() & Integer.MAX_VALUE;
ServiceInstance instance = instances.get(pos % instances.size());

23
spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/RoundRobinLoadBalancerTest.java

@ -26,6 +26,7 @@ import org.springframework.cloud.client.ServiceInstance; @@ -26,6 +26,7 @@ import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.support.SimpleObjectProvider;
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Integer.MIN_VALUE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
@ -37,7 +38,22 @@ import static org.mockito.Mockito.when; @@ -37,7 +38,22 @@ import static org.mockito.Mockito.when;
class RoundRobinLoadBalancerTest {
@Test
void shouldEnforceOrderWhenPositiveOverflow() {
void shouldOrderEnforcedWhenPositive() {
assertOrderEnforced(0);
}
@Test
void shouldOrderEnforcedWhenNegative() {
assertOrderEnforced(MIN_VALUE);
}
@Test
void shouldOrderEnforcedWhenPositiveOverflow() {
assertOrderEnforced(MAX_VALUE);
}
@SuppressWarnings("all")
void assertOrderEnforced(int seed) {
List<ServiceInstance> instances = new ArrayList<>();
for (int i = 0; i < 10; i++) {
ServiceInstance instance = mock(ServiceInstance.class);
@ -49,11 +65,12 @@ class RoundRobinLoadBalancerTest { @@ -49,11 +65,12 @@ class RoundRobinLoadBalancerTest {
when(supplier.get(any())).thenReturn(Flux.just(instances));
RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer(new SimpleObjectProvider<>(supplier),
"shouldStartFromZeroWhenPositiveOverflow", MAX_VALUE);
"shouldStartFromZeroWhenPositiveOverflow", seed);
for (int i = 0; i < 10; i++) {
int instanceId = ((seed + 1 + i) & MAX_VALUE) % instances.size();
ServiceInstance chosen = loadBalancer.choose().block().getServer();
assertThat(chosen.getInstanceId()).isEqualTo(i + "");
assertThat(chosen.getInstanceId()).isEqualTo(instanceId + "");
}
}

Loading…
Cancel
Save