publisher,
@@ -193,5 +225,7 @@ public class HystrixCommands {
}
return super.resumeWithFallback();
}
+
}
+
}
diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixConstants.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixConstants.java
index 073eec025..a1e167b2c 100644
--- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixConstants.java
+++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixConstants.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,8 +19,11 @@ package org.springframework.cloud.netflix.hystrix;
/**
* @author Spencer Gibb
*/
-public class HystrixConstants {
+public final class HystrixConstants {
+ /**
+ * Hystrix stream destination name.
+ */
public static final String HYSTRIX_STREAM_DESTINATION = "springCloudHystrixStream";
private HystrixConstants() {
diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixHealthIndicator.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixHealthIndicator.java
index fb1a8bfe5..e95946d16 100644
--- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixHealthIndicator.java
+++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixHealthIndicator.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2014 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,18 +19,18 @@ package org.springframework.cloud.netflix.hystrix;
import java.util.ArrayList;
import java.util.List;
+import com.netflix.hystrix.HystrixCircuitBreaker;
+import com.netflix.hystrix.HystrixCommandMetrics;
+
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health.Builder;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.Status;
-import com.netflix.hystrix.HystrixCircuitBreaker;
-import com.netflix.hystrix.HystrixCommandMetrics;
-
/**
* A {@link HealthIndicator} implementation for Hystrix circuit breakers.
*
- * This default implementation will not change the system state (e.g. OK) but
+ * This default implementation will not change the system state (e.g. OK) but
* includes all open circuits by name.
*
* @author Christian Dupuis
diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixMetricsProperties.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixMetricsProperties.java
index 5501efd6a..1deea322d 100644
--- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixMetricsProperties.java
+++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixMetricsProperties.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2016 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,10 @@
package org.springframework.cloud.netflix.hystrix;
-import org.springframework.boot.context.properties.ConfigurationProperties;
-
import java.util.Objects;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
/**
* @author Venil Noronha
* @author Gregor Zurowski
@@ -51,11 +51,15 @@ public class HystrixMetricsProperties {
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
HystrixMetricsProperties that = (HystrixMetricsProperties) o;
- return enabled == that.enabled &&
- Objects.equals(pollingIntervalMs, that.pollingIntervalMs);
+ return enabled == that.enabled
+ && Objects.equals(pollingIntervalMs, that.pollingIntervalMs);
}
@Override
@@ -65,9 +69,9 @@ public class HystrixMetricsProperties {
@Override
public String toString() {
- return new StringBuilder("HystrixMetricsProperties{")
- .append("enabled=").append(enabled).append(", ")
- .append("pollingIntervalMs=").append(pollingIntervalMs)
- .append("}").toString();
+ return new StringBuilder("HystrixMetricsProperties{").append("enabled=")
+ .append(enabled).append(", ").append("pollingIntervalMs=")
+ .append(pollingIntervalMs).append("}").toString();
}
+
}
diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixProperties.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixProperties.java
index 2039c62c1..620ff2f50 100644
--- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixProperties.java
+++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixProperties.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.hystrix;
@@ -42,4 +41,3 @@ public class HystrixProperties {
}
}
-
diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpoint.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpoint.java
index af2d870b9..5fb241e5a 100644
--- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpoint.java
+++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpoint.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,20 +12,21 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.hystrix;
-import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
-import org.springframework.boot.actuate.endpoint.web.EndpointServlet;
-import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpoint;
-
import java.util.Map;
import java.util.function.Supplier;
+import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
+
+import org.springframework.boot.actuate.endpoint.web.EndpointServlet;
+import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpoint;
+
/**
- * {@link org.springframework.boot.actuate.endpoint.annotation.Endpoint} to expose a Jolokia {@link HystrixMetricsStreamServlet}.
+ * {@link org.springframework.boot.actuate.endpoint.annotation.Endpoint} to expose a
+ * Jolokia {@link HystrixMetricsStreamServlet}.
*
* @author Phillip Webb
* @since 2.0.0
@@ -33,15 +34,16 @@ import java.util.function.Supplier;
@ServletEndpoint(id = "hystrix.stream")
public class HystrixStreamEndpoint implements Supplier {
- private final Map initParameters;
+ private final Map initParameters;
- public HystrixStreamEndpoint(Map initParameters) {
- this.initParameters = initParameters;
- }
+ public HystrixStreamEndpoint(Map initParameters) {
+ this.initParameters = initParameters;
+ }
+
+ @Override
+ public EndpointServlet get() {
+ return new EndpointServlet(HystrixMetricsStreamServlet.class)
+ .withInitParameters(this.initParameters);
+ }
- @Override
- public EndpointServlet get() {
- return new EndpointServlet(HystrixMetricsStreamServlet.class)
- .withInitParameters(this.initParameters);
- }
}
diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpoint.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpoint.java
index a9f4f220d..88eff84ea 100644
--- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpoint.java
+++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpoint.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.hystrix;
@@ -20,28 +19,29 @@ package org.springframework.cloud.netflix.hystrix;
import java.time.Duration;
import org.reactivestreams.Publisher;
+import reactor.core.publisher.Flux;
+
import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
-import reactor.core.publisher.Flux;
-
/**
* @author Spencer Gibb
*/
@RestControllerEndpoint(id = "hystrix.stream")
public class HystrixWebfluxEndpoint {
- private final Flux stream;
+ private final Flux stream;
- public HystrixWebfluxEndpoint(Publisher dashboardData) {
- stream = Flux.interval(Duration.ofMillis(500)).map(aLong -> "{\"type\":\"ping\"}")
- .mergeWith(dashboardData).share();
- }
+ public HystrixWebfluxEndpoint(Publisher dashboardData) {
+ stream = Flux.interval(Duration.ofMillis(500)).map(aLong -> "{\"type\":\"ping\"}")
+ .mergeWith(dashboardData).share();
+ }
+
+ // path needs to be empty, so it registers correct as /actuator/hystrix.stream
+ @GetMapping(path = "", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
+ public Flux hystrixStream() {
+ return stream;
+ }
- // path needs to be empty, so it registers correct as /actuator/hystrix.stream
- @GetMapping(path = "", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
- public Flux hystrixStream() {
- return stream;
- }
}
diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfiguration.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfiguration.java
index d2eddf08f..3e2f4a6a6 100644
--- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfiguration.java
+++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfiguration.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2016 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,9 +18,17 @@ package org.springframework.cloud.netflix.hystrix.security;
import javax.annotation.PostConstruct;
+import com.netflix.hystrix.Hystrix;
+import com.netflix.hystrix.strategy.HystrixPlugins;
+import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
+import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
+import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
+import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
+import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.AllNestedConditions;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@@ -30,14 +38,6 @@ import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContext;
-import com.netflix.hystrix.Hystrix;
-import com.netflix.hystrix.strategy.HystrixPlugins;
-import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
-import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
-import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
-import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
-import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
-
/**
* @author Daniel Lavoie
*/
@@ -45,7 +45,10 @@ import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
@Conditional(HystrixSecurityCondition.class)
@ConditionalOnClass({ Hystrix.class, SecurityContext.class })
public class HystrixSecurityAutoConfiguration {
- private static final Log LOGGER = LogFactory.getLog(HystrixSecurityAutoConfiguration.class);
+
+ private static final Log LOGGER = LogFactory
+ .getLog(HystrixSecurityAutoConfiguration.class);
+
@Autowired(required = false)
private HystrixConcurrencyStrategy existingConcurrencyStrategy;
@@ -79,20 +82,22 @@ public class HystrixSecurityAutoConfiguration {
if (existingConcurrencyStrategy == null) {
return registeredStrategy;
}
- //Hystrix registered a default Strategy.
- if (registeredStrategy instanceof HystrixConcurrencyStrategyDefault){
+ // Hystrix registered a default Strategy.
+ if (registeredStrategy instanceof HystrixConcurrencyStrategyDefault) {
return existingConcurrencyStrategy;
}
- //If registeredStrategy not the default and not some use bean of existingConcurrencyStrategy.
- if (!existingConcurrencyStrategy.equals(registeredStrategy)){
- LOGGER.warn("Multiple HystrixConcurrencyStrategy detected. Bean of HystrixConcurrencyStrategy was used.");
+ // If registeredStrategy not the default and not some use bean of
+ // existingConcurrencyStrategy.
+ if (!existingConcurrencyStrategy.equals(registeredStrategy)) {
+ LOGGER.warn(
+ "Multiple HystrixConcurrencyStrategy detected. Bean of HystrixConcurrencyStrategy was used.");
}
return existingConcurrencyStrategy;
}
static class HystrixSecurityCondition extends AllNestedConditions {
- public HystrixSecurityCondition() {
+ HystrixSecurityCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@@ -100,5 +105,7 @@ public class HystrixSecurityAutoConfiguration {
static class ShareSecurityContext {
}
+
}
+
}
diff --git a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/SecurityContextConcurrencyStrategy.java b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/SecurityContextConcurrencyStrategy.java
index a438882c8..2d35a8a5b 100644
--- a/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/SecurityContextConcurrencyStrategy.java
+++ b/spring-cloud-netflix-hystrix/src/main/java/org/springframework/cloud/netflix/hystrix/security/SecurityContextConcurrencyStrategy.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2016 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,19 +21,20 @@ import java.util.concurrent.Callable;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
-import com.netflix.hystrix.HystrixThreadPoolProperties;
-import org.springframework.security.concurrent.DelegatingSecurityContextCallable;
-
import com.netflix.hystrix.HystrixThreadPoolKey;
+import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariable;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
+import org.springframework.security.concurrent.DelegatingSecurityContextCallable;
+
/**
- * @author daniellavoie
+ * @author Daniel Lavoie
*/
public class SecurityContextConcurrencyStrategy extends HystrixConcurrencyStrategy {
+
private HystrixConcurrencyStrategy existingConcurrencyStrategy;
public SecurityContextConcurrencyStrategy(
@@ -70,9 +71,11 @@ public class SecurityContextConcurrencyStrategy extends HystrixConcurrencyStrate
}
@Override
- public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties threadPoolProperties) {
+ public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
+ HystrixThreadPoolProperties threadPoolProperties) {
return existingConcurrencyStrategy != null
- ? existingConcurrencyStrategy.getThreadPool(threadPoolKey, threadPoolProperties)
+ ? existingConcurrencyStrategy.getThreadPool(threadPoolKey,
+ threadPoolProperties)
: super.getThreadPool(threadPoolKey, threadPoolProperties);
}
@@ -83,4 +86,5 @@ public class SecurityContextConcurrencyStrategy extends HystrixConcurrencyStrate
.wrapCallable(new DelegatingSecurityContextCallable(callable))
: super.wrapCallable(new DelegatingSecurityContextCallable(callable));
}
+
}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfigurationTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfigurationTests.java
index 094ef8c75..c8d12d10a 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfigurationTests.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixAutoConfigurationTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.hystrix;
@@ -38,14 +37,15 @@ import static org.assertj.core.api.Assertions.fail;
public class HystrixAutoConfigurationTests {
@Test
- @Ignore //TODO: why does this test fail in maven, but not in IDE?
+ @Ignore // TODO: why does this test fail in maven, but not in IDE?
public void contextStarts() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder()
.web(WebApplicationType.NONE).sources(TestApp.class).run()) {
try {
context.getBean("hystrixMetricsBinder");
fail("HystrixMetricsBinder class should not be found");
- } catch (NoSuchBeanDefinitionException e) {
+ }
+ catch (NoSuchBeanDefinitionException e) {
// this is the correct case
}
}
@@ -54,5 +54,8 @@ public class HystrixAutoConfigurationTests {
@EnableCircuitBreaker
@SpringBootConfiguration
@EnableAutoConfiguration
- protected static class TestApp {}
-}
\ No newline at end of file
+ protected static class TestApp {
+
+ }
+
+}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java
index 616a4fc4d..3e5d1b0aa 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixCommandsTests.java
@@ -1,11 +1,11 @@
/*
- * Copyright 2013-2017 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -18,10 +18,8 @@ package org.springframework.cloud.netflix.hystrix;
import java.time.Duration;
-import org.junit.Test;
-
import com.netflix.hystrix.exception.HystrixRuntimeException;
-
+import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
@@ -31,20 +29,15 @@ public class HystrixCommandsTests {
@Test
public void monoWorks() {
StepVerifier.create(HystrixCommands.from(Flux.just("works"))
- .commandName("testworks")
- .toMono())
- .expectNext("works")
- .verifyComplete();
+ .commandName("testworks").toMono()).expectNext("works").verifyComplete();
}
@Test
public void eagerMonoWorks() {
- StepVerifier.create(HystrixCommands.from(Mono.just("works"))
- .eager()
- .commandName("testworks")
- .toMono())
- .expectNext("works")
- .verifyComplete();
+ StepVerifier
+ .create(HystrixCommands.from(Mono.just("works")).eager()
+ .commandName("testworks").toMono())
+ .expectNext("works").verifyComplete();
}
@Test
@@ -52,101 +45,81 @@ public class HystrixCommandsTests {
StepVerifier.create(HystrixCommands.from(Mono.fromCallable(() -> {
Thread.sleep(1500);
return "timeout";
- })).commandName("failcmd").toMono())
- .verifyError(HystrixRuntimeException.class);
+ })).commandName("failcmd").toMono()).verifyError(HystrixRuntimeException.class);
}
@Test
public void monoFallbackWorks() {
- StepVerifier.create(HystrixCommands.from(Mono.error(new Exception()))
- .commandName("failcmd")
- .fallback(Mono.just("fallback"))
- .toMono())
- .expectNext("fallback")
- .verifyComplete();
+ StepVerifier
+ .create(HystrixCommands.from(Mono.error(new Exception()))
+ .commandName("failcmd").fallback(Mono.just("fallback")).toMono())
+ .expectNext("fallback").verifyComplete();
}
@Test
public void monoFallbackWithExceptionWorks() {
- StepVerifier.create(HystrixCommands.from(Mono.error(new IllegalStateException()))
- .commandName("failcmd")
- .fallback(throwable -> {
- if (throwable instanceof IllegalStateException) {
- return Mono.just("specificfallback");
- }
- return Mono.just("genericfallback");
- })
- .toMono())
- .expectNext("specificfallback")
- .verifyComplete();
+ StepVerifier.create(
+ HystrixCommands.from(Mono.error(new IllegalStateException()))
+ .commandName("failcmd").fallback(throwable -> {
+ if (throwable instanceof IllegalStateException) {
+ return Mono.just("specificfallback");
+ }
+ return Mono.just("genericfallback");
+ }).toMono())
+ .expectNext("specificfallback").verifyComplete();
}
@Test
public void fluxWorks() {
- StepVerifier.create(HystrixCommands.from( Flux.just("1", "2"))
- .commandName("multiflux")
- .toFlux())
- .expectNext("1")
- .expectNext("2")
+ StepVerifier.create(HystrixCommands.from(Flux.just("1", "2"))
+ .commandName("multiflux").toFlux()).expectNext("1").expectNext("2")
.verifyComplete();
}
@Test
public void fluxWorksDeferredRequest() {
- StepVerifier.create(HystrixCommands.from(Flux.just("1", "2"))
- .commandName("multiflux")
- .build(), 1)
- .expectNext("1")
- .thenAwait(Duration.ofSeconds(1))
- .thenRequest(1)
- .expectNext("2")
- .verifyComplete();
+ StepVerifier
+ .create(HystrixCommands.from(Flux.just("1", "2")).commandName("multiflux")
+ .build(), 1)
+ .expectNext("1").thenAwait(Duration.ofSeconds(1)).thenRequest(1)
+ .expectNext("2").verifyComplete();
}
@Test
public void toObservableFunctionWorks() {
- StepVerifier.create(HystrixCommands.from(Flux.just("1", "2"))
- .commandName("multiflux")
- .toObservable(cmd -> cmd.toObservable())
- .build(), 1)
- .expectNext("1")
- .thenAwait(Duration.ofSeconds(1))
- .thenRequest(1)
+ StepVerifier
+ .create(HystrixCommands.from(Flux.just("1", "2")).commandName("multiflux")
+ .toObservable(cmd -> cmd.toObservable()).build(), 1)
+ .expectNext("1").thenAwait(Duration.ofSeconds(1)).thenRequest(1)
.verifyError();
}
@Test
public void eagerFluxWorks() {
- StepVerifier.create(HystrixCommands.from( Flux.just("1", "2"))
- .commandName("multiflux")
- .eager()
- .toFlux())
- .expectNext("1")
- .expectNext("2")
- .verifyComplete();
+ StepVerifier
+ .create(HystrixCommands.from(Flux.just("1", "2")).commandName("multiflux")
+ .eager().toFlux())
+ .expectNext("1").expectNext("2").verifyComplete();
}
@Test
public void fluxTimesOut() {
- StepVerifier.create(HystrixCommands.from( Flux.from(s -> {
+ StepVerifier.create(HystrixCommands.from(Flux.from(s -> {
try {
Thread.sleep(1500);
- } catch (InterruptedException e) {
+ }
+ catch (InterruptedException e) {
throw new RuntimeException(e);
}
- })).commandName("failcmd").toFlux())
- .verifyError(HystrixRuntimeException.class);
+ })).commandName("failcmd").toFlux()).verifyError(HystrixRuntimeException.class);
}
@Test
public void fluxFallbackWorks() {
- StepVerifier.create(HystrixCommands.from(Flux.error(new Exception()))
- .commandName("multiflux")
- .fallback(Flux.just("a", "b"))
- .toFlux())
- .expectNext("a")
- .expectNext("b")
- .verifyComplete();
+ StepVerifier
+ .create(HystrixCommands.from(Flux.error(new Exception()))
+ .commandName("multiflux").fallback(Flux.just("a", "b")).toFlux())
+ .expectNext("a").expectNext("b").verifyComplete();
}
@Test
@@ -157,9 +130,7 @@ public class HystrixCommandsTests {
})).commandName("extendTimeout")
.commandProperties(
setter -> setter.withExecutionTimeoutInMilliseconds(2000))
- .toMono())
- .expectNext("works")
- .verifyComplete();
+ .toMono()).expectNext("works").verifyComplete();
}
}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixConfigurationTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixConfigurationTests.java
index dcdab7b01..b2e5b4a31 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixConfigurationTests.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixConfigurationTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,23 +37,24 @@ public class HystrixConfigurationTests {
@Test
public void nonWebAppStartsUp() {
new ApplicationContextRunner()
- .withUserConfiguration(HystrixCircuitBreakerConfiguration.class)
- .run(c -> {
- assertThat(c).hasSingleBean(HystrixCommandAspect.class);
- });
+ .withUserConfiguration(HystrixCircuitBreakerConfiguration.class)
+ .run(c -> {
+ assertThat(c).hasSingleBean(HystrixCommandAspect.class);
+ });
}
@Test
public void hystrixMetricsConfigured() {
- new WebApplicationContextRunner()
- .withUserConfiguration(TestApp.class)
- .run(c -> {
- assertThat(c.getBeansOfType(MeterBinder.class).values())
- .hasAtLeastOneElementOfType(HystrixMetricsBinder.class);
- });
+ new WebApplicationContextRunner().withUserConfiguration(TestApp.class).run(c -> {
+ assertThat(c.getBeansOfType(MeterBinder.class).values())
+ .hasAtLeastOneElementOfType(HystrixMetricsBinder.class);
+ });
}
@SpringBootConfiguration
@EnableAutoConfiguration
- protected static class TestApp {}
-}
\ No newline at end of file
+ protected static class TestApp {
+
+ }
+
+}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixOnlyTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixOnlyTests.java
index 9f1b59915..3bacb4bed 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixOnlyTests.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixOnlyTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.hystrix;
@@ -22,7 +21,6 @@ import java.util.List;
import java.util.Map;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
-import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -49,9 +47,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.cloud.netflix.test.TestAutoConfiguration.PASSWORD;
import static org.springframework.cloud.netflix.test.TestAutoConfiguration.USER;
@@ -60,11 +55,12 @@ import static org.springframework.cloud.netflix.test.TestAutoConfiguration.USER;
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
-@SpringBootTest(classes = HystrixOnlyApplication.class, webEnvironment = RANDOM_PORT,
- properties = {"management.endpoint.health.show-details=ALWAYS"})
+@SpringBootTest(classes = HystrixOnlyApplication.class, webEnvironment = RANDOM_PORT, properties = {
+ "management.endpoint.health.show-details=ALWAYS" })
@DirtiesContext
@ActiveProfiles("proxysecurity")
public class HystrixOnlyTests {
+
private static final String BASE_PATH = new WebEndpointProperties().getBasePath();
@LocalServerPort
@@ -74,14 +70,15 @@ public class HystrixOnlyTests {
public void testNormalExecution() {
ResponseEntity res = new TestRestTemplate()
.getForEntity("http://localhost:" + this.port + "/", String.class);
- assertEquals("incorrect response", "Hello world", res.getBody());
+ assertThat(res.getBody()).as("incorrect response").isEqualTo("Hello world");
}
@Test
public void testFailureFallback() {
ResponseEntity res = new TestRestTemplate()
.getForEntity("http://localhost:" + this.port + "/fail", String.class);
- assertEquals("incorrect fallback", "Fallback Hello world", res.getBody());
+ assertThat(res.getBody()).as("incorrect fallback")
+ .isEqualTo("Fallback Hello world");
}
@Test
@@ -99,8 +96,8 @@ public class HystrixOnlyTests {
public void testNoDiscoveryHealth() {
Map, ?> map = getHealth();
// There is explicitly no discovery, so there should be no discovery health key
- assertFalse("Incorrect existing discovery health key",
- map.containsKey("discovery"));
+ assertThat(map.containsKey("discovery"))
+ .as("Incorrect existing discovery health key").isFalse();
}
@Test
@@ -109,22 +106,24 @@ public class HystrixOnlyTests {
String url = "http://localhost:" + this.port;
ResponseEntity response = new TestRestTemplate().getForEntity(url,
String.class);
- assertEquals("bad response code", HttpStatus.OK, response.getStatusCode());
+ assertThat(response.getStatusCode()).as("bad response code")
+ .isEqualTo(HttpStatus.OK);
// Poller takes some time to realize for new metrics
try {
Thread.sleep(2000);
- } catch (InterruptedException e) {}
+ }
+ catch (InterruptedException e) {
+ }
Map> map = (Map>) getMetrics();
- assertTrue("There is no latencyTotal group key specified",
- map.get("names").contains("hystrix.latency.total"));
- assertTrue("There is no latencyExecute group key specified",
- map.get("names").contains("hystrix.latency.execution"));
+ assertThat(map.get("names").contains("hystrix.latency.total"))
+ .as("There is no latencyTotal group key specified").isTrue();
+ assertThat(map.get("names").contains("hystrix.latency.execution"))
+ .as("There is no latencyExecute group key specified").isTrue();
}
-
private Map, ?> getMetrics() {
return getAuthenticatedEndpoint("/metrics");
}
@@ -136,12 +135,12 @@ public class HystrixOnlyTests {
private Map, ?> getAuthenticatedEndpoint(String endpoint) {
return new TestRestTemplate().exchange(
"http://localhost:" + this.port + BASE_PATH + endpoint, HttpMethod.GET,
- new HttpEntity(createBasicAuthHeader(USER, PASSWORD)),
- Map.class).getBody();
+ new HttpEntity(createBasicAuthHeader(USER, PASSWORD)), Map.class)
+ .getBody();
}
public static HttpHeaders createBasicAuthHeader(final String username,
- final String password) {
+ final String password) {
return new HttpHeaders() {
private static final long serialVersionUID = 1766341693637204893L;
@@ -153,9 +152,11 @@ public class HystrixOnlyTests {
}
};
}
+
}
class Service {
+
@HystrixCommand
public String hello() {
return "Hello world";
@@ -169,6 +170,7 @@ class Service {
public String fallback() {
return "Fallback Hello world";
}
+
}
// Don't use @SpringBootApplication because we don't want to component scan
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpointTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpointTests.java
index f3d567ca2..1c425f997 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpointTests.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixStreamEndpointTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.hystrix;
@@ -22,10 +21,12 @@ import java.net.URL;
import java.util.ArrayList;
import java.util.List;
+import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
+
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -45,22 +46,21 @@ import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
-import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.fail;
/**
* @author Dave Syer
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
-@SpringBootTest(classes = HystrixStreamEndpointTests.Application.class,
- webEnvironment = WebEnvironment.RANDOM_PORT, value = {
+@SpringBootTest(classes = HystrixStreamEndpointTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = {
"spring.application.name=hystrixstreamtest" })
@DirtiesContext
public class HystrixStreamEndpointTests {
+
private static final String BASE_PATH = new WebEndpointProperties().getBasePath();
+
private static final Log log = LogFactory.getLog(HystrixStreamEndpointTests.class);
@LocalServerPort
@@ -72,7 +72,8 @@ public class HystrixStreamEndpointTests {
// you have to hit a Hystrix circuit breaker before the stream sends anything
ResponseEntity response = new TestRestTemplate().getForEntity(url,
String.class);
- assertEquals("bad response code", HttpStatus.OK, response.getStatusCode());
+ assertThat(response.getStatusCode()).as("bad response code")
+ .isEqualTo(HttpStatus.OK);
URL hystrixUrl = new URL(url + BASE_PATH + "/hystrix.stream");
@@ -82,7 +83,8 @@ public class HystrixStreamEndpointTests {
byte[] buffer = new byte[1024];
in.read(buffer);
data.add(new String(buffer));
- } catch (Exception e) {
+ }
+ catch (Exception e) {
log.error("Error getting hystrix stream, try " + i, e);
}
}
@@ -101,6 +103,7 @@ public class HystrixStreamEndpointTests {
@EnableCircuitBreaker
@Import(NoSecurityConfiguration.class)
protected static class Application {
+
@Autowired
Service service;
@@ -113,12 +116,16 @@ public class HystrixStreamEndpointTests {
public String hello() {
return service.hello();
}
+
}
protected static class Service {
+
@HystrixCommand
public String hello() {
return "Hello World";
}
+
}
+
}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpointTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpointTests.java
index 95f5514f4..ffea005e5 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpointTests.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/HystrixWebfluxEndpointTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.hystrix;
@@ -49,12 +48,14 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
-@SpringBootTest( webEnvironment = RANDOM_PORT, properties = {
+@SpringBootTest(webEnvironment = RANDOM_PORT, properties = {
"spring.main.web-application-type=reactive",
- "spring.application.name=hystrixstreamwebfluxtest", /*"debug=true"*/ })
+ "spring.application.name=hystrixstreamwebfluxtest" /* "debug=true" */ })
@DirtiesContext
public class HystrixWebfluxEndpointTests {
+
private static final String BASE_PATH = new WebEndpointProperties().getBasePath();
+
private static final Log log = LogFactory.getLog(HystrixWebfluxEndpointTests.class);
@LocalServerPort
@@ -70,31 +71,29 @@ public class HystrixWebfluxEndpointTests {
WebClient client = WebClient.create(url);
Flux result = client.get().uri(BASE_PATH + "/hystrix.stream")
- .accept(MediaType.TEXT_EVENT_STREAM)
- .exchange()
- .flatMapMany(res -> res.bodyToFlux(Map.class))
- .take(5)
+ .accept(MediaType.TEXT_EVENT_STREAM).exchange()
+ .flatMapMany(res -> res.bodyToFlux(Map.class)).take(5)
.filter(map -> "HystrixCommand".equals(map.get("type")))
- .map(map -> (String)map.get("type"));
+ .map(map -> (String) map.get("type"));
- StepVerifier.create(result)
- .expectNext("HystrixCommand")
- .thenCancel()
- .verify();
+ StepVerifier.create(result).expectNext("HystrixCommand").thenCancel().verify();
}
@RestController
@EnableCircuitBreaker
- @EnableAutoConfiguration(exclude = TestAutoConfiguration.class,
- excludeName = {"org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration",
+ @EnableAutoConfiguration(exclude = TestAutoConfiguration.class, excludeName = {
+ "org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration",
"org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration",
- "org.springframework.boot.actuate.autoconfigure.security.reactive.ReactiveManagementWebSecurityAutoConfiguration"})
+ "org.springframework.boot.actuate.autoconfigure.security.reactive.ReactiveManagementWebSecurityAutoConfiguration" })
@SpringBootConfiguration
protected static class Config {
+
@HystrixCommand
@RequestMapping("/")
public String hi() {
return "hi";
}
+
}
+
}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfigurationTest.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfigurationTest.java
index 70a78e70d..f4d42c89f 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfigurationTest.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityAutoConfigurationTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,11 +12,12 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.hystrix.security;
+import java.lang.reflect.Field;
+
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
@@ -27,84 +28,98 @@ import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldSetter;
-import java.lang.reflect.Field;
-
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
/**
* @author : ailin.zhou
*/
public class HystrixSecurityAutoConfigurationTest {
- @Test
- public void testInit() throws NoSuchFieldException, IllegalAccessException {
+ @Test
+ public void testInit() throws NoSuchFieldException, IllegalAccessException {
- //save test context
- HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance()
- .getEventNotifier();
- HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance()
- .getMetricsPublisher();
- HystrixPropertiesStrategy propertiesStrategy = HystrixPlugins.getInstance()
- .getPropertiesStrategy();
- HystrixCommandExecutionHook commandExecutionHook = HystrixPlugins.getInstance()
- .getCommandExecutionHook();
- HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy();
+ // save test context
+ HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance()
+ .getEventNotifier();
+ HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance()
+ .getMetricsPublisher();
+ HystrixPropertiesStrategy propertiesStrategy = HystrixPlugins.getInstance()
+ .getPropertiesStrategy();
+ HystrixCommandExecutionHook commandExecutionHook = HystrixPlugins.getInstance()
+ .getCommandExecutionHook();
+ HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance()
+ .getConcurrencyStrategy();
- //test
- testForMultiConcurrentStrategy();
+ // test
+ testForMultiConcurrentStrategy();
- //recover test context
- HystrixPlugins.reset();
- HystrixPlugins.getInstance().registerConcurrencyStrategy(concurrencyStrategy);
- HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
- HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher);
- HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
- HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);
+ // recover test context
+ HystrixPlugins.reset();
+ HystrixPlugins.getInstance().registerConcurrencyStrategy(concurrencyStrategy);
+ HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
+ HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher);
+ HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
+ HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);
+ }
- }
+ private void testForMultiConcurrentStrategy()
+ throws IllegalAccessException, NoSuchFieldException {
+ HystrixSecurityAutoConfiguration securityStrategy = new HystrixSecurityAutoConfiguration();
- private void testForMultiConcurrentStrategy() throws IllegalAccessException, NoSuchFieldException {
- HystrixSecurityAutoConfiguration securityStrategy = new HystrixSecurityAutoConfiguration();
+ // 1.existingConcurrencyStrategy is null, registeredStrategy is default
+ HystrixPlugins.reset();
+ securityStrategy.init();
+ // result is default
+ assertThat(getOriginalInSecurityConcurrencyStrategy())
+ .isEqualTo(HystrixConcurrencyStrategyDefault.getInstance());
- //1.existingConcurrencyStrategy is null, registeredStrategy is default
- HystrixPlugins.reset();
- securityStrategy.init();
- //result is default
- assertEquals(HystrixConcurrencyStrategyDefault.getInstance(), getOriginalInSecurityConcurrencyStrategy());
+ // 2.existingConcurrencyStrategy is null, registered strategy is customized
+ HystrixPlugins.reset();
+ HystrixConcurrencyStrategy customized = new HystrixConcurrencyStrategy() {
+ };
+ HystrixPlugins.getInstance().registerConcurrencyStrategy(customized);
+ securityStrategy.init();
+ // result is customized
+ assertThat(getOriginalInSecurityConcurrencyStrategy()).isEqualTo(customized);
- //2.existingConcurrencyStrategy is null, registered strategy is customized
- HystrixPlugins.reset();
- HystrixConcurrencyStrategy customized = new HystrixConcurrencyStrategy() {
- };
- HystrixPlugins.getInstance().registerConcurrencyStrategy(customized);
- securityStrategy.init();
- //result is customized
- assertEquals(customized, getOriginalInSecurityConcurrencyStrategy());
+ // 3.existingConcurrencyStrategy is not null, registeredStrategy is default.
+ HystrixPlugins.reset();
+ HystrixConcurrencyStrategy existingConcurrencyStrategy = new HystrixConcurrencyStrategy() {
+ };
+ FieldSetter
+ .setField(securityStrategy,
+ securityStrategy.getClass()
+ .getDeclaredField("existingConcurrencyStrategy"),
+ existingConcurrencyStrategy);
+ securityStrategy.init();
+ // result is existingConcurrencyStrategy
+ assertThat(getOriginalInSecurityConcurrencyStrategy())
+ .isEqualTo(existingConcurrencyStrategy);
- //3.existingConcurrencyStrategy is not null, registeredStrategy is default.
- HystrixPlugins.reset();
- HystrixConcurrencyStrategy existingConcurrencyStrategy = new HystrixConcurrencyStrategy() {
- };
- FieldSetter.setField(securityStrategy, securityStrategy.getClass().getDeclaredField("existingConcurrencyStrategy"), existingConcurrencyStrategy);
- securityStrategy.init();
- //result is existingConcurrencyStrategy
- assertEquals(existingConcurrencyStrategy, getOriginalInSecurityConcurrencyStrategy());
+ // 4.existingConcurrencyStrategy is not null, registeredStrategy is customized.
+ HystrixPlugins.reset();
+ HystrixPlugins.getInstance().registerConcurrencyStrategy(customized);
+ FieldSetter
+ .setField(securityStrategy,
+ securityStrategy.getClass()
+ .getDeclaredField("existingConcurrencyStrategy"),
+ existingConcurrencyStrategy);
+ securityStrategy.init();
+ assertThat(getOriginalInSecurityConcurrencyStrategy())
+ .isEqualTo(existingConcurrencyStrategy);
+ }
- //4.existingConcurrencyStrategy is not null, registeredStrategy is customized.
- HystrixPlugins.reset();
- HystrixPlugins.getInstance().registerConcurrencyStrategy(customized);
- FieldSetter.setField(securityStrategy, securityStrategy.getClass().getDeclaredField("existingConcurrencyStrategy"), existingConcurrencyStrategy);
- securityStrategy.init();
- assertEquals(existingConcurrencyStrategy, getOriginalInSecurityConcurrencyStrategy());
- }
+ private HystrixConcurrencyStrategy getOriginalInSecurityConcurrencyStrategy()
+ throws IllegalAccessException, NoSuchFieldException {
+ HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance()
+ .getConcurrencyStrategy();
+ Field existingConcurrencyStrategy = concurrencyStrategy.getClass()
+ .getDeclaredField("existingConcurrencyStrategy");
+ existingConcurrencyStrategy.setAccessible(true);
+ HystrixConcurrencyStrategy strategyInSecurityStrategy = (HystrixConcurrencyStrategy) existingConcurrencyStrategy
+ .get(concurrencyStrategy);
+ return strategyInSecurityStrategy;
+ }
- private HystrixConcurrencyStrategy getOriginalInSecurityConcurrencyStrategy() throws IllegalAccessException, NoSuchFieldException {
- HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy();
- Field existingConcurrencyStrategy = concurrencyStrategy.getClass().getDeclaredField("existingConcurrencyStrategy");
- existingConcurrencyStrategy.setAccessible(true);
- HystrixConcurrencyStrategy strategyInSecurityStrategy = (HystrixConcurrencyStrategy) existingConcurrencyStrategy.get(concurrencyStrategy);
- return strategyInSecurityStrategy;
- }
-
-}
\ No newline at end of file
+}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityNoFeignTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityNoFeignTests.java
index e9a36fd36..621d4881d 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityNoFeignTests.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/HystrixSecurityNoFeignTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2017 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,20 +12,19 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.hystrix.security;
+import com.netflix.hystrix.strategy.HystrixPlugins;
+import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import org.junit.Test;
import org.junit.runner.RunWith;
+
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
-import com.netflix.hystrix.strategy.HystrixPlugins;
-import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
-
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@@ -35,8 +34,10 @@ public class HystrixSecurityNoFeignTests {
@Test
public void testSecurityConcurrencyStrategyInstalled() {
- HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy();
- assertThat(concurrencyStrategy).isInstanceOf(SecurityContextConcurrencyStrategy.class);
+ HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance()
+ .getConcurrencyStrategy();
+ assertThat(concurrencyStrategy)
+ .isInstanceOf(SecurityContextConcurrencyStrategy.class);
}
}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/CustomConcurrenyStrategy.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/CustomConcurrenyStrategy.java
index 674adf671..535101535 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/CustomConcurrenyStrategy.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/CustomConcurrenyStrategy.java
@@ -1,13 +1,30 @@
+/*
+ * Copyright 2016-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.springframework.cloud.netflix.hystrix.security.app;
import java.util.concurrent.Callable;
-import org.springframework.stereotype.Component;
-
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
+import org.springframework.stereotype.Component;
+
@Component
public class CustomConcurrenyStrategy extends HystrixConcurrencyStrategy {
+
private boolean hookCalled;
@Override
@@ -20,4 +37,5 @@ public class CustomConcurrenyStrategy extends HystrixConcurrencyStrategy {
public boolean isHookCalled() {
return hookCalled;
}
+
}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameController.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameController.java
index 54605b8e4..5e516326d 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameController.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/hystrix/security/app/UsernameController.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2016 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,8 +26,10 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/username")
public class UsernameController {
+
@RequestMapping
- public String getUsername(@RequestHeader String username){
+ public String getUsername(@RequestHeader String username) {
return username;
}
+
}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/resttemplate/RestTemplateRetryTests.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/resttemplate/RestTemplateRetryTests.java
index 84ea0d0bc..065ecff68 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/resttemplate/RestTemplateRetryTests.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/resttemplate/RestTemplateRetryTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.resttemplate;
@@ -21,11 +20,25 @@ import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
+import com.netflix.client.RetryHandler;
+import com.netflix.client.config.IClientConfig;
+import com.netflix.loadbalancer.AvailabilityFilteringRule;
+import com.netflix.loadbalancer.BaseLoadBalancer;
+import com.netflix.loadbalancer.ILoadBalancer;
+import com.netflix.loadbalancer.IPing;
+import com.netflix.loadbalancer.IRule;
+import com.netflix.loadbalancer.LoadBalancerBuilder;
+import com.netflix.loadbalancer.LoadBalancerStats;
+import com.netflix.loadbalancer.Server;
+import com.netflix.loadbalancer.ServerList;
+import com.netflix.loadbalancer.ServerStats;
+import com.netflix.niws.client.http.HttpClientLoadBalancerErrorHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -44,30 +57,15 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
-import com.netflix.client.RetryHandler;
-import com.netflix.client.config.IClientConfig;
-import com.netflix.loadbalancer.AvailabilityFilteringRule;
-import com.netflix.loadbalancer.BaseLoadBalancer;
-import com.netflix.loadbalancer.ILoadBalancer;
-import com.netflix.loadbalancer.IPing;
-import com.netflix.loadbalancer.IRule;
-import com.netflix.loadbalancer.LoadBalancerBuilder;
-import com.netflix.loadbalancer.LoadBalancerStats;
-import com.netflix.loadbalancer.Server;
-import com.netflix.loadbalancer.ServerList;
-import com.netflix.loadbalancer.ServerStats;
-import com.netflix.niws.client.http.HttpClientLoadBalancerErrorHandler;
-
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
-@SpringBootTest(classes = RestTemplateRetryTests.Application.class, webEnvironment = RANDOM_PORT,
- properties = { "spring.application.name=resttemplatetest", "logging.level.com.netflix=DEBUG",
- "logging.level.org.springframework.cloud.netflix.resttemplate=DEBUG",
- "logging.level.com.netflix=DEBUG", "badClients.ribbon.MaxAutoRetries=25",
- "badClients.ribbon.OkToRetryOnAllOperations=true", "ribbon.http.client.enabled" })
+@SpringBootTest(classes = RestTemplateRetryTests.Application.class, webEnvironment = RANDOM_PORT, properties = {
+ "spring.application.name=resttemplatetest", "logging.level.com.netflix=DEBUG",
+ "logging.level.org.springframework.cloud.netflix.resttemplate=DEBUG",
+ "logging.level.com.netflix=DEBUG", "badClients.ribbon.MaxAutoRetries=25",
+ "badClients.ribbon.OkToRetryOnAllOperations=true", "ribbon.http.client.enabled" })
@DirtiesContext
public class RestTemplateRetryTests {
@@ -111,9 +109,10 @@ public class RestTemplateRetryTests {
logServerStats(LocalBadClientConfiguration.badServer2);
logServerStats(LocalBadClientConfiguration.goodServer);
- assertTrue(badServer1Stats.isCircuitBreakerTripped());
- assertTrue(badServer2Stats.isCircuitBreakerTripped());
- assertThat(targetConnectionCount).isLessThanOrEqualTo(goodServerStats.getTotalRequestsCount());
+ assertThat(badServer1Stats.isCircuitBreakerTripped()).isTrue();
+ assertThat(badServer2Stats.isCircuitBreakerTripped()).isTrue();
+ assertThat(targetConnectionCount)
+ .isLessThanOrEqualTo(goodServerStats.getTotalRequestsCount());
// Wait for any timeout thread to finish.
@@ -157,9 +156,10 @@ public class RestTemplateRetryTests {
logServerStats(LocalBadClientConfiguration.badServer2);
logServerStats(LocalBadClientConfiguration.goodServer);
- assertTrue(badServer1Stats.isCircuitBreakerTripped());
- assertTrue(badServer2Stats.isCircuitBreakerTripped());
- assertThat(targetConnectionCount).isLessThanOrEqualTo(goodServerStats.getTotalRequestsCount());
+ assertThat(badServer1Stats.isCircuitBreakerTripped()).isTrue();
+ assertThat(badServer2Stats.isCircuitBreakerTripped()).isTrue();
+ assertThat(targetConnectionCount)
+ .isLessThanOrEqualTo(goodServerStats.getTotalRequestsCount());
assertThat(hits).isGreaterThanOrEqualTo(numCalls);
logger.debug("Retry Hits: " + hits);
}
@@ -178,8 +178,8 @@ public class RestTemplateRetryTests {
badServer1Stats.clearSuccessiveConnectionFailureCount();
badServer2Stats.clearSuccessiveConnectionFailureCount();
- assertTrue(!badServer1Stats.isCircuitBreakerTripped());
- assertTrue(!badServer2Stats.isCircuitBreakerTripped());
+ assertThat(!badServer1Stats.isCircuitBreakerTripped()).isTrue();
+ assertThat(!badServer2Stats.isCircuitBreakerTripped()).isTrue();
int hits = 0;
@@ -192,9 +192,9 @@ public class RestTemplateRetryTests {
logServerStats(LocalBadClientConfiguration.badServer2);
logServerStats(LocalBadClientConfiguration.goodServer);
- assertTrue(badServer1Stats.isCircuitBreakerTripped());
- assertTrue(badServer2Stats.isCircuitBreakerTripped());
- assertTrue(!goodServerStats.isCircuitBreakerTripped());
+ assertThat(badServer1Stats.isCircuitBreakerTripped()).isTrue();
+ assertThat(badServer2Stats.isCircuitBreakerTripped()).isTrue();
+ assertThat(!goodServerStats.isCircuitBreakerTripped()).isTrue();
// 15 + 4 timeouts. See the endpoint for timeout conditions.
assertThat(hits).isGreaterThanOrEqualTo(numCalls + 4);
@@ -212,6 +212,7 @@ public class RestTemplateRetryTests {
public static class Application {
private AtomicInteger hits = new AtomicInteger(1);
+
private AtomicInteger retryHits = new AtomicInteger(1);
@RequestMapping(method = RequestMethod.GET, value = "/ping")
@@ -246,8 +247,8 @@ public class RestTemplateRetryTests {
RestTemplate restTemplate() {
return new RestTemplate();
}
- }
+ }
// Load balancer with fixed server list for "local" pointing to localhost
// and some bogus servers are thrown in to test retry
@@ -259,7 +260,7 @@ public class RestTemplateRetryTests {
static Server badServer;
static Server badServer2;
- public LocalBadClientConfiguration() {
+ LocalBadClientConfiguration() {
}
@Value("${local.server.port}")
@@ -267,7 +268,8 @@ public class RestTemplateRetryTests {
@Bean
public IRule loadBalancerRule() {
- // This is a good place to try different load balancing rules and how those rules
+ // This is a good place to try different load balancing rules and how those
+ // rules
// behave in failure states: BestAvailableRule, WeightedResponseTimeRule, etc
// This rule just uses a round robin and will skip servers that are in circuit
@@ -296,11 +298,14 @@ public class RestTemplateRetryTests {
}
static class OverrideRetryHandler extends HttpClientLoadBalancerErrorHandler {
- public OverrideRetryHandler() {
+
+ OverrideRetryHandler() {
this.circuitRelated.add(UnknownHostException.class);
this.retriable.add(UnknownHostException.class);
}
+
}
}
+
}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeExceptionTest.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeExceptionTest.java
index ac00fc64a..6ecde8ceb 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeExceptionTest.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeExceptionTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,11 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.springframework.cloud.netflix.ribbon.apache;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.util.Locale;
+
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.ProtocolVersion;
@@ -31,8 +33,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -49,7 +50,7 @@ public class HttpClientStatusCodeExceptionTest {
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
doReturn(new Locale("en")).when(response).getLocale();
Header foo = new BasicHeader("foo", "bar");
- Header[] headers = new Header[]{foo};
+ Header[] headers = new Header[] { foo };
doReturn(headers).when(response).getAllHeaders();
StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1),
200, "Success");
@@ -59,16 +60,21 @@ public class HttpClientStatusCodeExceptionTest {
entity.setContentLength(3);
doReturn(entity).when(response).getEntity();
HttpEntity copiedEntity = HttpClientUtils.createEntity(response);
- HttpClientStatusCodeException ex = new HttpClientStatusCodeException("service", response, copiedEntity,
- new URI("http://service.com"));
- assertEquals("en", ex.getResponse().getLocale().toString());
- assertArrayEquals(headers, ex.getResponse().getAllHeaders());
- assertEquals("Success", ex.getResponse().getStatusLine().getReasonPhrase());
- assertEquals(200, ex.getResponse().getStatusLine().getStatusCode());
- assertEquals("http", ex.getResponse().getStatusLine().getProtocolVersion().getProtocol());
- assertEquals(1, ex.getResponse().getStatusLine().getProtocolVersion().getMajor());
- assertEquals(1, ex.getResponse().getStatusLine().getProtocolVersion().getMinor());
- assertEquals("foo", EntityUtils.toString(ex.getResponse().getEntity()));
+ HttpClientStatusCodeException ex = new HttpClientStatusCodeException("service",
+ response, copiedEntity, new URI("http://service.com"));
+ assertThat(ex.getResponse().getLocale().toString()).isEqualTo("en");
+ assertThat(ex.getResponse().getAllHeaders()).isEqualTo(headers);
+ assertThat(ex.getResponse().getStatusLine().getReasonPhrase())
+ .isEqualTo("Success");
+ assertThat(ex.getResponse().getStatusLine().getStatusCode()).isEqualTo(200);
+ assertThat(ex.getResponse().getStatusLine().getProtocolVersion().getProtocol())
+ .isEqualTo("http");
+ assertThat(ex.getResponse().getStatusLine().getProtocolVersion().getMajor())
+ .isEqualTo(1);
+ assertThat(ex.getResponse().getStatusLine().getProtocolVersion().getMinor())
+ .isEqualTo(1);
+ assertThat(EntityUtils.toString(ex.getResponse().getEntity())).isEqualTo("foo");
verify(response, times(1)).close();
}
-}
\ No newline at end of file
+
+}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeExceptionTest.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeExceptionTest.java
index af8320a5c..71cf55e77 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeExceptionTest.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeExceptionTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,22 +13,22 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.springframework.cloud.netflix.ribbon.okhttp;
+import java.net.URI;
+
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
-
-import java.net.URI;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
-import static org.junit.Assert.assertEquals;
-
+import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Ryan Baxter
@@ -39,15 +39,19 @@ public class OkHttpStatusCodeExceptionTest {
@Test
public void getResponse() throws Exception {
Headers headers = new Headers.Builder().add("foo", "bar").build();
- Response response = new Response.Builder().code(200).headers(headers).code(200).message("Success")
- .body(ResponseBody.create(MediaType.parse("text/plain"), "foo")).protocol(Protocol.HTTP_1_1)
+ Response response = new Response.Builder().code(200).headers(headers).code(200)
+ .message("Success")
+ .body(ResponseBody.create(MediaType.parse("text/plain"), "foo"))
+ .protocol(Protocol.HTTP_1_1)
.request(new Request.Builder().url("http://service.com").build()).build();
ResponseBody body = response.peekBody(Integer.MAX_VALUE);
- OkHttpStatusCodeException ex = new OkHttpStatusCodeException("service", response, body, new URI("http://service.com"));
- assertEquals(headers, ex.getResponse().headers());
- assertEquals(200, ex.getResponse().code());
- assertEquals("Success", ex.getResponse().message());
- assertEquals("foo", ex.getResponse().body().string());
- assertEquals(Protocol.HTTP_1_1, ex.getResponse().protocol());
+ OkHttpStatusCodeException ex = new OkHttpStatusCodeException("service", response,
+ body, new URI("http://service.com"));
+ assertThat(ex.getResponse().headers()).isEqualTo(headers);
+ assertThat(ex.getResponse().code()).isEqualTo(200);
+ assertThat(ex.getResponse().message()).isEqualTo("Success");
+ assertThat(ex.getResponse().body().string()).isEqualTo("foo");
+ assertThat(ex.getResponse().protocol()).isEqualTo(Protocol.HTTP_1_1);
}
-}
\ No newline at end of file
+
+}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/NoSecurityConfiguration.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/NoSecurityConfiguration.java
index 44e71946e..f93e0563e 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/NoSecurityConfiguration.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/NoSecurityConfiguration.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.test;
@@ -23,11 +22,10 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
@Configuration
public class NoSecurityConfiguration extends WebSecurityConfigurerAdapter {
+
@Override
protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests()
- .anyRequest().permitAll()
- .and()
- .csrf().disable();
+ http.authorizeRequests().anyRequest().permitAll().and().csrf().disable();
}
+
}
diff --git a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/TestAutoConfiguration.java b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/TestAutoConfiguration.java
index 33b671e70..6be271a05 100644
--- a/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/TestAutoConfiguration.java
+++ b/spring-cloud-netflix-hystrix/src/test/java/org/springframework/cloud/netflix/test/TestAutoConfiguration.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,17 +34,18 @@ import org.springframework.security.provisioning.InMemoryUserDetailsManager;
* @author Spencer Gibb
*/
@Configuration
-@Import({NoopDiscoveryClientAutoConfiguration.class})
+@Import({ NoopDiscoveryClientAutoConfiguration.class })
@AutoConfigureBefore(SecurityAutoConfiguration.class)
public class TestAutoConfiguration {
public static final String USER = "user";
+
public static final String PASSWORD = "{noop}password";
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
- protected static class TestSecurityConfiguration extends WebSecurityConfigurerAdapter {
-
+ protected static class TestSecurityConfiguration
+ extends WebSecurityConfigurerAdapter {
TestSecurityConfiguration() {
super(true);
@@ -53,18 +54,18 @@ public class TestAutoConfiguration {
@Bean
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
- manager.createUser(User.withUsername(USER).password(PASSWORD).roles("USER").build());
+ manager.createUser(
+ User.withUsername(USER).password(PASSWORD).roles("USER").build());
return manager;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http);
- http.antMatcher("/proxy-username")
- .httpBasic()
- .and()
- .authorizeRequests().antMatchers("/**").permitAll();
+ http.antMatcher("/proxy-username").httpBasic().and().authorizeRequests()
+ .antMatchers("/**").permitAll();
}
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospector.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospector.java
index c1dfcb1dc..b2a185343 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospector.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/DefaultServerIntrospector.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,10 +19,10 @@ package org.springframework.cloud.netflix.ribbon;
import java.util.Collections;
import java.util.Map;
-import org.springframework.beans.factory.annotation.Autowired;
-
import com.netflix.loadbalancer.Server;
+import org.springframework.beans.factory.annotation.Autowired;
+
/**
* @author Spencer Gibb
*/
@@ -31,7 +31,8 @@ public class DefaultServerIntrospector implements ServerIntrospector {
private ServerIntrospectorProperties serverIntrospectorProperties = new ServerIntrospectorProperties();
@Autowired(required = false)
- public void setServerIntrospectorProperties(ServerIntrospectorProperties serverIntrospectorProperties){
+ public void setServerIntrospectorProperties(
+ ServerIntrospectorProperties serverIntrospectorProperties) {
this.serverIntrospectorProperties = serverIntrospectorProperties;
}
@@ -44,4 +45,5 @@ public class DefaultServerIntrospector implements ServerIntrospector {
public Map getMetadata(Server server) {
return Collections.emptyMap();
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/PropertiesFactory.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/PropertiesFactory.java
index 3e26ee31f..09072b7ec 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/PropertiesFactory.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/PropertiesFactory.java
@@ -1,10 +1,24 @@
+/*
+ * Copyright 2016-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.springframework.cloud.netflix.ribbon;
import java.util.HashMap;
import java.util.Map;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.env.Environment;
-import org.springframework.util.StringUtils;
+
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IPing;
@@ -12,12 +26,17 @@ import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.ServerList;
import com.netflix.loadbalancer.ServerListFilter;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.env.Environment;
+import org.springframework.util.StringUtils;
+
import static org.springframework.cloud.netflix.ribbon.SpringClientFactory.NAMESPACE;
/**
* @author Spencer Gibb
*/
public class PropertiesFactory {
+
@Autowired
private Environment environment;
@@ -38,7 +57,8 @@ public class PropertiesFactory {
public String getClassName(Class clazz, String name) {
if (this.classToProperty.containsKey(clazz)) {
String classNameProperty = this.classToProperty.get(clazz);
- String className = environment.getProperty(name + "." + NAMESPACE + "." + classNameProperty);
+ String className = environment
+ .getProperty(name + "." + NAMESPACE + "." + classNameProperty);
return className;
}
return null;
@@ -50,11 +70,15 @@ public class PropertiesFactory {
if (StringUtils.hasText(className)) {
try {
Class> toInstantiate = Class.forName(className);
- return (C) SpringClientFactory.instantiateWithConfig(toInstantiate, config);
- } catch (ClassNotFoundException e) {
- throw new IllegalArgumentException("Unknown class to load "+className+" for class " + clazz + " named " + name);
+ return (C) SpringClientFactory.instantiateWithConfig(toInstantiate,
+ config);
+ }
+ catch (ClassNotFoundException e) {
+ throw new IllegalArgumentException("Unknown class to load " + className
+ + " for class " + clazz + " named " + name);
}
}
return null;
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RestClientRibbonConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RestClientRibbonConfiguration.java
index 61076e51a..884e2347d 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RestClientRibbonConfiguration.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RestClientRibbonConfiguration.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2017 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,22 +12,20 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.ribbon;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Lazy;
-
import com.netflix.client.AbstractLoadBalancerAwareClient;
import com.netflix.client.RetryHandler;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.niws.client.http.RestClient;
-import com.netflix.servo.monitor.Monitors;
+
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Lazy;
/**
* @author Spencer Gibb
@@ -36,6 +34,7 @@ import com.netflix.servo.monitor.Monitors;
@Configuration
@RibbonAutoConfiguration.ConditionalOnRibbonRestClient
class RestClientRibbonConfiguration {
+
@RibbonClientName
private String name = "client";
@@ -43,21 +42,23 @@ class RestClientRibbonConfiguration {
* Create a Netflix {@link RestClient} integrated with Ribbon if none already exists
* in the application context. It is not required for Ribbon to work properly and is
* therefore created lazily if ever another component requires it.
- *
- * @param config the configuration to use by the underlying Ribbon instance
- * @param loadBalancer the load balancer to use by the underlying Ribbon instance
- * @param serverIntrospector server introspector to use by the underlying Ribbon instance
- * @param retryHandler retry handler to use by the underlying Ribbon instance
+ * @param config the configuration to use by the underlying Ribbon instance
+ * @param loadBalancer the load balancer to use by the underlying Ribbon instance
+ * @param serverIntrospector server introspector to use by the underlying Ribbon
+ * instance
+ * @param retryHandler retry handler to use by the underlying Ribbon instance
* @return a {@link RestClient} instances backed by Ribbon
*/
@Bean
@Lazy
@ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class)
public RestClient ribbonRestClient(IClientConfig config, ILoadBalancer loadBalancer,
- ServerIntrospector serverIntrospector, RetryHandler retryHandler) {
- RestClient client = new RibbonClientConfiguration.OverrideRestClient(config, serverIntrospector);
+ ServerIntrospector serverIntrospector, RetryHandler retryHandler) {
+ RestClient client = new RibbonClientConfiguration.OverrideRestClient(config,
+ serverIntrospector);
client.setLoadBalancer(loadBalancer);
client.setRetryHandler(retryHandler);
return client;
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializer.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializer.java
index 3051bb495..cf77fd4fb 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializer.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonApplicationContextInitializer.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2017 the original author or authors.
+ * Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,12 +17,13 @@
package org.springframework.cloud.netflix.ribbon;
import java.util.List;
+
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
/**
* Responsible for eagerly creating the child application context holding the Ribbon
- * related configuration
+ * related configuration.
*
* @author Biju Kunjummen
*/
@@ -30,8 +31,8 @@ public class RibbonApplicationContextInitializer
implements ApplicationListener {
private final SpringClientFactory springClientFactory;
-
- //List of Ribbon client names
+
+ // List of Ribbon client names
private final List clientNames;
public RibbonApplicationContextInitializer(SpringClientFactory springClientFactory,
@@ -52,4 +53,5 @@ public class RibbonApplicationContextInitializer
public void onApplicationEvent(ApplicationReadyEvent event) {
initialize();
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java
index 1e71032c0..94378cba0 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2017 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -60,8 +60,10 @@ import org.springframework.web.client.RestTemplate;
@Conditional(RibbonAutoConfiguration.RibbonClassesConditions.class)
@RibbonClients
@AutoConfigureAfter(name = "org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration")
-@AutoConfigureBefore({LoadBalancerAutoConfiguration.class, AsyncLoadBalancerAutoConfiguration.class})
-@EnableConfigurationProperties({RibbonEagerLoadProperties.class, ServerIntrospectorProperties.class})
+@AutoConfigureBefore({ LoadBalancerAutoConfiguration.class,
+ AsyncLoadBalancerAutoConfiguration.class })
+@EnableConfigurationProperties({ RibbonEagerLoadProperties.class,
+ ServerIntrospectorProperties.class })
public class RibbonAutoConfiguration {
@Autowired(required = false)
@@ -91,7 +93,8 @@ public class RibbonAutoConfiguration {
@Bean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
@ConditionalOnMissingBean
- public LoadBalancedRetryFactory loadBalancedRetryPolicyFactory(final SpringClientFactory clientFactory) {
+ public LoadBalancedRetryFactory loadBalancedRetryPolicyFactory(
+ final SpringClientFactory clientFactory) {
return new RibbonLoadBalancedRetryFactory(clientFactory);
}
@@ -102,7 +105,7 @@ public class RibbonAutoConfiguration {
}
@Bean
- @ConditionalOnProperty(value = "ribbon.eager-load.enabled")
+ @ConditionalOnProperty("ribbon.eager-load.enabled")
public RibbonApplicationContextInitializer ribbonApplicationContextInitializer() {
return new RibbonApplicationContextInitializer(springClientFactory(),
ribbonEagerLoadProperties.getClients());
@@ -119,38 +122,48 @@ public class RibbonAutoConfiguration {
@Bean
public RestTemplateCustomizer restTemplateCustomizer(
final RibbonClientHttpRequestFactory ribbonClientHttpRequestFactory) {
- return restTemplate -> restTemplate.setRequestFactory(ribbonClientHttpRequestFactory);
+ return restTemplate -> restTemplate
+ .setRequestFactory(ribbonClientHttpRequestFactory);
}
@Bean
public RibbonClientHttpRequestFactory ribbonClientHttpRequestFactory() {
return new RibbonClientHttpRequestFactory(this.springClientFactory);
}
+
}
- //TODO: support for autoconfiguring restemplate to use apache http client or okhttp
+ // TODO: support for autoconfiguring restemplate to use apache http client or okhttp
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnRibbonRestClientCondition.class)
- @interface ConditionalOnRibbonRestClient { }
+ @interface ConditionalOnRibbonRestClient {
+
+ }
private static class OnRibbonRestClientCondition extends AnyNestedCondition {
- public OnRibbonRestClientCondition() {
+
+ OnRibbonRestClientCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
- @Deprecated //remove in Edgware"
+ @Deprecated // remove in Edgware"
@ConditionalOnProperty("ribbon.http.client.enabled")
- static class ZuulProperty {}
+ static class ZuulProperty {
+
+ }
@ConditionalOnProperty("ribbon.restclient.enabled")
- static class RibbonProperty {}
+ static class RibbonProperty {
+
+ }
+
}
/**
- * {@link AllNestedConditions} that checks that either multiple classes are present
+ * {@link AllNestedConditions} that checks that either multiple classes are present.
*/
static class RibbonClassesConditions extends AllNestedConditions {
@@ -179,4 +192,5 @@ public class RibbonAutoConfiguration {
}
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClient.java
index 1b6e017b4..69ca1ecac 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClient.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClient.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2014 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,12 +21,14 @@ import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Import;
+
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.ServerListFilter;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+
/**
* Declarative configuration for a ribbon client. Add this annotation to any
* @Configuration and then inject a {@link SpringClientFactory} to access the
@@ -42,15 +44,17 @@ import com.netflix.loadbalancer.ServerListFilter;
public @interface RibbonClient {
/**
- * Synonym for name (the name of the client)
+ * Synonym for name (the name of the client).
*
* @see #name()
+ * @return name of the Ribbon client
*/
String value() default "";
/**
* The name of the ribbon client, uniquely identifying a set of client resources,
* including a load balancer.
+ * @return name of the Ribbon client
*/
String name() default "";
@@ -60,6 +64,7 @@ public @interface RibbonClient {
* {@link ILoadBalancer}, {@link ServerListFilter}, {@link IRule}.
*
* @see RibbonClientConfiguration for the defaults
+ * @return the custom Ribbon client configuration
*/
Class>[] configuration() default {};
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfiguration.java
index 9d1de9d8f..dc489e956 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfiguration.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfiguration.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2014 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,18 +17,9 @@
package org.springframework.cloud.netflix.ribbon;
import java.net.URI;
+
import javax.annotation.PostConstruct;
-import org.apache.http.client.params.ClientPNames;
-import org.apache.http.client.params.CookiePolicy;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.cloud.commons.httpclient.HttpClientConfiguration;
-import org.springframework.cloud.netflix.ribbon.apache.HttpClientRibbonConfiguration;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Import;
-import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpRibbonConfiguration;
+
import com.netflix.client.DefaultLoadBalancerRetryHandler;
import com.netflix.client.RetryHandler;
import com.netflix.client.config.CommonClientConfigKey;
@@ -49,6 +40,18 @@ import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import com.netflix.niws.client.http.RestClient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
+import org.apache.http.client.params.ClientPNames;
+import org.apache.http.client.params.CookiePolicy;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.cloud.commons.httpclient.HttpClientConfiguration;
+import org.springframework.cloud.netflix.ribbon.apache.HttpClientRibbonConfiguration;
+import org.springframework.cloud.netflix.ribbon.okhttp.OkHttpRibbonConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
import static com.netflix.client.config.CommonClientConfigKey.DeploymentContextBasedVipAddresses;
import static org.springframework.cloud.netflix.ribbon.RibbonUtils.setRibbonProperty;
@@ -61,13 +64,26 @@ import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecur
@SuppressWarnings("deprecation")
@Configuration
@EnableConfigurationProperties
-//Order is important here, last should be the default, first should be optional
-// see https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653
-@Import({HttpClientConfiguration.class, OkHttpRibbonConfiguration.class, RestClientRibbonConfiguration.class, HttpClientRibbonConfiguration.class})
+// Order is important here, last should be the default, first should be optional
+// see
+// https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653
+@Import({ HttpClientConfiguration.class, OkHttpRibbonConfiguration.class,
+ RestClientRibbonConfiguration.class, HttpClientRibbonConfiguration.class })
public class RibbonClientConfiguration {
+ /**
+ * Ribbon client default connect timeout.
+ */
public static final int DEFAULT_CONNECT_TIMEOUT = 1000;
+
+ /**
+ * Ribbon client default read timeout.
+ */
public static final int DEFAULT_READ_TIMEOUT = 1000;
+
+ /**
+ * Ribbon client default Gzip Payload flag.
+ */
public static final boolean DEFAULT_GZIP_PAYLOAD = true;
@RibbonClientName
@@ -155,7 +171,7 @@ public class RibbonClientConfiguration {
@Bean
@ConditionalOnMissingBean
public RibbonLoadBalancerContext ribbonLoadBalancerContext(ILoadBalancer loadBalancer,
- IClientConfig config, RetryHandler retryHandler) {
+ IClientConfig config, RetryHandler retryHandler) {
return new RibbonLoadBalancerContext(loadBalancer, config, retryHandler);
}
@@ -179,6 +195,7 @@ public class RibbonClientConfiguration {
static class OverrideRestClient extends RestClient {
private IClientConfig config;
+
private ServerIntrospector serverIntrospector;
protected OverrideRestClient(IClientConfig config,
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationRegistrar.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationRegistrar.java
index b72841caa..cc03ed8ac 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationRegistrar.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientConfigurationRegistrar.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2014 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package org.springframework.cloud.netflix.ribbon;
import java.util.Map;
+
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
@@ -32,8 +33,8 @@ public class RibbonClientConfigurationRegistrar implements ImportBeanDefinitionR
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
- Map attrs = metadata.getAnnotationAttributes(
- RibbonClients.class.getName(), true);
+ Map attrs = metadata
+ .getAnnotationAttributes(RibbonClients.class.getName(), true);
if (attrs != null && attrs.containsKey("value")) {
AnnotationAttributes[] clients = (AnnotationAttributes[]) attrs.get("value");
for (AnnotationAttributes client : clients) {
@@ -45,14 +46,15 @@ public class RibbonClientConfigurationRegistrar implements ImportBeanDefinitionR
String name;
if (metadata.hasEnclosingClass()) {
name = "default." + metadata.getEnclosingClassName();
- } else {
+ }
+ else {
name = "default." + metadata.getClassName();
}
registerClientConfiguration(registry, name,
attrs.get("defaultConfiguration"));
}
- Map client = metadata.getAnnotationAttributes(
- RibbonClient.class.getName(), true);
+ Map client = metadata
+ .getAnnotationAttributes(RibbonClient.class.getName(), true);
String name = getClientName(client);
if (name != null) {
registerClientConfiguration(registry, name, client.get("configuration"));
@@ -74,8 +76,8 @@ public class RibbonClientConfigurationRegistrar implements ImportBeanDefinitionR
"Either 'name' or 'value' must be provided in @RibbonClient");
}
- private void registerClientConfiguration(BeanDefinitionRegistry registry,
- Object name, Object configuration) {
+ private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name,
+ Object configuration) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder
.genericBeanDefinition(RibbonClientSpecification.class);
builder.addConstructorArgValue(name);
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactory.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactory.java
index 910206b4d..8abc3b265 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactory.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientHttpRequestFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,13 +18,15 @@ package org.springframework.cloud.netflix.ribbon;
import java.io.IOException;
import java.net.URI;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.client.ClientHttpRequest;
-import org.springframework.http.client.ClientHttpRequestFactory;
+
import com.netflix.client.config.IClientConfig;
import com.netflix.client.http.HttpRequest;
import com.netflix.niws.client.http.RestClient;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.client.ClientHttpRequest;
+import org.springframework.http.client.ClientHttpRequestFactory;
+
/**
* @author Spencer Gibb
*/
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientName.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientName.java
index 122edb624..0a441a349 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientName.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientName.java
@@ -1,6 +1,20 @@
-package org.springframework.cloud.netflix.ribbon;
+/*
+ * Copyright 2018-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
-import org.springframework.beans.factory.annotation.Value;
+package org.springframework.cloud.netflix.ribbon;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
@@ -8,16 +22,18 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
+import org.springframework.beans.factory.annotation.Value;
+
/**
- * Annotation at the field or method/constructor parameter level that injects the
- * Ribbon Client Name that got allocated at runtime. Provides a convenient
- * alternative for @Value("${ribbon.client.name}").
+ * Annotation at the field or method/constructor parameter level that injects the Ribbon
+ * Client Name that got allocated at runtime. Provides a convenient alternative for
+ * @Value("${ribbon.client.name}").
*
* @author Spencer Gibb
* @since 2.0.0
*/
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,
- ElementType.ANNOTATION_TYPE })
+ ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Value("${ribbon.client.name}")
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientSpecification.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientSpecification.java
index ad1827fe6..aaf7f6c94 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientSpecification.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClientSpecification.java
@@ -18,6 +18,7 @@ package org.springframework.cloud.netflix.ribbon;
import java.util.Arrays;
import java.util.Objects;
+
import org.springframework.cloud.context.named.NamedContextFactory;
/**
@@ -55,11 +56,15 @@ public class RibbonClientSpecification implements NamedContextFactory.Specificat
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
RibbonClientSpecification that = (RibbonClientSpecification) o;
- return Arrays.equals(configuration, that.configuration) &&
- Objects.equals(name, that.name);
+ return Arrays.equals(configuration, that.configuration)
+ && Objects.equals(name, that.name);
}
@Override
@@ -69,10 +74,9 @@ public class RibbonClientSpecification implements NamedContextFactory.Specificat
@Override
public String toString() {
- return new StringBuilder("RibbonClientSpecification{")
- .append("name='").append(name).append("', ")
- .append("configuration=").append(Arrays.toString(configuration))
- .append("}").toString();
+ return new StringBuilder("RibbonClientSpecification{").append("name='")
+ .append(name).append("', ").append("configuration=")
+ .append(Arrays.toString(configuration)).append("}").toString();
}
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClients.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClients.java
index 32e88cc22..cee741b6f 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClients.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonClients.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2014 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@ import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
+
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonEagerLoadProperties.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonEagerLoadProperties.java
index f27b6b48d..b648ff8f7 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonEagerLoadProperties.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonEagerLoadProperties.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2017 the original author or authors.
+ * Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,17 +17,20 @@
package org.springframework.cloud.netflix.ribbon;
import java.util.List;
+
import org.springframework.boot.context.properties.ConfigurationProperties;
-/*
- * Configuration Properties to indicate which Ribbon configurations
- * should be eagerly loaded up
- *
+/**
+ * Configuration Properties to indicate which Ribbon configurations should be eagerly
+ * loaded up.
+ *
* @author Biju Kunjummen
*/
@ConfigurationProperties(prefix = "ribbon.eager-load")
public class RibbonEagerLoadProperties {
+
private boolean enabled = false;
+
private List clients;
public boolean isEnabled() {
@@ -45,4 +48,5 @@ public class RibbonEagerLoadProperties {
public void setClients(List clients) {
this.clients = clients;
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpRequest.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpRequest.java
index 803f2cb76..0f612606e 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpRequest.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpRequest.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,15 +21,17 @@ import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.List;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.client.AbstractClientHttpRequest;
-import org.springframework.http.client.ClientHttpResponse;
+
import com.netflix.client.config.IClientConfig;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.niws.client.http.RestClient;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.client.AbstractClientHttpRequest;
+import org.springframework.http.client.ClientHttpResponse;
+
/**
* @author Spencer Gibb
*/
@@ -37,14 +39,19 @@ import com.netflix.niws.client.http.RestClient;
public class RibbonHttpRequest extends AbstractClientHttpRequest {
private HttpRequest.Builder builder;
+
private URI uri;
+
private HttpRequest.Verb verb;
+
private RestClient client;
+
private IClientConfig config;
+
private ByteArrayOutputStream outputStream = null;
public RibbonHttpRequest(URI uri, HttpRequest.Verb verb, RestClient client,
- IClientConfig config) {
+ IClientConfig config) {
this.uri = uri;
this.verb = verb;
this.client = client;
@@ -76,8 +83,7 @@ public class RibbonHttpRequest extends AbstractClientHttpRequest {
}
@Override
- protected ClientHttpResponse executeInternal(HttpHeaders headers)
- throws IOException {
+ protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
try {
addHeaders(headers);
if (outputStream != null) {
@@ -87,19 +93,21 @@ public class RibbonHttpRequest extends AbstractClientHttpRequest {
HttpRequest request = builder.build();
HttpResponse response = client.executeWithLoadBalancer(request, config);
return new RibbonHttpResponse(response);
- } catch (Exception e) {
+ }
+ catch (Exception e) {
throw new IOException(e);
}
}
private void addHeaders(HttpHeaders headers) {
for (String name : headers.keySet()) {
- // apache http RequestContent pukes if there is a body and
- // the dynamic headers are already present
+ // apache http RequestContent pukes if there is a body and
+ // the dynamic headers are already present
if (isDynamic(name) && outputStream != null) {
continue;
}
- //Don't add content-length if the output stream is null. The RibbonClient does this for us.
+ // Don't add content-length if the output stream is null. The RibbonClient
+ // does this for us.
if (name.equals("Content-Length") && outputStream == null) {
continue;
}
@@ -111,6 +119,8 @@ public class RibbonHttpRequest extends AbstractClientHttpRequest {
}
private boolean isDynamic(String name) {
- return "Content-Length".equalsIgnoreCase(name) || "Transfer-Encoding".equalsIgnoreCase(name);
+ return "Content-Length".equalsIgnoreCase(name)
+ || "Transfer-Encoding".equalsIgnoreCase(name);
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpResponse.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpResponse.java
index 12a6e1929..d704cdbfd 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpResponse.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonHttpResponse.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,10 +20,12 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
+
+import com.netflix.client.http.HttpResponse;
+
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.AbstractClientHttpResponse;
-import com.netflix.client.http.HttpResponse;
/**
* @author Spencer Gibb
@@ -31,6 +33,7 @@ import com.netflix.client.http.HttpResponse;
public class RibbonHttpResponse extends AbstractClientHttpResponse {
private HttpResponse response;
+
private HttpHeaders httpHeaders;
public RibbonHttpResponse(HttpResponse response) {
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryFactory.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryFactory.java
index de307a9d1..b544b7ec1 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryFactory.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2017 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.springframework.cloud.netflix.ribbon;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
@@ -33,10 +34,12 @@ public class RibbonLoadBalancedRetryFactory implements LoadBalancedRetryFactory
}
@Override
- public LoadBalancedRetryPolicy createRetryPolicy(String service, ServiceInstanceChooser serviceInstanceChooser) {
+ public LoadBalancedRetryPolicy createRetryPolicy(String service,
+ ServiceInstanceChooser serviceInstanceChooser) {
RibbonLoadBalancerContext lbContext = this.clientFactory
.getLoadBalancerContext(service);
- return new RibbonLoadBalancedRetryPolicy(service, lbContext, serviceInstanceChooser, clientFactory.getClientConfig(service));
+ return new RibbonLoadBalancedRetryPolicy(service, lbContext,
+ serviceInstanceChooser, clientFactory.getClientConfig(service));
}
@Override
@@ -48,5 +51,5 @@ public class RibbonLoadBalancedRetryFactory implements LoadBalancedRetryFactory
public BackOffPolicy createBackOffPolicy(String service) {
return null;
}
-}
+}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicy.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicy.java
index 05fd0abec..9047cf2c7 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicy.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancedRetryPolicy.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2017 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,8 +19,14 @@ package org.springframework.cloud.netflix.ribbon;
import java.util.ArrayList;
import java.util.List;
+import com.netflix.client.config.CommonClientConfigKey;
+import com.netflix.client.config.IClientConfig;
+import com.netflix.client.config.IClientConfigKey;
+import com.netflix.loadbalancer.Server;
+import com.netflix.loadbalancer.ServerStats;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy;
@@ -29,48 +35,62 @@ import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonS
import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;
-import com.netflix.client.config.CommonClientConfigKey;
-import com.netflix.client.config.IClientConfig;
-import com.netflix.client.config.IClientConfigKey;
-import com.netflix.loadbalancer.Server;
-import com.netflix.loadbalancer.ServerStats;
-
/**
* {@link LoadBalancedRetryPolicy} for Ribbon clients.
+ *
* @author Ryan Baxter
*/
public class RibbonLoadBalancedRetryPolicy implements LoadBalancedRetryPolicy {
- public static final IClientConfigKey RETRYABLE_STATUS_CODES = new CommonClientConfigKey("retryableStatusCodes") {};
- private static final Log log = LogFactory.getLog(RibbonLoadBalancedRetryPolicy.class);
- private int sameServerCount = 0;
- private int nextServerCount = 0;
- private String serviceId;
- private RibbonLoadBalancerContext lbContext;
- private ServiceInstanceChooser loadBalanceChooser;
- List retryableStatusCodes = new ArrayList<>();
-
- private static final Log LOGGER = LogFactory.getLog(RibbonLoadBalancedRetryPolicy.class);
+ /**
+ * Retrayable status codes config key.
+ */
+ public static final IClientConfigKey RETRYABLE_STATUS_CODES = new CommonClientConfigKey(
+ "retryableStatusCodes") {
+ };
- public RibbonLoadBalancedRetryPolicy(String serviceId, RibbonLoadBalancerContext context, ServiceInstanceChooser loadBalanceChooser) {
+ private static final Log log = LogFactory.getLog(RibbonLoadBalancedRetryPolicy.class);
+
+ private int sameServerCount = 0;
+
+ private int nextServerCount = 0;
+
+ private String serviceId;
+
+ private RibbonLoadBalancerContext lbContext;
+
+ private ServiceInstanceChooser loadBalanceChooser;
+
+ List retryableStatusCodes = new ArrayList<>();
+
+ private static final Log LOGGER = LogFactory
+ .getLog(RibbonLoadBalancedRetryPolicy.class);
+
+ public RibbonLoadBalancedRetryPolicy(String serviceId,
+ RibbonLoadBalancerContext context,
+ ServiceInstanceChooser loadBalanceChooser) {
this.serviceId = serviceId;
this.lbContext = context;
this.loadBalanceChooser = loadBalanceChooser;
}
- public RibbonLoadBalancedRetryPolicy(String serviceId, RibbonLoadBalancerContext context, ServiceInstanceChooser loadBalanceChooser,
- IClientConfig clientConfig) {
+ public RibbonLoadBalancedRetryPolicy(String serviceId,
+ RibbonLoadBalancerContext context, ServiceInstanceChooser loadBalanceChooser,
+ IClientConfig clientConfig) {
this.serviceId = serviceId;
this.lbContext = context;
this.loadBalanceChooser = loadBalanceChooser;
- String retryableStatusCodesProp = clientConfig.getPropertyAsString(RETRYABLE_STATUS_CODES, "");
+ String retryableStatusCodesProp = clientConfig
+ .getPropertyAsString(RETRYABLE_STATUS_CODES, "");
String[] retryableStatusCodesArray = retryableStatusCodesProp.split(",");
- for(String code : retryableStatusCodesArray) {
- if(!StringUtils.isEmpty(code)) {
+ for (String code : retryableStatusCodesArray) {
+ if (!StringUtils.isEmpty(code)) {
try {
retryableStatusCodes.add(Integer.valueOf(code.trim()));
- } catch (NumberFormatException e) {
- log.warn("We cant add the status code because the code [ " + code + " ] could not be converted to an integer. ", e);
+ }
+ catch (NumberFormatException e) {
+ log.warn("We cant add the status code because the code [ " + code
+ + " ] could not be converted to an integer. ", e);
}
}
}
@@ -83,15 +103,17 @@ public class RibbonLoadBalancedRetryPolicy implements LoadBalancedRetryPolicy {
@Override
public boolean canRetrySameServer(LoadBalancedRetryContext context) {
- return sameServerCount < lbContext.getRetryHandler().getMaxRetriesOnSameServer() && canRetry(context);
+ return sameServerCount < lbContext.getRetryHandler().getMaxRetriesOnSameServer()
+ && canRetry(context);
}
@Override
public boolean canRetryNextServer(LoadBalancedRetryContext context) {
- //this will be called after a failure occurs and we increment the counter
- //so we check that the count is less than or equals to too make sure
- //we try the next server the right number of times
- return nextServerCount <= lbContext.getRetryHandler().getMaxRetriesOnNextServer() && canRetry(context);
+ // this will be called after a failure occurs and we increment the counter
+ // so we check that the count is less than or equals to too make sure
+ // we try the next server the right number of times
+ return nextServerCount <= lbContext.getRetryHandler().getMaxRetriesOnNextServer()
+ && canRetry(context);
}
@Override
@@ -101,44 +123,50 @@ public class RibbonLoadBalancedRetryPolicy implements LoadBalancedRetryPolicy {
@Override
public void registerThrowable(LoadBalancedRetryContext context, Throwable throwable) {
- //if this is a circuit tripping exception then notify the load balancer
+ // if this is a circuit tripping exception then notify the load balancer
if (lbContext.getRetryHandler().isCircuitTrippingException(throwable)) {
updateServerInstanceStats(context);
}
-
- //Check if we need to ask the load balancer for a new server.
- //Do this before we increment the counters because the first call to this method
- //is not a retry it is just an initial failure.
- if(!canRetrySameServer(context) && canRetryNextServer(context)) {
+
+ // Check if we need to ask the load balancer for a new server.
+ // Do this before we increment the counters because the first call to this method
+ // is not a retry it is just an initial failure.
+ if (!canRetrySameServer(context) && canRetryNextServer(context)) {
context.setServiceInstance(loadBalanceChooser.choose(serviceId));
}
- //This method is called regardless of whether we are retrying or making the first request.
- //Since we do not count the initial request in the retry count we don't reset the counter
- //until we actually equal the same server count limit. This will allow us to make the initial
- //request plus the right number of retries.
- if(sameServerCount >= lbContext.getRetryHandler().getMaxRetriesOnSameServer() && canRetry(context)) {
- //reset same server since we are moving to a new server
+ // This method is called regardless of whether we are retrying or making the first
+ // request.
+ // Since we do not count the initial request in the retry count we don't reset the
+ // counter
+ // until we actually equal the same server count limit. This will allow us to make
+ // the initial
+ // request plus the right number of retries.
+ if (sameServerCount >= lbContext.getRetryHandler().getMaxRetriesOnSameServer()
+ && canRetry(context)) {
+ // reset same server since we are moving to a new server
sameServerCount = 0;
nextServerCount++;
- if(!canRetryNextServer(context)) {
+ if (!canRetryNextServer(context)) {
context.setExhaustedOnly();
}
- } else {
+ }
+ else {
sameServerCount++;
}
}
-
+
private void updateServerInstanceStats(LoadBalancedRetryContext context) {
ServiceInstance serviceInstance = context.getServiceInstance();
if (serviceInstance instanceof RibbonServer) {
- Server lbServer = ((RibbonServer)serviceInstance).getServer();
+ Server lbServer = ((RibbonServer) serviceInstance).getServer();
ServerStats serverStats = lbContext.getServerStats(lbServer);
serverStats.incrementSuccessiveConnectionFailureCount();
- serverStats.addToFailureCount();
- LOGGER.debug(lbServer.getHostPort() + " RetryCount: " + context.getRetryCount()
- + " Successive Failures: " + serverStats.getSuccessiveConnectionFailureCount()
- + " CircuitBreakerTripped:" + serverStats.isCircuitBreakerTripped());
+ serverStats.addToFailureCount();
+ LOGGER.debug(lbServer.getHostPort() + " RetryCount: "
+ + context.getRetryCount() + " Successive Failures: "
+ + serverStats.getSuccessiveConnectionFailureCount()
+ + " CircuitBreakerTripped:" + serverStats.isCircuitBreakerTripped());
}
}
@@ -146,4 +174,5 @@ public class RibbonLoadBalancedRetryPolicy implements LoadBalancedRetryPolicy {
public boolean retryableStatusCode(int statusCode) {
return retryableStatusCodes.contains(statusCode);
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClient.java
index 34b053fae..fb51fbadd 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClient.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerClient.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -61,8 +61,10 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient {
RibbonServer ribbonServer = (RibbonServer) instance;
server = ribbonServer.getServer();
uri = updateToSecureConnectionIfNeeded(original, ribbonServer);
- } else {
- server = new Server(instance.getScheme(), instance.getHost(), instance.getPort());
+ }
+ else {
+ server = new Server(instance.getScheme(), instance.getHost(),
+ instance.getPort());
IClientConfig clientConfig = clientFactory.getClientConfig(serviceId);
ServerIntrospector serverIntrospector = serverIntrospector(serviceId);
uri = updateToSecureConnectionIfNeeded(original, clientConfig,
@@ -73,11 +75,14 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient {
@Override
public ServiceInstance choose(String serviceId) {
- return choose(serviceId, null);
+ return choose(serviceId, null);
}
/**
* New: Select a server using a 'key'.
+ * @param serviceId of the service to choose an instance for
+ * @param hint to specify the service instance
+ * @return the selected {@link ServiceInstance}
*/
public ServiceInstance choose(String serviceId, Object hint) {
Server server = getServer(getLoadBalancer(serviceId), hint);
@@ -89,32 +94,43 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient {
}
@Override
- public T execute(String serviceId, LoadBalancerRequest request) throws IOException {
- return execute(serviceId, request, null);
+ public T execute(String serviceId, LoadBalancerRequest request)
+ throws IOException {
+ return execute(serviceId, request, null);
}
/**
- * New: Execute a request by selecting server using a 'key'.
- * The hint will have to be the last parameter to not mess with the `execute(serviceId, ServiceInstance, request)`
- * method. This somewhat breaks the fluent coding style when using a lambda to define the LoadBalancerRequest.
+ * New: Execute a request by selecting server using a 'key'. The hint will have to be
+ * the last parameter to not mess with the `execute(serviceId, ServiceInstance,
+ * request)` method. This somewhat breaks the fluent coding style when using a lambda
+ * to define the LoadBalancerRequest.
+ * @param returned request execution result type
+ * @param serviceId id of the service to execute the request to
+ * @param request to be executed
+ * @param hint used to choose appropriate {@link Server} instance
+ * @return request execution result
+ * @throws IOException executing the request may result in an {@link IOException}
*/
- public T execute(String serviceId, LoadBalancerRequest request, Object hint) throws IOException {
+ public T execute(String serviceId, LoadBalancerRequest request, Object hint)
+ throws IOException {
ILoadBalancer loadBalancer = getLoadBalancer(serviceId);
Server server = getServer(loadBalancer, hint);
if (server == null) {
throw new IllegalStateException("No instances available for " + serviceId);
}
- RibbonServer ribbonServer = new RibbonServer(serviceId, server, isSecure(server,
- serviceId), serverIntrospector(serviceId).getMetadata(server));
+ RibbonServer ribbonServer = new RibbonServer(serviceId, server,
+ isSecure(server, serviceId),
+ serverIntrospector(serviceId).getMetadata(server));
return execute(serviceId, ribbonServer, request);
}
@Override
- public T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest request) throws IOException {
+ public T execute(String serviceId, ServiceInstance serviceInstance,
+ LoadBalancerRequest request) throws IOException {
Server server = null;
- if(serviceInstance instanceof RibbonServer) {
- server = ((RibbonServer)serviceInstance).getServer();
+ if (serviceInstance instanceof RibbonServer) {
+ server = ((RibbonServer) serviceInstance).getServer();
}
if (server == null) {
throw new IllegalStateException("No instances available for " + serviceId);
@@ -156,15 +172,13 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient {
return RibbonUtils.isSecure(config, serverIntrospector, server);
}
- /**
- * Note: This method could be removed?
- */
+ // Note: This method could be removed?
protected Server getServer(String serviceId) {
return getServer(getLoadBalancer(serviceId), null);
}
protected Server getServer(ILoadBalancer loadBalancer) {
- return getServer(loadBalancer, null);
+ return getServer(loadBalancer, null);
}
protected Server getServer(ILoadBalancer loadBalancer, Object hint) {
@@ -179,10 +193,17 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient {
return this.clientFactory.getLoadBalancer(serviceId);
}
+ /**
+ * Ribbon-server-specific {@link ServiceInstance} implementation.
+ */
public static class RibbonServer implements ServiceInstance {
+
private final String serviceId;
+
private final Server server;
+
private final boolean secure;
+
private Map metadata;
public RibbonServer(String serviceId, Server server) {
@@ -251,6 +272,7 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient {
sb.append('}');
return sb.toString();
}
+
}
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerContext.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerContext.java
index 72eb2471b..e837b9bab 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerContext.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonLoadBalancerContext.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,6 +27,7 @@ import com.netflix.servo.monitor.Timer;
* @author Spencer Gibb
*/
public class RibbonLoadBalancerContext extends LoadBalancerContext {
+
public RibbonLoadBalancerContext(ILoadBalancer lb) {
super(lb);
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonProperties.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonProperties.java
index 57737041b..4d47dd37b 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonProperties.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonProperties.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright 2018-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.springframework.cloud.netflix.ribbon;
import java.util.concurrent.TimeUnit;
@@ -21,7 +37,14 @@ import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_POOL_KEE
import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_PORT;
import static com.netflix.client.config.DefaultClientConfigImpl.DEFAULT_READ_TIMEOUT;
+/**
+ * Stores and allows the access to Ribbon {@link IClientConfig}.
+ *
+ * @author Spencer Gibb
+ * @author Tomasz Juchniewicz
+ */
public class RibbonProperties {
+
private final IClientConfig config;
public static RibbonProperties from(IClientConfig config) {
@@ -111,16 +134,17 @@ public class RibbonProperties {
Object property = this.config.getProperty(PoolKeepAliveTime);
if (property instanceof Long) {
return (Long) property;
- } else if (property instanceof String) {
- return Long.valueOf((String) property);
+ }
+ else if (property instanceof String) {
+ return Long.valueOf((String) property);
}
return null;
}
public long poolKeepAliveTime() {
- Long poolKeepAliveTime = getPoolKeepAliveTime();
- if (poolKeepAliveTime != null) {
- return poolKeepAliveTime;
+ Long poolKeepAliveTime = getPoolKeepAliveTime();
+ if (poolKeepAliveTime != null) {
+ return poolKeepAliveTime;
}
return DEFAULT_POOL_KEEP_ALIVE_TIME;
@@ -194,4 +218,5 @@ public class RibbonProperties {
public T get(IClientConfigKey key, T defaultValue) {
return this.config.get(key, defaultValue);
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonStatsRecorder.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonStatsRecorder.java
index 4f01100f9..ef70db101 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonStatsRecorder.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonStatsRecorder.java
@@ -1,6 +1,23 @@
+/*
+ * Copyright 2016-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.springframework.cloud.netflix.ribbon;
import java.util.concurrent.TimeUnit;
+
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerStats;
import com.netflix.servo.monitor.Stopwatch;
@@ -11,7 +28,9 @@ import com.netflix.servo.monitor.Stopwatch;
public class RibbonStatsRecorder {
private RibbonLoadBalancerContext context;
+
private ServerStats serverStats;
+
private Stopwatch tracer;
public RibbonStatsRecorder(RibbonLoadBalancerContext context, Server server) {
@@ -35,7 +54,9 @@ public class RibbonStatsRecorder {
if (this.tracer != null && this.serverStats != null) {
this.tracer.stop();
long duration = this.tracer.getDuration(TimeUnit.MILLISECONDS);
- this.context.noteRequestCompletion(serverStats, entity, exception, duration, null/* errorHandler */);
+ this.context.noteRequestCompletion(serverStats, entity, exception, duration,
+ null/* errorHandler */);
}
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonUtils.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonUtils.java
index 54fac1348..a8182da0b 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonUtils.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonUtils.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright 2016-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.springframework.cloud.netflix.ribbon;
import java.net.URI;
@@ -23,22 +39,32 @@ import static com.netflix.client.config.CommonClientConfigKey.EnableZoneAffinity
* @author Jacques-Etienne Beaudet
* @author Tim Ysewyn
*/
-public class RibbonUtils {
+public final class RibbonUtils {
+ /**
+ * Used to verify if property value is set.
+ */
public static final String VALUE_NOT_SET = "__not__set__";
+
+ /**
+ * Default Ribbon namespace.
+ */
public static final String DEFAULT_NAMESPACE = "ribbon";
private static final Map unsecureSchemeMapping;
- static
- {
+
+ static {
unsecureSchemeMapping = new HashMap<>();
unsecureSchemeMapping.put("http", "https");
unsecureSchemeMapping.put("ws", "wss");
}
+ private RibbonUtils() {
+ throw new AssertionError("Must not instantiate utility class.");
+ }
+
public static void initializeRibbonDefaults(String serviceId) {
- setRibbonProperty(serviceId, DeploymentContextBasedVipAddresses.key(),
- serviceId);
+ setRibbonProperty(serviceId, DeploymentContextBasedVipAddresses.key(), serviceId);
setRibbonProperty(serviceId, EnableZoneAffinity.key(), "true");
}
@@ -60,14 +86,16 @@ public class RibbonUtils {
}
/**
- * Determine if client is secure. If the supplied {@link IClientConfig} has the {@link CommonClientConfigKey#IsSecure}
- * set, return that value. Otherwise, query the supplied {@link ServerIntrospector}.
+ * Determine if client is secure. If the supplied {@link IClientConfig} has the
+ * {@link CommonClientConfigKey#IsSecure} set, return that value. Otherwise, query the
+ * supplied {@link ServerIntrospector}.
* @param config the supplied client configuration.
- * @param serverIntrospector
- * @param server
+ * @param serverIntrospector used to verify if the server provides secure connections
+ * @param server to verify
* @return true if the client is secure
*/
- public static boolean isSecure(IClientConfig config, ServerIntrospector serverIntrospector, Server server) {
+ public static boolean isSecure(IClientConfig config,
+ ServerIntrospector serverIntrospector, Server server) {
if (config != null) {
Boolean isSecure = config.get(CommonClientConfigKey.IsSecure);
if (isSecure != null) {
@@ -80,30 +108,28 @@ public class RibbonUtils {
/**
* Replace the scheme to https if needed. If the uri doesn't start with https and
- * {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the scheme.
- * This assumes the uri is already encoded to avoid double encoding.
- *
- * @param uri
- * @param config
- * @param serverIntrospector
- * @param server
- * @return
- *
+ * {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the
+ * scheme. This assumes the uri is already encoded to avoid double encoding.
+ * @param uri to modify if required
+ * @param config Ribbon {@link IClientConfig} configuration
+ * @param serverIntrospector used to verify if the server provides secure connections
+ * @param server to verify
+ * @return {@link URI} updated to https if necessary
* @deprecated use {@link #updateToSecureConnectionIfNeeded}
*/
- public static URI updateToHttpsIfNeeded(URI uri, IClientConfig config, ServerIntrospector serverIntrospector,
- Server server) {
+ public static URI updateToHttpsIfNeeded(URI uri, IClientConfig config,
+ ServerIntrospector serverIntrospector, Server server) {
return updateToSecureConnectionIfNeeded(uri, config, serverIntrospector, server);
}
/**
- * Replace the scheme to the secure variant if needed. If the {@link #unsecureSchemeMapping} map contains the uri
- * scheme and {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the scheme.
- * This assumes the uri is already encoded to avoid double encoding.
- *
- * @param uri
- * @param ribbonServer
- * @return
+ * Replace the scheme to the secure variant if needed. If the
+ * {@link #unsecureSchemeMapping} map contains the uri scheme and
+ * {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the
+ * scheme. This assumes the uri is already encoded to avoid double encoding.
+ * @param uri to modify if required
+ * @param ribbonServer to verify if it provides secure connections
+ * @return {@link URI} updated if required
*/
static URI updateToSecureConnectionIfNeeded(URI uri, ServiceInstance ribbonServer) {
String scheme = uri.getScheme();
@@ -113,26 +139,25 @@ public class RibbonUtils {
}
if (!StringUtils.isEmpty(uri.toString())
- && unsecureSchemeMapping.containsKey(scheme)
- && ribbonServer.isSecure()) {
+ && unsecureSchemeMapping.containsKey(scheme) && ribbonServer.isSecure()) {
return upgradeConnection(uri, unsecureSchemeMapping.get(scheme));
}
return uri;
}
/**
- * Replace the scheme to the secure variant if needed. If the {@link #unsecureSchemeMapping} map contains the uri
- * scheme and {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the scheme.
- * This assumes the uri is already encoded to avoid double encoding.
- *
- * @param uri
- * @param config
- * @param serverIntrospector
- * @param server
- * @return
+ * Replace the scheme to the secure variant if needed. If the
+ * {@link #unsecureSchemeMapping} map contains the uri scheme and
+ * {@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the
+ * scheme. This assumes the uri is already encoded to avoid double encoding.
+ * @param uri to modify if required
+ * @param config the supplied client configuration
+ * @param serverIntrospector used to verify if the server provides secure connections
+ * @param server to verify
+ * @return {@link URI} updated if required
*/
public static URI updateToSecureConnectionIfNeeded(URI uri, IClientConfig config,
- ServerIntrospector serverIntrospector, Server server) {
+ ServerIntrospector serverIntrospector, Server server) {
String scheme = uri.getScheme();
if (StringUtils.isEmpty(scheme)) {
@@ -148,13 +173,16 @@ public class RibbonUtils {
}
private static URI upgradeConnection(URI uri, String scheme) {
- UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(uri).scheme(scheme);
+ UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(uri)
+ .scheme(scheme);
if (uri.getRawQuery() != null) {
- // When building the URI, UriComponentsBuilder verify the allowed characters and does not
+ // When building the URI, UriComponentsBuilder verify the allowed characters
+ // and does not
// support the '+' so we replace it for its equivalent '%20'.
// See issue https://jira.spring.io/browse/SPR-10172
uriComponentsBuilder.replaceQuery(uri.getRawQuery().replace("+", "%20"));
}
return uriComponentsBuilder.build(true).toUri();
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospector.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospector.java
index d63641784..cfa2c5ea0 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospector.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospector.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package org.springframework.cloud.netflix.ribbon;
import java.util.Map;
+
import com.netflix.loadbalancer.Server;
/**
@@ -27,4 +28,5 @@ public interface ServerIntrospector {
boolean isSecure(Server server);
Map getMetadata(Server server);
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospectorProperties.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospectorProperties.java
index ce8633457..1250e2fe3 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospectorProperties.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ServerIntrospectorProperties.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2017 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@ package org.springframework.cloud.netflix.ribbon;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
+
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
@@ -28,7 +29,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("ribbon")
public class ServerIntrospectorProperties {
- private List securePorts = Arrays.asList(443,8443);
+ private List securePorts = Arrays.asList(443, 8443);
public List getSecurePorts() {
return securePorts;
@@ -40,8 +41,12 @@ public class ServerIntrospectorProperties {
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
ServerIntrospectorProperties that = (ServerIntrospectorProperties) o;
return Objects.equals(securePorts, that.securePorts);
}
@@ -53,9 +58,8 @@ public class ServerIntrospectorProperties {
@Override
public String toString() {
- return new StringBuilder("ServerIntrospectorProperties{")
- .append("securePorts=").append(securePorts)
- .append("}").toString();
+ return new StringBuilder("ServerIntrospectorProperties{").append("securePorts=")
+ .append(securePorts).append("}").toString();
}
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java
index d23408743..15121f7da 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2017 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,14 +17,16 @@
package org.springframework.cloud.netflix.ribbon;
import java.lang.reflect.Constructor;
-import org.springframework.beans.BeanUtils;
-import org.springframework.cloud.context.named.NamedContextFactory;
-import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+
import com.netflix.client.IClient;
import com.netflix.client.IClientConfigAware;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ILoadBalancer;
+import org.springframework.beans.BeanUtils;
+import org.springframework.cloud.context.named.NamedContextFactory;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+
/**
* A factory that creates client, load balancer and client configuration instances. It
* creates a Spring ApplicationContext per client name, and extracts the beans that it
@@ -43,6 +45,10 @@ public class SpringClientFactory extends NamedContextFactory {@link IClient} subtype
+ * @return {@link IClient} instance
* @throws RuntimeException if any error occurs
*/
public > C getClient(String name, Class clientClass) {
@@ -51,6 +57,8 @@ public class SpringClientFactory extends NamedContextFactory C instantiateWithConfig(AnnotationConfigApplicationContext context,
- Class clazz, IClientConfig config) {
+ Class clazz, IClientConfig config) {
C result = null;
-
+
try {
Constructor constructor = clazz.getConstructor(IClientConfig.class);
result = constructor.newInstance(config);
- } catch (Throwable e) {
+ }
+ catch (Throwable e) {
// Ignored
}
-
+
if (result == null) {
result = BeanUtils.instantiate(clazz);
-
+
if (result instanceof IClientConfigAware) {
((IClientConfigAware) result).initWithNiwsConfig(config);
}
-
+
if (context != null) {
context.getAutowireCapableBeanFactory().autowireBean(result);
}
}
-
+
return result;
}
@@ -119,4 +132,3 @@ public class SpringClientFactory extends NamedContextFactory {@link Server} subtype
* @author Spencer Gibb
*/
public class StaticServerList implements ServerList {
@@ -41,4 +45,5 @@ public class StaticServerList implements ServerList {
public List getUpdatedListOfServers() {
return servers;
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilter.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilter.java
index b0defeaa4..d4f86b35f 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilter.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/ZonePreferenceServerListFilter.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2014 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@ package org.springframework.cloud.netflix.ribbon;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
+
import com.netflix.client.config.IClientConfig;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DeploymentContext.ContextKey;
@@ -39,8 +40,8 @@ public class ZonePreferenceServerListFilter extends ZoneAffinityServerListFilter
public void initWithNiwsConfig(IClientConfig niwsClientConfig) {
super.initWithNiwsConfig(niwsClientConfig);
if (ConfigurationManager.getDeploymentContext() != null) {
- this.zone = ConfigurationManager.getDeploymentContext().getValue(
- ContextKey.zone);
+ this.zone = ConfigurationManager.getDeploymentContext()
+ .getValue(ContextKey.zone);
}
}
@@ -71,8 +72,12 @@ public class ZonePreferenceServerListFilter extends ZoneAffinityServerListFilter
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
ZonePreferenceServerListFilter that = (ZonePreferenceServerListFilter) o;
return Objects.equals(zone, that.zone);
}
@@ -84,9 +89,8 @@ public class ZonePreferenceServerListFilter extends ZoneAffinityServerListFilter
@Override
public String toString() {
- return new StringBuilder("ZonePreferenceServerListFilter{")
- .append("zone='").append(zone).append("'")
- .append("}").toString();
+ return new StringBuilder("ZonePreferenceServerListFilter{").append("zone='")
+ .append(zone).append("'").append("}").toString();
}
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientRibbonConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientRibbonConfiguration.java
index a02b4b1ae..5da66d9a6 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientRibbonConfiguration.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientRibbonConfiguration.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2017 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.ribbon.apache;
@@ -23,10 +22,16 @@ import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;
+import com.netflix.client.AbstractLoadBalancerAwareClient;
+import com.netflix.client.RetryHandler;
+import com.netflix.client.config.IClientConfig;
+import com.netflix.loadbalancer.ILoadBalancer;
+import com.netflix.servo.monitor.Monitors;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
+
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@@ -42,12 +47,6 @@ import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-import com.netflix.client.AbstractLoadBalancerAwareClient;
-import com.netflix.client.RetryHandler;
-import com.netflix.client.config.IClientConfig;
-import com.netflix.loadbalancer.ILoadBalancer;
-import com.netflix.servo.monitor.Monitors;
-
/**
* @author Spencer Gibb
*/
@@ -55,13 +54,49 @@ import com.netflix.servo.monitor.Monitors;
@ConditionalOnClass(name = "org.apache.http.client.HttpClient")
@ConditionalOnProperty(name = "ribbon.httpclient.enabled", matchIfMissing = true)
public class HttpClientRibbonConfiguration {
+
@RibbonClientName
private String name = "client";
+ @Bean
+ @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class)
+ @ConditionalOnMissingClass("org.springframework.retry.support.RetryTemplate")
+ public RibbonLoadBalancingHttpClient ribbonLoadBalancingHttpClient(
+ IClientConfig config, ServerIntrospector serverIntrospector,
+ ILoadBalancer loadBalancer, RetryHandler retryHandler,
+ CloseableHttpClient httpClient) {
+ RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient(
+ httpClient, config, serverIntrospector);
+ client.setLoadBalancer(loadBalancer);
+ client.setRetryHandler(retryHandler);
+ Monitors.registerObject("Client_" + this.name, client);
+ return client;
+ }
+
+ @Bean
+ @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class)
+ @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
+ public RetryableRibbonLoadBalancingHttpClient retryableRibbonLoadBalancingHttpClient(
+ IClientConfig config, ServerIntrospector serverIntrospector,
+ ILoadBalancer loadBalancer, RetryHandler retryHandler,
+ LoadBalancedRetryFactory loadBalancedRetryFactory,
+ CloseableHttpClient httpClient,
+ RibbonLoadBalancerContext ribbonLoadBalancerContext) {
+ RetryableRibbonLoadBalancingHttpClient client = new RetryableRibbonLoadBalancingHttpClient(
+ httpClient, config, serverIntrospector, loadBalancedRetryFactory);
+ client.setLoadBalancer(loadBalancer);
+ client.setRetryHandler(retryHandler);
+ client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext);
+ Monitors.registerObject("Client_" + this.name, client);
+ return client;
+ }
+
@Configuration
protected static class ApacheHttpClientConfiguration {
+
private final Timer connectionManagerTimer = new Timer(
"RibbonApacheHttpClientConfiguration.connectionManagerTimer", true);
+
private CloseableHttpClient httpClient;
@Autowired(required = false)
@@ -93,55 +128,27 @@ public class HttpClientRibbonConfiguration {
@Bean
@ConditionalOnMissingBean(CloseableHttpClient.class)
public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory,
- HttpClientConnectionManager connectionManager, IClientConfig config) {
+ HttpClientConnectionManager connectionManager, IClientConfig config) {
RibbonProperties ribbon = RibbonProperties.from(config);
Boolean followRedirects = ribbon.isFollowRedirects();
Integer connectTimeout = ribbon.connectTimeout();
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setRedirectsEnabled(followRedirects).build();
- this.httpClient = httpClientFactory.createBuilder().
- setDefaultRequestConfig(defaultRequestConfig).
- setConnectionManager(connectionManager).build();
+ this.httpClient = httpClientFactory.createBuilder()
+ .setDefaultRequestConfig(defaultRequestConfig)
+ .setConnectionManager(connectionManager).build();
return httpClient;
}
@PreDestroy
public void destroy() throws Exception {
connectionManagerTimer.cancel();
- if(httpClient != null) {
+ if (httpClient != null) {
httpClient.close();
}
}
+
}
- @Bean
- @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class)
- @ConditionalOnMissingClass(value = "org.springframework.retry.support.RetryTemplate")
- public RibbonLoadBalancingHttpClient ribbonLoadBalancingHttpClient(
- IClientConfig config, ServerIntrospector serverIntrospector,
- ILoadBalancer loadBalancer, RetryHandler retryHandler, CloseableHttpClient httpClient) {
- RibbonLoadBalancingHttpClient client = new RibbonLoadBalancingHttpClient(httpClient, config, serverIntrospector);
- client.setLoadBalancer(loadBalancer);
- client.setRetryHandler(retryHandler);
- Monitors.registerObject("Client_" + this.name, client);
- return client;
- }
-
- @Bean
- @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class)
- @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
- public RetryableRibbonLoadBalancingHttpClient retryableRibbonLoadBalancingHttpClient(
- IClientConfig config, ServerIntrospector serverIntrospector,
- ILoadBalancer loadBalancer, RetryHandler retryHandler,
- LoadBalancedRetryFactory loadBalancedRetryFactory, CloseableHttpClient httpClient,
- RibbonLoadBalancerContext ribbonLoadBalancerContext) {
- RetryableRibbonLoadBalancingHttpClient client = new RetryableRibbonLoadBalancingHttpClient(
- httpClient, config, serverIntrospector, loadBalancedRetryFactory);
- client.setLoadBalancer(loadBalancer);
- client.setRetryHandler(retryHandler);
- client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext);
- Monitors.registerObject("Client_" + this.name, client);
- return client;
- }
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeException.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeException.java
index 8e53719ba..d770a8271 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeException.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientStatusCodeException.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,28 +13,30 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.springframework.cloud.netflix.ribbon.apache;
-import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
+
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.util.EntityUtils;
+
import org.springframework.cloud.client.loadbalancer.RetryableStatusCodeException;
/**
- * A {@link RetryableStatusCodeException} for {@link HttpResponse}s
+ * A {@link RetryableStatusCodeException} for {@link HttpResponse}s.
+ *
* @author Ryan Baxter
*/
public class HttpClientStatusCodeException extends RetryableStatusCodeException {
- private BasicHttpResponse response;
+ private final BasicHttpResponse response;
- public HttpClientStatusCodeException(String serviceId, HttpResponse response, HttpEntity entity, URI uri) throws IOException {
+ public HttpClientStatusCodeException(String serviceId, HttpResponse response,
+ HttpEntity entity, URI uri) throws IOException {
super(serviceId, response.getStatusLine().getStatusCode(), response, uri);
this.response = new BasicHttpResponse(response.getStatusLine());
this.response.setLocale(response.getLocale());
@@ -48,4 +50,5 @@ public class HttpClientStatusCodeException extends RetryableStatusCodeException
public HttpResponse getResponse() {
return this.response;
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientUtils.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientUtils.java
index 67c70612d..bfdb07843 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientUtils.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/HttpClientUtils.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,10 +13,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.springframework.cloud.netflix.ribbon.apache;
import java.io.ByteArrayInputStream;
import java.io.IOException;
+
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
@@ -24,14 +26,19 @@ import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.util.EntityUtils;
/**
- * Provides basic utilities for {@link org.apache.http.client.HttpClient}
+ * Provides basic utilities for {@link org.apache.http.client.HttpClient}.
+ *
* @author Ryan Baxter
*/
-public class HttpClientUtils {
+public final class HttpClientUtils {
+
+ private HttpClientUtils() {
+ throw new AssertionError("Must not instantiate utility class.");
+ }
/**
- * Creates an new {@link HttpEntity} by copying the {@link HttpEntity} from the {@link HttpResponse}.
- * This method will close the response after copying the entity.
+ * Creates an new {@link HttpEntity} by copying the {@link HttpEntity} from the
+ * {@link HttpResponse}. This method will close the response after copying the entity.
* @param response The response to create the {@link HttpEntity} from
* @return A new {@link HttpEntity}
* @throws IOException thrown if there is a problem closing the response.
@@ -42,9 +49,10 @@ public class HttpClientUtils {
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(is);
entity.setContentLength(response.getEntity().getContentLength());
- if(CloseableHttpResponse.class.isInstance(response)) {
- ((CloseableHttpResponse)response).close();
+ if (CloseableHttpResponse.class.isInstance(response)) {
+ ((CloseableHttpResponse) response).close();
}
return entity;
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RetryableRibbonLoadBalancingHttpClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RetryableRibbonLoadBalancingHttpClient.java
index 021395ba3..2138abe10 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RetryableRibbonLoadBalancingHttpClient.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RetryableRibbonLoadBalancingHttpClient.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,28 +13,33 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.springframework.cloud.netflix.ribbon.apache;
import java.net.URI;
+import com.netflix.client.RequestSpecificRetryHandler;
+import com.netflix.client.RetryHandler;
+import com.netflix.client.config.IClientConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
+
import org.springframework.cloud.client.ServiceInstance;
+import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRecoveryCallback;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy;
import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser;
-import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy;
+import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer;
+import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerContext;
import org.springframework.cloud.netflix.ribbon.RibbonProperties;
import org.springframework.cloud.netflix.ribbon.RibbonStatsRecorder;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
-import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer;
-import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerContext;
import org.springframework.cloud.netflix.ribbon.support.ContextAwareRequest;
import org.springframework.http.HttpRequest;
import org.springframework.retry.RecoveryCallback;
@@ -46,30 +51,32 @@ import org.springframework.retry.policy.NeverRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.web.util.UriComponentsBuilder;
-import com.netflix.client.RequestSpecificRetryHandler;
-import com.netflix.client.RetryHandler;
-import com.netflix.client.config.IClientConfig;
-
/**
* An Apache HTTP client which leverages Spring Retry to retry failed requests.
+ *
* @author Ryan Baxter
* @author Gang Li
*/
-public class RetryableRibbonLoadBalancingHttpClient extends RibbonLoadBalancingHttpClient {
- private static final Log LOGGER = LogFactory.getLog(RetryableRibbonLoadBalancingHttpClient.class);
+public class RetryableRibbonLoadBalancingHttpClient
+ extends RibbonLoadBalancingHttpClient {
+
+ private static final Log LOGGER = LogFactory
+ .getLog(RetryableRibbonLoadBalancingHttpClient.class);
private LoadBalancedRetryFactory loadBalancedRetryFactory;
+
private RibbonLoadBalancerContext ribbonLoadBalancerContext;
public RetryableRibbonLoadBalancingHttpClient(CloseableHttpClient delegate,
- IClientConfig config, ServerIntrospector serverIntrospector,
- LoadBalancedRetryFactory loadBalancedRetryFactory) {
+ IClientConfig config, ServerIntrospector serverIntrospector,
+ LoadBalancedRetryFactory loadBalancedRetryFactory) {
super(delegate, config, serverIntrospector);
this.loadBalancedRetryFactory = loadBalancedRetryFactory;
}
@Override
- public RibbonApacheHttpResponse execute(final RibbonApacheHttpRequest request, final IClientConfig configOverride) throws Exception {
+ public RibbonApacheHttpResponse execute(final RibbonApacheHttpRequest request,
+ final IClientConfig configOverride) throws Exception {
final RequestConfig.Builder builder = RequestConfig.custom();
IClientConfig config = configOverride != null ? configOverride : this.config;
RibbonProperties ribbon = RibbonProperties.from(config);
@@ -79,37 +86,49 @@ public class RetryableRibbonLoadBalancingHttpClient extends RibbonLoadBalancingH
builder.setContentCompressionEnabled(ribbon.isGZipPayload(this.gzipPayload));
final RequestConfig requestConfig = builder.build();
- final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory.createRetryPolicy(this.getClientName(), this);
+ final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory
+ .createRetryPolicy(this.getClientName(), this);
RetryCallback retryCallback = context -> {
- //on retries the policy will choose the server and set it in the context
- //extract the server and update the request being made
+ // on retries the policy will choose the server and set it in the context
+ // extract the server and update the request being made
RibbonApacheHttpRequest newRequest = request;
RibbonStatsRecorder statsRecorder = null;
if (context instanceof LoadBalancedRetryContext) {
- ServiceInstance service = ((LoadBalancedRetryContext) context).getServiceInstance();
+ ServiceInstance service = ((LoadBalancedRetryContext) context)
+ .getServiceInstance();
validateServiceInstance(service);
if (service != null) {
- //Reconstruct the request URI using the host and port set in the retry context
- newRequest = newRequest.withNewUri(UriComponentsBuilder.newInstance().host(service.getHost())
- .scheme(service.getUri().getScheme()).userInfo(newRequest.getURI().getUserInfo())
+ // Reconstruct the request URI using the host and port set in the
+ // retry context
+ newRequest = newRequest.withNewUri(UriComponentsBuilder.newInstance()
+ .host(service.getHost()).scheme(service.getUri().getScheme())
+ .userInfo(newRequest.getURI().getUserInfo())
.port(service.getPort()).path(newRequest.getURI().getPath())
- .query(newRequest.getURI().getQuery()).fragment(newRequest.getURI().getFragment())
- .build().encode().toUri());
-
+ .query(newRequest.getURI().getQuery())
+ .fragment(newRequest.getURI().getFragment()).build().encode()
+ .toUri());
+
if (ribbonLoadBalancerContext == null) {
- LOGGER.error("RibbonLoadBalancerContext is null. Unable to update load balancer stats");
- } else if (service instanceof RibbonServer) {
- statsRecorder = new RibbonStatsRecorder(ribbonLoadBalancerContext, ((RibbonServer)service).getServer());
+ LOGGER.error(
+ "RibbonLoadBalancerContext is null. Unable to update load balancer stats");
+ }
+ else if (service instanceof RibbonServer) {
+ statsRecorder = new RibbonStatsRecorder(ribbonLoadBalancerContext,
+ ((RibbonServer) service).getServer());
}
}
}
newRequest = getSecureRequest(newRequest, configOverride);
HttpUriRequest httpUriRequest = newRequest.toRequest(requestConfig);
- final HttpResponse httpResponse = RetryableRibbonLoadBalancingHttpClient.this.delegate.execute(httpUriRequest);
- if (retryPolicy.retryableStatusCode(httpResponse.getStatusLine().getStatusCode())) {
- throw new HttpClientStatusCodeException(RetryableRibbonLoadBalancingHttpClient.this.clientName,
- httpResponse, HttpClientUtils.createEntity(httpResponse), httpUriRequest.getURI());
+ final HttpResponse httpResponse = RetryableRibbonLoadBalancingHttpClient.this.delegate
+ .execute(httpUriRequest);
+ if (retryPolicy
+ .retryableStatusCode(httpResponse.getStatusLine().getStatusCode())) {
+ throw new HttpClientStatusCodeException(
+ RetryableRibbonLoadBalancingHttpClient.this.clientName,
+ httpResponse, HttpClientUtils.createEntity(httpResponse),
+ httpUriRequest.getURI());
}
if (statsRecorder != null) {
statsRecorder.recordStats(httpResponse);
@@ -118,16 +137,18 @@ public class RetryableRibbonLoadBalancingHttpClient extends RibbonLoadBalancingH
};
LoadBalancedRecoveryCallback recoveryCallback = new LoadBalancedRecoveryCallback() {
@Override
- protected RibbonApacheHttpResponse createResponse(HttpResponse response, URI uri) {
+ protected RibbonApacheHttpResponse createResponse(HttpResponse response,
+ URI uri) {
return new RibbonApacheHttpResponse(response, uri);
}
};
- return this.executeWithRetry(request, retryPolicy, retryCallback, recoveryCallback);
+ return this.executeWithRetry(request, retryPolicy, retryCallback,
+ recoveryCallback);
}
-
+
@Override
public boolean isClientRetryable(ContextAwareRequest request) {
- return request!= null && isRequestRetryable(request);
+ return request != null && isRequestRetryable(request);
}
private boolean isRequestRetryable(ContextAwareRequest request) {
@@ -137,16 +158,22 @@ public class RetryableRibbonLoadBalancingHttpClient extends RibbonLoadBalancingH
return request.getContext().getRetryable();
}
- private RibbonApacheHttpResponse executeWithRetry(RibbonApacheHttpRequest request, LoadBalancedRetryPolicy retryPolicy,
- RetryCallback callback,
- RecoveryCallback recoveryCallback) throws Exception {
+ private RibbonApacheHttpResponse executeWithRetry(RibbonApacheHttpRequest request,
+ LoadBalancedRetryPolicy retryPolicy,
+ RetryCallback callback,
+ RecoveryCallback recoveryCallback)
+ throws Exception {
RetryTemplate retryTemplate = new RetryTemplate();
boolean retryable = isRequestRetryable(request);
- retryTemplate.setRetryPolicy(retryPolicy == null || !retryable ? new NeverRetryPolicy()
+ retryTemplate.setRetryPolicy(retryPolicy == null || !retryable
+ ? new NeverRetryPolicy()
: new RetryPolicy(request, retryPolicy, this, this.getClientName()));
- BackOffPolicy backOffPolicy = loadBalancedRetryFactory.createBackOffPolicy(this.getClientName());
- retryTemplate.setBackOffPolicy(backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
- RetryListener[] retryListeners = this.loadBalancedRetryFactory.createRetryListeners(this.getClientName());
+ BackOffPolicy backOffPolicy = loadBalancedRetryFactory
+ .createBackOffPolicy(this.getClientName());
+ retryTemplate.setBackOffPolicy(
+ backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
+ RetryListener[] retryListeners = this.loadBalancedRetryFactory
+ .createRetryListeners(this.getClientName());
if (retryListeners != null && retryListeners.length != 0) {
retryTemplate.setListeners(retryListeners);
}
@@ -154,19 +181,23 @@ public class RetryableRibbonLoadBalancingHttpClient extends RibbonLoadBalancingH
}
@Override
- public RequestSpecificRetryHandler getRequestSpecificRetryHandler(RibbonApacheHttpRequest request, IClientConfig requestConfig) {
+ public RequestSpecificRetryHandler getRequestSpecificRetryHandler(
+ RibbonApacheHttpRequest request, IClientConfig requestConfig) {
return new RequestSpecificRetryHandler(false, false, RetryHandler.DEFAULT, null);
}
+ public void setRibbonLoadBalancerContext(
+ RibbonLoadBalancerContext ribbonLoadBalancerContext) {
+ this.ribbonLoadBalancerContext = ribbonLoadBalancerContext;
+ }
+
static class RetryPolicy extends InterceptorRetryPolicy {
- public RetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy,
+
+ RetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy,
ServiceInstanceChooser serviceInstanceChooser, String serviceName) {
super(request, policy, serviceInstanceChooser, serviceName);
}
+
}
- public void setRibbonLoadBalancerContext(RibbonLoadBalancerContext ribbonLoadBalancerContext) {
- this.ribbonLoadBalancerContext = ribbonLoadBalancerContext;
- }
-
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequest.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequest.java
index ed11f8f68..d8db563ac 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequest.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpRequest.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,12 +18,14 @@ package org.springframework.cloud.netflix.ribbon.apache;
import java.net.URI;
import java.util.List;
+
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.BasicHttpEntity;
-import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext;
+
import org.springframework.cloud.netflix.ribbon.support.ContextAwareRequest;
+import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext;
import static org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer.Runner.customize;
@@ -60,9 +62,11 @@ public class RibbonApacheHttpRequest extends ContextAwareRequest implements Clon
// if the entity contentLength isn't set, transfer-encoding will be set
// to chunked in org.apache.http.protocol.RequestContent. See gh-1042
Long contentLength = this.context.getContentLength();
- if ("GET".equals(this.context.getMethod()) && (contentLength == null || contentLength < 0)) {
+ if ("GET".equals(this.context.getMethod())
+ && (contentLength == null || contentLength < 0)) {
entity.setContentLength(0);
- } else if (contentLength != null) {
+ }
+ else if (contentLength != null) {
entity.setContentLength(contentLength);
}
builder.setEntity(entity);
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponse.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponse.java
index 689fff082..f09730739 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponse.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonApacheHttpResponse.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,14 +25,16 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.apache.http.Header;
-import org.apache.http.HttpResponse;
-import org.springframework.http.HttpStatus;
-import org.springframework.util.Assert;
+
import com.google.common.reflect.TypeToken;
import com.netflix.client.ClientException;
import com.netflix.client.http.CaseInsensitiveMultiMap;
import com.netflix.client.http.HttpHeaders;
+import org.apache.http.Header;
+import org.apache.http.HttpResponse;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.util.Assert;
/**
* @author Christian Lohmann
@@ -40,6 +42,7 @@ import com.netflix.client.http.HttpHeaders;
public class RibbonApacheHttpResponse implements com.netflix.client.http.HttpResponse {
private HttpResponse httpResponse;
+
private URI uri;
public RibbonApacheHttpResponse(final HttpResponse httpResponse, final URI uri) {
@@ -68,7 +71,8 @@ public class RibbonApacheHttpResponse implements com.netflix.client.http.HttpRes
@Override
public boolean isSuccess() {
- return HttpStatus.valueOf(this.httpResponse.getStatusLine().getStatusCode()).is2xxSuccessful();
+ return HttpStatus.valueOf(this.httpResponse.getStatusLine().getStatusCode())
+ .is2xxSuccessful();
}
@Override
@@ -143,7 +147,7 @@ public class RibbonApacheHttpResponse implements com.netflix.client.http.HttpRes
}
/**
- * Not used
+ * Not used.
*/
@Override
public T getEntity(final Class type) throws Exception {
@@ -151,7 +155,7 @@ public class RibbonApacheHttpResponse implements com.netflix.client.http.HttpRes
}
/**
- * Not used
+ * Not used.
*/
@Override
public T getEntity(final Type type) throws Exception {
@@ -159,10 +163,11 @@ public class RibbonApacheHttpResponse implements com.netflix.client.http.HttpRes
}
/**
- * Not used
+ * Not used.
*/
@Override
public T getEntity(final TypeToken type) throws Exception {
return null;
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClient.java
index 21f688931..6f67826a7 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClient.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/apache/RibbonLoadBalancingHttpClient.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,21 +18,21 @@ package org.springframework.cloud.netflix.ribbon.apache;
import java.net.URI;
+import com.netflix.client.RequestSpecificRetryHandler;
+import com.netflix.client.RetryHandler;
+import com.netflix.client.config.IClientConfig;
+import com.netflix.loadbalancer.Server;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
+
import org.springframework.cloud.netflix.ribbon.RibbonProperties;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import org.springframework.cloud.netflix.ribbon.support.AbstractLoadBalancingClient;
import org.springframework.web.util.UriComponentsBuilder;
-import com.netflix.client.RequestSpecificRetryHandler;
-import com.netflix.client.RetryHandler;
-import com.netflix.client.config.IClientConfig;
-import com.netflix.loadbalancer.Server;
-
import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecureConnectionIfNeeded;
/**
@@ -40,7 +40,8 @@ import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecur
* @author Ryan Baxter
* @author Tim Ysewyn
*/
-// TODO: rename (ie new class that extends this in Dalston) to ApacheHttpLoadBalancingClient
+// TODO: rename (ie new class that extends this in Dalston) to
+// ApacheHttpLoadBalancingClient
public class RibbonLoadBalancingHttpClient extends
AbstractLoadBalancingClient {
@@ -67,7 +68,7 @@ public class RibbonLoadBalancingHttpClient extends
@Override
public RibbonApacheHttpResponse execute(RibbonApacheHttpRequest request,
- final IClientConfig configOverride) throws Exception {
+ final IClientConfig configOverride) throws Exception {
IClientConfig config = configOverride != null ? configOverride : this.config;
RibbonProperties ribbon = RibbonProperties.from(config);
RequestConfig requestConfig = RequestConfig.custom()
@@ -85,8 +86,8 @@ public class RibbonLoadBalancingHttpClient extends
@Override
public URI reconstructURIWithServer(Server server, URI original) {
- URI uri = updateToSecureConnectionIfNeeded(original, this.config, this.serverIntrospector,
- server);
+ URI uri = updateToSecureConnectionIfNeeded(original, this.config,
+ this.serverIntrospector, server);
return super.reconstructURIWithServer(server, uri);
}
@@ -97,7 +98,8 @@ public class RibbonLoadBalancingHttpClient extends
requestConfig);
}
- protected RibbonApacheHttpRequest getSecureRequest(RibbonApacheHttpRequest request, IClientConfig configOverride) {
+ protected RibbonApacheHttpRequest getSecureRequest(RibbonApacheHttpRequest request,
+ IClientConfig configOverride) {
if (isSecure(configOverride)) {
final URI secureUri = UriComponentsBuilder.fromUri(request.getUri())
.scheme("https").build(true).toUri();
@@ -105,4 +107,5 @@ public class RibbonLoadBalancingHttpClient extends
}
return request;
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClient.java
index b488f8e11..2cc3196b0 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClient.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpLoadBalancingClient.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,27 +19,26 @@ package org.springframework.cloud.netflix.ribbon.okhttp;
import java.net.URI;
import java.util.concurrent.TimeUnit;
+import com.netflix.client.config.IClientConfig;
+import com.netflix.loadbalancer.Server;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
import org.springframework.cloud.netflix.ribbon.RibbonProperties;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import org.springframework.cloud.netflix.ribbon.support.AbstractLoadBalancingClient;
import org.springframework.web.util.UriComponentsBuilder;
-import com.netflix.client.config.IClientConfig;
-import com.netflix.loadbalancer.Server;
-
import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecureConnectionIfNeeded;
-import okhttp3.OkHttpClient;
-import okhttp3.Request;
-import okhttp3.Response;
-
/**
* @author Spencer Gibb
* @author Ryan Baxter
* @author Tim Ysewyn
*/
-public class OkHttpLoadBalancingClient
- extends AbstractLoadBalancingClient {
+public class OkHttpLoadBalancingClient extends
+ AbstractLoadBalancingClient {
public OkHttpLoadBalancingClient(IClientConfig config,
ServerIntrospector serverIntrospector) {
@@ -47,7 +46,7 @@ public class OkHttpLoadBalancingClient
}
public OkHttpLoadBalancingClient(OkHttpClient delegate, IClientConfig config,
- ServerIntrospector serverIntrospector) {
+ ServerIntrospector serverIntrospector) {
super(delegate, config, serverIntrospector);
}
@@ -58,7 +57,7 @@ public class OkHttpLoadBalancingClient
@Override
public OkHttpRibbonResponse execute(OkHttpRibbonRequest ribbonRequest,
- final IClientConfig configOverride) throws Exception {
+ final IClientConfig configOverride) throws Exception {
boolean secure = isSecure(configOverride);
if (secure) {
final URI secureUri = UriComponentsBuilder.fromUri(ribbonRequest.getUri())
@@ -76,7 +75,8 @@ public class OkHttpLoadBalancingClient
IClientConfig config = configOverride != null ? configOverride : this.config;
RibbonProperties ribbon = RibbonProperties.from(config);
OkHttpClient.Builder builder = this.delegate.newBuilder()
- .connectTimeout(ribbon.connectTimeout(this.connectTimeout), TimeUnit.MILLISECONDS)
+ .connectTimeout(ribbon.connectTimeout(this.connectTimeout),
+ TimeUnit.MILLISECONDS)
.readTimeout(ribbon.readTimeout(this.readTimeout), TimeUnit.MILLISECONDS)
.followRedirects(ribbon.isFollowRedirects(this.followRedirects));
if (secure) {
@@ -88,8 +88,9 @@ public class OkHttpLoadBalancingClient
@Override
public URI reconstructURIWithServer(Server server, URI original) {
- URI uri = updateToSecureConnectionIfNeeded(original, this.config, this.serverIntrospector,
- server);
+ URI uri = updateToSecureConnectionIfNeeded(original, this.config,
+ this.serverIntrospector, server);
return super.reconstructURIWithServer(server, uri);
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonConfiguration.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonConfiguration.java
index 51b6edb2a..28a6ffb9d 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonConfiguration.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonConfiguration.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2017 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.ribbon.okhttp;
@@ -21,6 +20,14 @@ import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;
+import com.netflix.client.AbstractLoadBalancerAwareClient;
+import com.netflix.client.RetryHandler;
+import com.netflix.client.config.IClientConfig;
+import com.netflix.loadbalancer.ILoadBalancer;
+import com.netflix.servo.monitor.Monitors;
+import okhttp3.ConnectionPool;
+import okhttp3.OkHttpClient;
+
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
@@ -29,21 +36,12 @@ import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory;
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
import org.springframework.cloud.netflix.ribbon.RibbonClientName;
-import org.springframework.cloud.netflix.ribbon.RibbonProperties;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerContext;
+import org.springframework.cloud.netflix.ribbon.RibbonProperties;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-import com.netflix.client.AbstractLoadBalancerAwareClient;
-import com.netflix.client.RetryHandler;
-import com.netflix.client.config.IClientConfig;
-import com.netflix.loadbalancer.ILoadBalancer;
-import com.netflix.servo.monitor.Monitors;
-
-import okhttp3.ConnectionPool;
-import okhttp3.OkHttpClient;
-
/**
* @author Spencer Gibb
*/
@@ -51,17 +49,50 @@ import okhttp3.OkHttpClient;
@ConditionalOnProperty("ribbon.okhttp.enabled")
@ConditionalOnClass(name = "okhttp3.OkHttpClient")
public class OkHttpRibbonConfiguration {
+
@RibbonClientName
private String name = "client";
+ @Bean
+ @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class)
+ @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
+ public RetryableOkHttpLoadBalancingClient retryableOkHttpLoadBalancingClient(
+ IClientConfig config, ServerIntrospector serverIntrospector,
+ ILoadBalancer loadBalancer, RetryHandler retryHandler,
+ LoadBalancedRetryFactory loadBalancedRetryFactory, OkHttpClient delegate,
+ RibbonLoadBalancerContext ribbonLoadBalancerContext) {
+ RetryableOkHttpLoadBalancingClient client = new RetryableOkHttpLoadBalancingClient(
+ delegate, config, serverIntrospector, loadBalancedRetryFactory);
+ client.setLoadBalancer(loadBalancer);
+ client.setRetryHandler(retryHandler);
+ client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext);
+ Monitors.registerObject("Client_" + this.name, client);
+ return client;
+ }
+
+ @Bean
+ @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class)
+ @ConditionalOnMissingClass("org.springframework.retry.support.RetryTemplate")
+ public OkHttpLoadBalancingClient okHttpLoadBalancingClient(IClientConfig config,
+ ServerIntrospector serverIntrospector, ILoadBalancer loadBalancer,
+ RetryHandler retryHandler, OkHttpClient delegate) {
+ OkHttpLoadBalancingClient client = new OkHttpLoadBalancingClient(delegate, config,
+ serverIntrospector);
+ client.setLoadBalancer(loadBalancer);
+ client.setRetryHandler(retryHandler);
+ Monitors.registerObject("Client_" + this.name, client);
+ return client;
+ }
+
@Configuration
protected static class OkHttpClientConfiguration {
+
private OkHttpClient httpClient;
@Bean
@ConditionalOnMissingBean(ConnectionPool.class)
public ConnectionPool httpClientConnectionPool(IClientConfig config,
- OkHttpClientConnectionPoolFactory connectionPoolFactory) {
+ OkHttpClientConnectionPoolFactory connectionPoolFactory) {
RibbonProperties ribbon = RibbonProperties.from(config);
int maxTotalConnections = ribbon.maxTotalConnections();
long timeToLive = ribbon.poolKeepAliveTime();
@@ -72,57 +103,24 @@ public class OkHttpRibbonConfiguration {
@Bean
@ConditionalOnMissingBean(OkHttpClient.class)
public OkHttpClient client(OkHttpClientFactory httpClientFactory,
- ConnectionPool connectionPool, IClientConfig config) {
+ ConnectionPool connectionPool, IClientConfig config) {
RibbonProperties ribbon = RibbonProperties.from(config);
this.httpClient = httpClientFactory.createBuilder(false)
.connectTimeout(ribbon.connectTimeout(), TimeUnit.MILLISECONDS)
.readTimeout(ribbon.readTimeout(), TimeUnit.MILLISECONDS)
.followRedirects(ribbon.isFollowRedirects())
- .connectionPool(connectionPool)
- .build();
+ .connectionPool(connectionPool).build();
return this.httpClient;
}
@PreDestroy
public void destroy() {
- if(httpClient != null) {
+ if (httpClient != null) {
httpClient.dispatcher().executorService().shutdown();
httpClient.connectionPool().evictAll();
}
}
+
}
- @Bean
- @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class)
- @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
- public RetryableOkHttpLoadBalancingClient retryableOkHttpLoadBalancingClient(
- IClientConfig config,
- ServerIntrospector serverIntrospector,
- ILoadBalancer loadBalancer,
- RetryHandler retryHandler,
- LoadBalancedRetryFactory loadBalancedRetryFactory,
- OkHttpClient delegate, RibbonLoadBalancerContext ribbonLoadBalancerContext) {
- RetryableOkHttpLoadBalancingClient client = new RetryableOkHttpLoadBalancingClient(delegate, config,
- serverIntrospector, loadBalancedRetryFactory);
- client.setLoadBalancer(loadBalancer);
- client.setRetryHandler(retryHandler);
- client.setRibbonLoadBalancerContext(ribbonLoadBalancerContext);
- Monitors.registerObject("Client_" + this.name, client);
- return client;
- }
-
- @Bean
- @ConditionalOnMissingBean(AbstractLoadBalancerAwareClient.class)
- @ConditionalOnMissingClass(value = "org.springframework.retry.support.RetryTemplate")
- public OkHttpLoadBalancingClient okHttpLoadBalancingClient(
- IClientConfig config,
- ServerIntrospector serverIntrospector, ILoadBalancer loadBalancer,
- RetryHandler retryHandler, OkHttpClient delegate) {
- OkHttpLoadBalancingClient client = new OkHttpLoadBalancingClient(delegate, config,
- serverIntrospector);
- client.setLoadBalancer(loadBalancer);
- client.setRetryHandler(retryHandler);
- Monitors.registerObject("Client_" + this.name, client);
- return client;
- }
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequest.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequest.java
index 7df4c8a53..917641720 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequest.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonRequest.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,11 @@
package org.springframework.cloud.netflix.ribbon.okhttp;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.util.List;
+
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
@@ -26,10 +31,6 @@ import okio.BufferedSink;
import okio.Okio;
import okio.Source;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-import java.util.List;
import org.springframework.cloud.netflix.ribbon.support.ContextAwareRequest;
import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext;
@@ -63,18 +64,18 @@ public class OkHttpRibbonRequest extends ContextAwareRequest implements Cloneabl
RequestBody requestBody = null;
- if (this.context.getRequestEntity() != null && HttpMethod.permitsRequestBody(this.context.getMethod())) {
+ if (this.context.getRequestEntity() != null
+ && HttpMethod.permitsRequestBody(this.context.getMethod())) {
MediaType mediaType = null;
if (headers.get("Content-Type") != null) {
mediaType = MediaType.parse(headers.get("Content-Type"));
}
- requestBody = new InputStreamRequestBody(this.context.getRequestEntity(), mediaType, this.context.getContentLength());
+ requestBody = new InputStreamRequestBody(this.context.getRequestEntity(),
+ mediaType, this.context.getContentLength());
}
- Request.Builder builder = new Request.Builder()
- .url(url.build())
- .headers(headers.build())
- .method(this.context.getMethod(), requestBody);
+ Request.Builder builder = new Request.Builder().url(url.build())
+ .headers(headers.build()).method(this.context.getMethod(), requestBody);
customize(this.context.getRequestCustomizers(), builder);
@@ -88,10 +89,13 @@ public class OkHttpRibbonRequest extends ContextAwareRequest implements Cloneabl
static class InputStreamRequestBody extends RequestBody {
private InputStream inputStream;
+
private MediaType mediaType;
+
private Long contentLength;
- InputStreamRequestBody(InputStream inputStream, MediaType mediaType, Long contentLength) {
+ InputStreamRequestBody(InputStream inputStream, MediaType mediaType,
+ Long contentLength) {
this.inputStream = inputStream;
this.mediaType = mediaType;
this.contentLength = contentLength;
@@ -109,7 +113,8 @@ public class OkHttpRibbonRequest extends ContextAwareRequest implements Cloneabl
}
try {
return inputStream.available();
- } catch (IOException e) {
+ }
+ catch (IOException e) {
return 0;
}
}
@@ -120,11 +125,14 @@ public class OkHttpRibbonRequest extends ContextAwareRequest implements Cloneabl
try {
source = Okio.source(inputStream);
sink.writeAll(source);
- } finally {
+ }
+ finally {
if (source != null) {
source.close();
}
}
}
+
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponse.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponse.java
index 6fcfdc15f..f984fc4c6 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponse.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpRibbonResponse.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2015 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,9 +16,6 @@
package org.springframework.cloud.netflix.ribbon.okhttp;
-import okhttp3.Response;
-import okhttp3.ResponseBody;
-
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.URI;
@@ -27,11 +24,15 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.springframework.util.Assert;
+
import com.google.common.reflect.TypeToken;
import com.netflix.client.ClientException;
import com.netflix.client.http.CaseInsensitiveMultiMap;
import com.netflix.client.http.HttpHeaders;
+import okhttp3.Response;
+import okhttp3.ResponseBody;
+
+import org.springframework.util.Assert;
/**
* @author Spencer Gibb
@@ -39,7 +40,9 @@ import com.netflix.client.http.HttpHeaders;
public class OkHttpRibbonResponse implements com.netflix.client.http.HttpResponse {
private final ResponseBody body;
+
private URI uri;
+
private Response response;
public OkHttpRibbonResponse(Response response, URI uri) {
@@ -49,7 +52,6 @@ public class OkHttpRibbonResponse implements com.netflix.client.http.HttpRespons
this.uri = uri;
}
-
@Override
public int getStatus() {
return this.response.code();
@@ -86,12 +88,14 @@ public class OkHttpRibbonResponse implements com.netflix.client.http.HttpRespons
@Override
public Map> getHeaders() {
final Map> headers = new HashMap<>();
- for (Map.Entry> entry : this.response.headers().toMultimap().entrySet()) {
+ for (Map.Entry> entry : this.response.headers().toMultimap()
+ .entrySet()) {
String name = entry.getKey();
for (String value : entry.getValue()) {
if (headers.containsKey(name)) {
headers.get(name).add(value);
- } else {
+ }
+ else {
final List values = new ArrayList<>();
values.add(value);
headers.put(name, values);
@@ -105,7 +109,8 @@ public class OkHttpRibbonResponse implements com.netflix.client.http.HttpRespons
@Override
public HttpHeaders getHttpHeaders() {
final CaseInsensitiveMultiMap headers = new CaseInsensitiveMultiMap();
- for (Map.Entry> entry : this.response.headers().toMultimap().entrySet()) {
+ for (Map.Entry> entry : this.response.headers().toMultimap()
+ .entrySet()) {
for (String value : entry.getValue()) {
headers.addHeader(entry.getKey(), value);
}
@@ -146,4 +151,5 @@ public class OkHttpRibbonResponse implements com.netflix.client.http.HttpRespons
public T getEntity(TypeToken type) throws Exception {
return null;
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeException.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeException.java
index a5341fa6c..654e959ad 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeException.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/OkHttpStatusCodeException.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2018 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,33 +13,41 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.springframework.cloud.netflix.ribbon.okhttp;
+import java.net.URI;
+
import okhttp3.Response;
import okhttp3.ResponseBody;
-import java.io.IOException;
-import java.net.URI;
import org.springframework.cloud.client.loadbalancer.RetryableStatusCodeException;
/**
- * An {@link RetryableStatusCodeException} that captures a {@link Response}
+ * An {@link RetryableStatusCodeException} that captures a {@link Response}.
+ *
* @author Ryan Baxter
*/
public class OkHttpStatusCodeException extends RetryableStatusCodeException {
- private Response response;
- public OkHttpStatusCodeException(String serviceId, Response response, ResponseBody responseBody, URI uri) {
+ private final Response response;
+
+ public OkHttpStatusCodeException(String serviceId, Response response,
+ ResponseBody responseBody, URI uri) {
super(serviceId, response.code(), response, uri);
- this.response = new Response.Builder().code(response.code()).message(response.message()).protocol(response.protocol())
- .request(response.request()).headers(response.headers()).handshake(response.handshake())
- .cacheResponse(response.cacheResponse()).networkResponse(response.networkResponse())
- .priorResponse(response.priorResponse()).sentRequestAtMillis(response.sentRequestAtMillis())
- .body(responseBody).build();
+ this.response = new Response.Builder().code(response.code())
+ .message(response.message()).protocol(response.protocol())
+ .request(response.request()).headers(response.headers())
+ .handshake(response.handshake()).cacheResponse(response.cacheResponse())
+ .networkResponse(response.networkResponse())
+ .priorResponse(response.priorResponse())
+ .sentRequestAtMillis(response.sentRequestAtMillis()).body(responseBody)
+ .build();
}
@Override
public Response getResponse() {
return response;
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/RetryableOkHttpLoadBalancingClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/RetryableOkHttpLoadBalancingClient.java
index 825024320..42ffd3da6 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/RetryableOkHttpLoadBalancingClient.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/okhttp/RetryableOkHttpLoadBalancingClient.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2017 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,16 +13,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.springframework.cloud.netflix.ribbon.okhttp;
+import java.net.URI;
+
+import com.netflix.client.RequestSpecificRetryHandler;
+import com.netflix.client.RetryHandler;
+import com.netflix.client.config.IClientConfig;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
-
-import java.net.URI;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRecoveryCallback;
@@ -30,10 +35,10 @@ import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy;
import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser;
+import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerContext;
import org.springframework.cloud.netflix.ribbon.RibbonStatsRecorder;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
-import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer;
import org.springframework.cloud.netflix.ribbon.support.ContextAwareRequest;
import org.springframework.http.HttpRequest;
import org.springframework.retry.RecoveryCallback;
@@ -46,96 +51,112 @@ import org.springframework.retry.policy.NeverRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.web.util.UriComponentsBuilder;
-import com.netflix.client.RequestSpecificRetryHandler;
-import com.netflix.client.RetryHandler;
-import com.netflix.client.config.IClientConfig;
-
/**
* An OK HTTP client which leverages Spring Retry to retry failed request.
+ *
* @author Ryan Baxter
* @author Gang Li
*/
public class RetryableOkHttpLoadBalancingClient extends OkHttpLoadBalancingClient {
- private static final Log LOGGER = LogFactory.getLog(RetryableOkHttpLoadBalancingClient.class);
+
+ private static final Log LOGGER = LogFactory
+ .getLog(RetryableOkHttpLoadBalancingClient.class);
private LoadBalancedRetryFactory loadBalancedRetryFactory;
+
private RibbonLoadBalancerContext ribbonLoadBalancerContext;
- public RetryableOkHttpLoadBalancingClient(OkHttpClient delegate, IClientConfig config, ServerIntrospector serverIntrospector,
- LoadBalancedRetryFactory loadBalancedRetryPolicyFactory) {
+ public RetryableOkHttpLoadBalancingClient(OkHttpClient delegate, IClientConfig config,
+ ServerIntrospector serverIntrospector,
+ LoadBalancedRetryFactory loadBalancedRetryPolicyFactory) {
super(delegate, config, serverIntrospector);
this.loadBalancedRetryFactory = loadBalancedRetryPolicyFactory;
}
@Override
public boolean isClientRetryable(ContextAwareRequest request) {
- return request!= null && isRequestRetryable(request);
+ return request != null && isRequestRetryable(request);
}
-
+
private boolean isRequestRetryable(ContextAwareRequest request) {
- if (request.getContext() == null || request.getContext().getRetryable() == null) {
- return true;
+ if (request.getContext() == null || request.getContext().getRetryable() == null) {
+ return true;
}
return request.getContext().getRetryable();
}
-
- private OkHttpRibbonResponse executeWithRetry(OkHttpRibbonRequest request, LoadBalancedRetryPolicy retryPolicy,
- RetryCallback callback,
- RecoveryCallback recoveryCallback) throws Exception {
+
+ private OkHttpRibbonResponse executeWithRetry(OkHttpRibbonRequest request,
+ LoadBalancedRetryPolicy retryPolicy,
+ RetryCallback callback,
+ RecoveryCallback recoveryCallback) throws Exception {
RetryTemplate retryTemplate = new RetryTemplate();
- BackOffPolicy backOffPolicy = loadBalancedRetryFactory.createBackOffPolicy(this.getClientName());
- retryTemplate.setBackOffPolicy(backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
- RetryListener[] retryListeners = this.loadBalancedRetryFactory.createRetryListeners(this.getClientName());
+ BackOffPolicy backOffPolicy = loadBalancedRetryFactory
+ .createBackOffPolicy(this.getClientName());
+ retryTemplate.setBackOffPolicy(
+ backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
+ RetryListener[] retryListeners = this.loadBalancedRetryFactory
+ .createRetryListeners(this.getClientName());
if (retryListeners != null && retryListeners.length != 0) {
retryTemplate.setListeners(retryListeners);
}
boolean retryable = isRequestRetryable(request);
- retryTemplate.setRetryPolicy(retryPolicy == null || !retryable ? new NeverRetryPolicy()
+ retryTemplate.setRetryPolicy(retryPolicy == null || !retryable
+ ? new NeverRetryPolicy()
: new RetryPolicy(request, retryPolicy, this, this.getClientName()));
return retryTemplate.execute(callback, recoveryCallback);
}
@Override
public OkHttpRibbonResponse execute(final OkHttpRibbonRequest ribbonRequest,
- final IClientConfig configOverride) throws Exception {
- final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory.createRetryPolicy(this.getClientName(), this);
- RetryCallback retryCallback = new RetryCallback() {
+ final IClientConfig configOverride) throws Exception {
+ final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory
+ .createRetryPolicy(this.getClientName(), this);
+ RetryCallback retryCallback = new RetryCallback() {
@Override
- public OkHttpRibbonResponse doWithRetry(RetryContext context) throws Exception {
- //on retries the policy will choose the server and set it in the context
- //extract the server and update the request being made
+ public OkHttpRibbonResponse doWithRetry(RetryContext context)
+ throws Exception {
+ // on retries the policy will choose the server and set it in the context
+ // extract the server and update the request being made
OkHttpRibbonRequest newRequest = ribbonRequest;
RibbonStatsRecorder statsRecorder = null;
-
- if(context instanceof LoadBalancedRetryContext) {
- ServiceInstance service = ((LoadBalancedRetryContext)context).getServiceInstance();
+
+ if (context instanceof LoadBalancedRetryContext) {
+ ServiceInstance service = ((LoadBalancedRetryContext) context)
+ .getServiceInstance();
validateServiceInstance(service);
- //Reconstruct the request URI using the host and port set in the retry context
- newRequest = newRequest.withNewUri(new URI(service.getUri().getScheme(),
- newRequest.getURI().getUserInfo(), service.getHost(), service.getPort(),
- newRequest.getURI().getPath(), newRequest.getURI().getQuery(),
- newRequest.getURI().getFragment()));
-
+ // Reconstruct the request URI using the host and port set in the
+ // retry context
+ newRequest = newRequest
+ .withNewUri(new URI(service.getUri().getScheme(),
+ newRequest.getURI().getUserInfo(), service.getHost(),
+ service.getPort(), newRequest.getURI().getPath(),
+ newRequest.getURI().getQuery(),
+ newRequest.getURI().getFragment()));
+
if (ribbonLoadBalancerContext == null) {
- LOGGER.error("RibbonLoadBalancerContext is null. Unable to update load balancer stats");
- } else if (service instanceof RibbonServer) {
- statsRecorder = new RibbonStatsRecorder(ribbonLoadBalancerContext, ((RibbonServer)service).getServer());
+ LOGGER.error(
+ "RibbonLoadBalancerContext is null. Unable to update load balancer stats");
+ }
+ else if (service instanceof RibbonServer) {
+ statsRecorder = new RibbonStatsRecorder(ribbonLoadBalancerContext,
+ ((RibbonServer) service).getServer());
}
}
if (isSecure(configOverride)) {
- final URI secureUri = UriComponentsBuilder.fromUri(newRequest.getUri())
- .scheme("https").build().toUri();
+ final URI secureUri = UriComponentsBuilder
+ .fromUri(newRequest.getUri()).scheme("https").build().toUri();
newRequest = newRequest.withNewUri(secureUri);
}
OkHttpClient httpClient = getOkHttpClient(configOverride, secure);
final Request request = newRequest.toRequest();
Response response = httpClient.newCall(request).execute();
- if(retryPolicy.retryableStatusCode(response.code())) {
+ if (retryPolicy.retryableStatusCode(response.code())) {
ResponseBody responseBody = response.peekBody(Integer.MAX_VALUE);
response.close();
- throw new OkHttpStatusCodeException(RetryableOkHttpLoadBalancingClient.this.clientName,
- response, responseBody, newRequest.getURI());
+ throw new OkHttpStatusCodeException(
+ RetryableOkHttpLoadBalancingClient.this.clientName, response,
+ responseBody, newRequest.getURI());
}
if (statsRecorder != null) {
statsRecorder.recordStats(response);
@@ -143,27 +164,35 @@ public class RetryableOkHttpLoadBalancingClient extends OkHttpLoadBalancingClien
return new OkHttpRibbonResponse(response, newRequest.getUri());
}
};
- return this.executeWithRetry(ribbonRequest, retryPolicy, retryCallback, new LoadBalancedRecoveryCallback(){
+ return this.executeWithRetry(ribbonRequest, retryPolicy, retryCallback,
+ new LoadBalancedRecoveryCallback() {
- @Override
- protected OkHttpRibbonResponse createResponse(Response response, URI uri) {
- return new OkHttpRibbonResponse(response, uri);
- }
- });
+ @Override
+ protected OkHttpRibbonResponse createResponse(Response response,
+ URI uri) {
+ return new OkHttpRibbonResponse(response, uri);
+ }
+ });
}
@Override
- public RequestSpecificRetryHandler getRequestSpecificRetryHandler(OkHttpRibbonRequest request, IClientConfig requestConfig) {
+ public RequestSpecificRetryHandler getRequestSpecificRetryHandler(
+ OkHttpRibbonRequest request, IClientConfig requestConfig) {
return new RequestSpecificRetryHandler(false, false, RetryHandler.DEFAULT, null);
}
-
- public void setRibbonLoadBalancerContext(RibbonLoadBalancerContext ribbonLoadBalancerContext) {
+
+ public void setRibbonLoadBalancerContext(
+ RibbonLoadBalancerContext ribbonLoadBalancerContext) {
this.ribbonLoadBalancerContext = ribbonLoadBalancerContext;
}
static class RetryPolicy extends InterceptorRetryPolicy {
- public RetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy, ServiceInstanceChooser serviceInstanceChooser, String serviceName) {
+
+ RetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy,
+ ServiceInstanceChooser serviceInstanceChooser, String serviceName) {
super(request, policy, serviceInstanceChooser, serviceName);
}
+
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/AbstractLoadBalancingClient.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/AbstractLoadBalancingClient.java
index 2e3106de7..b751133dd 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/AbstractLoadBalancingClient.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/AbstractLoadBalancingClient.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2016 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,16 +12,10 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.ribbon.support;
-import org.springframework.cloud.client.ServiceInstance;
-import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser;
-import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
-import org.springframework.cloud.netflix.ribbon.RibbonProperties;
-import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import com.netflix.client.AbstractLoadBalancerAwareClient;
import com.netflix.client.ClientException;
import com.netflix.client.IResponse;
@@ -31,15 +25,25 @@ import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.reactive.LoadBalancerCommand;
+import org.springframework.cloud.client.ServiceInstance;
+import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser;
+import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
+import org.springframework.cloud.netflix.ribbon.RibbonProperties;
+import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
+
import static org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration.DEFAULT_CONNECT_TIMEOUT;
+import static org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration.DEFAULT_GZIP_PAYLOAD;
import static org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration.DEFAULT_READ_TIMEOUT;
-import static org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration.DEFAULT_GZIP_PAYLOAD;;
/**
+ * @param delegate
+ * @param {@link ContextAwareRequest} subtype
+ * @param {@link ServiceInstanceChooser} subtype
* @author Spencer Gibb
+ *
*/
-public abstract class AbstractLoadBalancingClient extends
- AbstractLoadBalancerAwareClient implements ServiceInstanceChooser {
+public abstract class AbstractLoadBalancingClient
+ extends AbstractLoadBalancerAwareClient implements ServiceInstanceChooser {
protected int connectTimeout;
@@ -54,14 +58,17 @@ public abstract class AbstractLoadBalancingClient builder) {
+ protected void customizeLoadBalancerCommandBuilder(S request, IClientConfig config,
+ LoadBalancerCommand.Builder builder) {
if (request.getLoadBalancerKey() != null) {
builder.withServerLocator(request.getLoadBalancerKey());
}
}
-
+
@Override
public ServiceInstance choose(String serviceId) {
Server server = this.getLoadBalancer().chooseServer(serviceId);
@@ -137,12 +146,18 @@ public abstract class AbstractLoadBalancingClient headers = context.getHeaders();
this.httpHeaders = new HttpHeaders();
- for(String key : headers.keySet()) {
+ for (String key : headers.keySet()) {
this.httpHeaders.put(key, headers.get(key));
}
this.uri = context.uri();
@@ -69,11 +72,13 @@ public abstract class ContextAwareRequest extends ClientRequest implements HttpR
}
protected RibbonCommandContext newContext(URI uri) {
- RibbonCommandContext commandContext = new RibbonCommandContext(this.context.getServiceId(),
- this.context.getMethod(), uri.toString(), this.context.getRetryable(),
- this.context.getHeaders(), this.context.getParams(), this.context.getRequestEntity(),
+ RibbonCommandContext commandContext = new RibbonCommandContext(
+ this.context.getServiceId(), this.context.getMethod(), uri.toString(),
+ this.context.getRetryable(), this.context.getHeaders(),
+ this.context.getParams(), this.context.getRequestEntity(),
this.context.getRequestCustomizers(), this.context.getContentLength(),
this.context.getLoadBalancerKey());
return commandContext;
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ResettableServletInputStreamWrapper.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ResettableServletInputStreamWrapper.java
index 11d5b93cd..628c26271 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ResettableServletInputStreamWrapper.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/ResettableServletInputStreamWrapper.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2017 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,14 +13,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.springframework.cloud.netflix.ribbon.support;
import java.io.ByteArrayInputStream;
import java.io.IOException;
+
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
+/**
+ * A wrapper for {@link ServletInputStream} providing additional capabilities to allow for
+ * resetting.
+ *
+ * @author Arne Dörnbrack
+ * @author Spencer Gibb
+ */
public class ResettableServletInputStreamWrapper extends ServletInputStream {
+
private final ByteArrayInputStream input;
public ResettableServletInputStreamWrapper(byte[] data) {
@@ -50,4 +60,5 @@ public class ResettableServletInputStreamWrapper extends ServletInputStream {
public synchronized void reset() throws IOException {
input.reset();
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContext.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContext.java
index 3d548e831..113a19e10 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContext.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonCommandContext.java
@@ -1,11 +1,11 @@
/*
- * Copyright 2013-2017 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -22,6 +22,7 @@ import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
+
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ReflectionUtils;
@@ -32,49 +33,66 @@ import org.springframework.util.StreamUtils;
* @author Yongsung Yoon
*/
public class RibbonCommandContext {
+
private final String serviceId;
+
private final String method;
+
private final String uri;
+
private final Boolean retryable;
+
private final MultiValueMap headers;
+
private final MultiValueMap params;
+
private final List requestCustomizers;
+
private InputStream requestEntity;
+
private Long contentLength;
+
private Object loadBalancerKey;
/**
- * Kept for backwards compatibility with Spring Cloud Sleuth 1.x versions
+ * Kept for backwards compatibility with Spring Cloud Sleuth 1.x versions.
+ * @param serviceId to be used with Ribbon request
+ * @param method to be used with Ribbon request
+ * @param uri {@link String} value of the uri to be used with Ribbon request
+ * @param retryable determines whether the requests should be retried
+ * @param headers to pass to the Ribbon request
+ * @param params parameters to pass to the Ribbon request
+ * @param requestEntity request content {@link InputStream}
*/
@Deprecated
- public RibbonCommandContext(String serviceId, String method,
- String uri, Boolean retryable, MultiValueMap headers,
- MultiValueMap params, InputStream requestEntity) {
+ public RibbonCommandContext(String serviceId, String method, String uri,
+ Boolean retryable, MultiValueMap headers,
+ MultiValueMap params, InputStream requestEntity) {
this(serviceId, method, uri, retryable, headers, params, requestEntity,
- new ArrayList(), null, null);
+ new ArrayList(), null, null);
}
public RibbonCommandContext(String serviceId, String method, String uri,
- Boolean retryable, MultiValueMap headers,
- MultiValueMap params, InputStream requestEntity,
- List requestCustomizers) {
+ Boolean retryable, MultiValueMap headers,
+ MultiValueMap params, InputStream requestEntity,
+ List requestCustomizers) {
this(serviceId, method, uri, retryable, headers, params, requestEntity,
- requestCustomizers, null, null);
+ requestCustomizers, null, null);
}
public RibbonCommandContext(String serviceId, String method, String uri,
- Boolean retryable, MultiValueMap headers,
- MultiValueMap params, InputStream requestEntity,
- List requestCustomizers, Long contentLength) {
+ Boolean retryable, MultiValueMap headers,
+ MultiValueMap params, InputStream requestEntity,
+ List requestCustomizers, Long contentLength) {
this(serviceId, method, uri, retryable, headers, params, requestEntity,
- requestCustomizers, contentLength, null);
+ requestCustomizers, contentLength, null);
}
public RibbonCommandContext(String serviceId, String method, String uri,
- Boolean retryable, MultiValueMap headers,
- MultiValueMap params, InputStream requestEntity,
- List requestCustomizers, Long contentLength,
- Object loadBalancerKey) {
+ Boolean retryable, MultiValueMap headers,
+ MultiValueMap params, InputStream requestEntity,
+ List requestCustomizers, Long contentLength,
+ Object loadBalancerKey) {
Assert.notNull(serviceId, "serviceId may not be null");
Assert.notNull(method, "method may not be null");
Assert.notNull(uri, "uri may not be null");
@@ -96,16 +114,16 @@ public class RibbonCommandContext {
public URI uri() {
try {
return new URI(this.uri);
- } catch (URISyntaxException e) {
+ }
+ catch (URISyntaxException e) {
ReflectionUtils.rethrowRuntimeException(e);
}
return null;
}
/**
- * Use getMethod()
- *
- * @return
+ * Use {@link #getMethod()}.
+ * @return request method
*/
@Deprecated
public String getVerb() {
@@ -140,20 +158,23 @@ public class RibbonCommandContext {
if (requestEntity == null) {
return null;
}
- //If the route is not retryable there is no point in copying the RequestEntity. This
- //has memory implications in all cases but especially when uploading large files through
- //Zuul
- if(!retryable) {
+ // If the route is not retryable there is no point in copying the RequestEntity.
+ // This
+ // has memory implications in all cases but especially when uploading large files
+ // through
+ // Zuul
+ if (!retryable) {
return requestEntity;
}
try {
if (!(requestEntity instanceof ResettableServletInputStreamWrapper)) {
requestEntity = new ResettableServletInputStreamWrapper(
- StreamUtils.copyToByteArray(requestEntity));
+ StreamUtils.copyToByteArray(requestEntity));
}
requestEntity.reset();
- } finally {
+ }
+ finally {
return requestEntity;
}
}
@@ -180,26 +201,28 @@ public class RibbonCommandContext {
@Override
public boolean equals(Object o) {
- if (this == o)
+ if (this == o) {
return true;
- if (o == null || getClass() != o.getClass())
+ }
+ if (o == null || getClass() != o.getClass()) {
return false;
+ }
RibbonCommandContext that = (RibbonCommandContext) o;
- return Objects.equals(serviceId, that.serviceId) && Objects
- .equals(method, that.method) && Objects.equals(uri, that.uri)
- && Objects.equals(retryable, that.retryable) && Objects
- .equals(headers, that.headers) && Objects
- .equals(params, that.params) && Objects
- .equals(requestEntity, that.requestEntity) && Objects
- .equals(requestCustomizers, that.requestCustomizers) && Objects
- .equals(contentLength, that.contentLength) && Objects
- .equals(loadBalancerKey, that.loadBalancerKey);
+ return Objects.equals(serviceId, that.serviceId)
+ && Objects.equals(method, that.method) && Objects.equals(uri, that.uri)
+ && Objects.equals(retryable, that.retryable)
+ && Objects.equals(headers, that.headers)
+ && Objects.equals(params, that.params)
+ && Objects.equals(requestEntity, that.requestEntity)
+ && Objects.equals(requestCustomizers, that.requestCustomizers)
+ && Objects.equals(contentLength, that.contentLength)
+ && Objects.equals(loadBalancerKey, that.loadBalancerKey);
}
@Override
public int hashCode() {
return Objects.hash(serviceId, method, uri, retryable, headers, params,
- requestEntity, requestCustomizers, contentLength, loadBalancerKey);
+ requestEntity, requestCustomizers, contentLength, loadBalancerKey);
}
@Override
@@ -218,4 +241,5 @@ public class RibbonCommandContext {
sb.append('}');
return sb.toString();
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRequestCustomizer.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRequestCustomizer.java
index 4e416a1b9..3546932bf 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRequestCustomizer.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRequestCustomizer.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2013-2016 the original author or authors.
+ * Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
*/
package org.springframework.cloud.netflix.ribbon.support;
@@ -20,21 +19,33 @@ package org.springframework.cloud.netflix.ribbon.support;
import java.util.List;
/**
+ * Interface providing methods for customizing Ribbon requests.
+ *
+ * @param Request builder type
* @author Spencer Gibb
*/
public interface RibbonRequestCustomizer {
+
boolean accepts(Class builderClass);
+
void customize(B builder);
class Runner {
+ private Runner() {
+ throw new AssertionError("Must not instantiate utility class.");
+ }
+
@SuppressWarnings("unchecked")
- public static void customize(List customizers, Object builder) {
+ public static void customize(List customizers,
+ Object builder) {
for (RibbonRequestCustomizer customizer : customizers) {
if (customizer.accepts(builder.getClass())) {
customizer.customize(builder);
}
}
}
+
}
+
}
diff --git a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRetryPolicy.java b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRetryPolicy.java
index 157ce5013..7f5ce20ec 100644
--- a/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRetryPolicy.java
+++ b/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/support/RibbonRetryPolicy.java
@@ -1,8 +1,25 @@
+/*
+ * Copyright 2018-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.springframework.cloud.netflix.ribbon.support;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
+
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext;
@@ -15,9 +32,13 @@ import org.springframework.retry.RetryContext;
* @author Ryan Baxter
*/
public class RibbonRetryPolicy extends InterceptorRetryPolicy {
+
private HttpRequest request;
+
private String serviceId;
- public RibbonRetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy, ServiceInstanceChooser serviceInstanceChooser, String serviceName) {
+
+ public RibbonRetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy,
+ ServiceInstanceChooser serviceInstanceChooser, String serviceName) {
super(request, policy, serviceInstanceChooser, serviceName);
this.request = request;
this.serviceId = serviceName;
@@ -26,13 +47,14 @@ public class RibbonRetryPolicy extends InterceptorRetryPolicy {
@Override
public boolean canRetry(RetryContext context) {
/*
- * In InterceptorRetryPolicy.canRetry we ask the LoadBalancer to choose a server if one is not
- * set in the retry context and then return true. RetryTemplat calls the canRetry method of
- * the policy even on its first execution. So the fact that we didnt have a service instance set
- * in the RetryContext signaled that it was the first execution and we should return true.
+ * In InterceptorRetryPolicy.canRetry we ask the LoadBalancer to choose a server
+ * if one is not set in the retry context and then return true. RetryTemplat calls
+ * the canRetry method of the policy even on its first execution. So the fact that
+ * we didnt have a service instance set in the RetryContext signaled that it was
+ * the first execution and we should return true.
*
*/
- if(context.getRetryCount() == 0) {
+ if (context.getRetryCount() == 0) {
return true;
}
return super.canRetry(context);
@@ -40,15 +62,19 @@ public class RibbonRetryPolicy extends InterceptorRetryPolicy {
@Override
public RetryContext open(RetryContext parent) {
- LoadBalancedRetryContext context = new LoadBalancedRetryContext(parent, this.request);
- context.setServiceInstance(new RibbonRetryPolicyServiceInstance(serviceId, request));
+ LoadBalancedRetryContext context = new LoadBalancedRetryContext(parent,
+ this.request);
+ context.setServiceInstance(
+ new RibbonRetryPolicyServiceInstance(serviceId, request));
return context;
}
class RibbonRetryPolicyServiceInstance implements ServiceInstance {
private String serviceId;
+
private HttpRequest request;
+
private Map metadata;
RibbonRetryPolicyServiceInstance(String serviceId, HttpRequest request) {
@@ -86,5 +112,7 @@ public class RibbonRetryPolicy extends InterceptorRetryPolicy {
public Map