Compare commits

...
Author SHA1 Message Date
buildmaster c33bc490cd Update SNAPSHOT to 2.2.8.RELEASE 2021-04-21 17:10:24 +00:00
Olga MaciaszekSharma d738b3b224 Upgrade Feign to 10.12. Fixes gh-530. 2021-04-21 10:23:38 +02:00
buildmaster 0c1d281970 Bumping versions 2021-04-20 21:33:18 +00:00
Olga MaciaszekSharma 0bf0426f60 Update GH actions setup. 2021-04-20 16:50:36 +02:00
Leandro Quiroga 9f9ce39789 Fix typo. 2021-04-20 16:50:18 +02:00
Olga MaciaszekSharma 4d0caec7ee Fix checkstyle and formatting. 2021-04-13 15:17:00 +02:00
Olga MaciaszekSharma 92f7ba9901 Fix GH actions setup 2021-04-13 15:08:27 +02:00
Olga MaciaszekSharma b2c208ba5f Fix GH actions setup 2021-04-13 15:08:00 +02:00
Olga MaciaszekSharma cdfd3695c2 Add GH actions build icon. 2021-04-13 15:03:23 +02:00
Olga MaciaszekSharma 59216f2f82 Switch to building the project with GH actions. 2021-04-13 14:53:48 +02:00
Sam Kruglov 4d827623f0 Add FeignClientBuilder.Builder#customize(FeignBuilderCustomizer) (#499) (#515) 2021-04-13 12:57:35 +02:00
Olga MaciaszekSharma 5e494aa196 Add more logging. Fixes gh-517. 2021-04-12 14:29:45 +02:00
Thanh e3439f38bc Add Apache HC5 client option (#498) 2021-03-11 14:14:34 +01:00
Hyeonmin Park 2a23b6d304 Support Pageable, Sort annotated as SpringQueryMap to use with RequestBody (#502) 2021-03-10 17:30:36 +01:00
Olga Maciaszek-Sharma 6b436c4133 Set followRedirects via properties. (#500) 2021-03-03 11:20:48 +01:00
Olga MaciaszekSharma b4fb3fe7b4 Refactor. 2021-03-01 15:35:49 +01:00
Olga MaciaszekSharma b8129f52b7 Use delegate in RetryableFeignLoadBalancer when url present. Fixes gh-494. 2021-03-01 15:19:20 +01:00
Krishna Kumar Mishra a2b798c31a mentioning Spring Cloud OpenFeign instead of Sleuth (#497) 2021-02-26 18:28:12 +01:00
Olga Maciaszek-Sharma 11fd7dc43e Use Feign naming convention for circuit names. (#496)
Fixes gh-484.
2021-02-26 18:09:29 +01:00
Olga Maciaszek-Sharma cf20710cad Improve charset determination (#491) 2021-02-25 09:42:18 +01:00
Olga Maciaszek-Sharma c92849e28e Allow using multiple qualifiers for feign clients. (#485)
* Allow using multiple qualifiers for feign clients. Fixes gh-471.
2021-02-18 13:28:18 +01:00
Tim Peeters a205afb88d Fixes #482 No bean found of type Targeter. (#483) 2021-02-16 16:28:39 +01:00
buildmaster 37e1c2fd11 Bumping versions to 2.2.8.BUILD-SNAPSHOT after release 2021-02-11 14:15:44 +00:00
buildmaster ce7a55a484 Going back to snapshots 2021-02-11 14:15:44 +00:00
buildmaster 10c6992935 Update SNAPSHOT to 2.2.7.RELEASE 2021-02-11 14:14:19 +00:00
Hyeonmin Park d87375e835 Encode Pageable.Sort with percent encoded comma. Fixes gh-440. (#467)
* Encode Pageable.Sort with percent encoded comma. Fixes gh-440.

* Replace ifs with assert in FeignPageableEncodingTests
2021-02-08 18:33:12 +01:00
Hyeonmin Park cc9af41dfe Add configuration metadata for feign.autoconfiguration.jackson.enabled (#478) 2021-02-08 16:51:47 +01:00
Tim Peeters 9bb8b43d58 Import OpenFeign bom 2021-02-08 16:18:52 +01:00
Olga Maciaszek-Sharma 60558c46ef Reformat. 2021-02-02 15:31:06 +01:00
Olga Maciaszek-Sharma 89db04d7d0 Fix broken reference in docs. 2021-02-02 15:30:43 +01:00
Olga Maciaszek-Sharma 27a3967975 Support all non-deprecated Jackson naming strategies for page deserialization. Fixes gh-170. (#477) 2021-02-02 14:10:46 +01:00
spencergibb 0c4c19bfcd Better classpath protections for pageable modules.
Fixes gh-474

# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignAutoConfiguration.java
2021-01-29 12:29:33 +01:00
Olga Maciaszek-Sharma c672d205d7 Use case-insensitive ResponseEntity headers. Fixes gh-456. (#472) 2021-01-27 16:52:29 +01:00
Nikita Konev 6b29a1f7df Move Spring Data Jackson Modules from FeignClientsConfiguration to FeignAutoConfiguration - Fix https://github.com/spring-cloud/spring-cloud-openfeign/issues/205 (#430) 2021-01-26 09:23:51 +01:00
Olga Maciaszek-Sharma bbef08205d Use CircuitBreaker even when no fallback. (#466) 2021-01-22 16:53:32 +01:00
Olga Maciaszek-Sharma 0799f3dd7c Use org security policy.
(cherry picked from commit 25b8202991)
2021-01-22 10:14:04 +01:00
Marcin Grzejszczak 7ef5c0ce96 Lazy openfeign bean registration (#455)
without this change we're eagerly resolving placeholder properties in passed URLs / names. Since this happens at bean definition level it's extremely early e.g. Spring Cloud Contract has not yet registered any placeholders that Feign could try to consume.

with this change we're changing the bean to become lazy initialized and we resolve the placeholder values at runtime - as late as possible.

Fixes gh-441.
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsRegistrar.java
2021-01-20 15:13:21 +01:00
Olga Maciaszek-Sharma 14914b4c97 Fixes gh-460. Remove unused variable. 2021-01-19 12:48:11 +01:00
Olga Maciaszek-Sharma 6bfb1edcf1 Revert "Edit sagan-index."
This reverts commit 01a3898e83.
2021-01-18 11:23:30 +01:00
Olga Maciaszek-Sharma 01a3898e83 Edit sagan-index. 2021-01-18 11:20:41 +01:00
Olga Maciaszek-Sharma 286360cf7b Add information on contributing, community support and commercial support to project site (#458)
* Add information on contributing, community support and commercial support to project site.

* Fixes after review.
2021-01-18 11:11:32 +01:00
Olga Maciaszek-Sharma 14eb8a7bb1 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/src/main/asciidoc/_configprops.adoc
2021-01-14 16:02:02 +01:00
Olga Maciaszek-Sharma a79d82584e Update docs. 2021-01-14 15:50:47 +01:00
Olga Maciaszek-Sharma ae3e3efb26 Add license link to README. 2021-01-14 15:21:21 +01:00
Marcin Grzejszczak e32b10b60f Added support for Spring Cloud CircuitBreaker
fixes gh-279
2020-12-15 18:15:49 +01:00
79 changed files with 3950 additions and 560 deletions
-38
View File
@@ -1,38 +0,0 @@
version: 2
jobs:
build:
docker:
- image: springcloud/pipeline-base
environment:
_JAVA_OPTIONS: "-Xms1024m -Xmx2048m"
TERM: dumb
branches:
ignore:
- gh-pages # list of branches to ignore
steps:
- checkout
- restore_cache:
key: sc-openfeign-{{ .Branch }}
- run:
name: "Download dependencies"
command: ./mvnw -s .settings.xml -U --fail-never dependency:go-offline || true
- save_cache:
key: sc-openfeign-{{ .Branch }}
paths:
- ~/.m2
- run:
name: "Running build"
command: ./mvnw -s .settings.xml clean org.jacoco:jacoco-maven-plugin:prepare-agent install -U -P sonar -nsu --batch-mode -Dmaven.test.redirectTestOutputToFile=true -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- run:
name: "Aggregate test results"
when: always
command: |
mkdir -p $CIRCLE_TEST_REPORTS/junit/
find . -type f -regex ".*/target/.*-reports/.*" -exec cp {} $CIRCLE_TEST_REPORTS/junit/ \;
bash <(curl -s https://codecov.io/bash)
- store_artifacts:
path: /junit/
destination: artifacts
- store_test_results:
path: /junit/
destination: testartifacts
+35
View File
@@ -0,0 +1,35 @@
# This workflow will build a Java project with Maven
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Build
on:
push:
branches: [ 2.2.x ]
pull_request:
branches: [ 2.2.x ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
java: ["8", "11", "16"]
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Cache local Maven repository
uses: actions/cache@v2
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Build with Maven
run: ./mvnw clean install -B -U
+7 -1
View File
@@ -5,7 +5,7 @@ Edit the files in the src/main/asciidoc/ directory instead.
//// ////
image:https://circleci.com/gh/spring-cloud/spring-cloud-openfeign.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-openfeign"] image::https://github.com/spring-cloud/spring-cloud-openfeign/workflows/Build/badge.svg?branch=2.2.x&style=svg["Build",link="https://github.com/spring-cloud/spring-cloud-openfeign/actions"]
image:https://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"] image:https://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
@@ -28,6 +28,8 @@ image:https://api.codacy.com/project/badge/Grade/97b04c4e609c4b4f86b415e4437a648
:project-full-name: Spring Cloud OpenFeign :project-full-name: Spring Cloud OpenFeign
:all: {asterisk}{asterisk} :all: {asterisk}{asterisk}
:core_path: {project-root}/spring-cloud-openfeign-core
This project provides OpenFeign integrations for Spring Boot apps through autoconfiguration This project provides OpenFeign integrations for Spring Boot apps through autoconfiguration
and binding to the Spring Environment and other Spring programming model idioms. and binding to the Spring Environment and other Spring programming model idioms.
@@ -314,3 +316,7 @@ Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on t
- `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`. - `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`.
IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources. IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources.
== License
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/master/LICENSE.txt[here].
-5
View File
@@ -1,5 +0,0 @@
# Security Policy
## Reporting a Vulnerability
To report security vulnerabilities, please go to https://pivotal.io/security.
+1 -1
View File
@@ -6,7 +6,7 @@
<parent> <parent>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId> <artifactId>spring-cloud-openfeign</artifactId>
<version>2.2.7.BUILD-SNAPSHOT</version> <version>2.2.8.RELEASE</version>
</parent> </parent>
<artifactId>spring-cloud-openfeign-docs</artifactId> <artifactId>spring-cloud-openfeign-docs</artifactId>
<packaging>pom</packaging> <packaging>pom</packaging>
+5 -1
View File
@@ -1,4 +1,4 @@
image:https://circleci.com/gh/spring-cloud/spring-cloud-openfeign.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-openfeign"] image::https://github.com/spring-cloud/spring-cloud-openfeign/workflows/Build/badge.svg?branch=2.2.x&style=svg["Build",link="https://github.com/spring-cloud/spring-cloud-openfeign/actions"]
image:https://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"] image:https://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
@@ -19,3 +19,7 @@ include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/maste
== Contributing == Contributing
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[] include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[]
== License
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/master/LICENSE.txt[here].
+2
View File
@@ -14,3 +14,5 @@
:sc-ext: java :sc-ext: java
:project-full-name: Spring Cloud OpenFeign :project-full-name: Spring Cloud OpenFeign
:all: {asterisk}{asterisk} :all: {asterisk}{asterisk}
:core_path: {project-root}/spring-cloud-openfeign-core
+26 -18
View File
@@ -1,25 +1,33 @@
|=== |===
|Name | Default | Description |Name | Default | Description
|feign.autoconfiguration.jackson.enabled | `false` | If true, PageJacksonModule and SortJacksonModule bean will be provided for Jackson page decoding.
|feign.circuitbreaker.enabled | `false` | If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker.
|feign.client.config | | |feign.client.config | |
|feign.client.decode-slash | true | Feign clients do not encode slash `/` characters by default. To change this behavior, set the `decodeSlash` to `false`. |feign.client.decode-slash | `true` | Feign clients do not encode slash `/` characters by default. To change this behavior, set the `decodeSlash` to `false`.
|feign.client.default-config | default | |feign.client.default-config | `default` |
|feign.client.default-to-properties | true | |feign.client.default-to-properties | `true` |
|feign.compression.request.enabled | false | Enables the request sent by Feign to be compressed. |feign.compression.request.enabled | `false` | Enables the request sent by Feign to be compressed.
|feign.compression.request.mime-types | [text/xml, application/xml, application/json] | The list of supported mime types. |feign.compression.request.mime-types | `[text/xml, application/xml, application/json]` | The list of supported mime types.
|feign.compression.request.min-request-size | 2048 | The minimum threshold content size. |feign.compression.request.min-request-size | `2048` | The minimum threshold content size.
|feign.compression.response.enabled | false | Enables the response from Feign to be compressed. |feign.compression.response.enabled | `false` | Enables the response from Feign to be compressed.
|feign.compression.response.useGzipDecoder | false | Enables the default gzip decoder to be used. |feign.compression.response.useGzipDecoder | `false` | Enables the default gzip decoder to be used.
|feign.httpclient.connection-timeout | 2000 | |feign.encoder.charset-from-content-type | `false` | Indicates whether the charset should be derived from the {@code Content-Type} header.
|feign.httpclient.connection-timer-repeat | 3000 | |feign.httpclient.connection-timeout | `2000` |
|feign.httpclient.disable-ssl-validation | false | |feign.httpclient.connection-timer-repeat | `3000` |
|feign.httpclient.enabled | true | Enables the use of the Apache HTTP Client by Feign. |feign.httpclient.disable-ssl-validation | `false` |
|feign.httpclient.follow-redirects | true | |feign.httpclient.enabled | `true` | Enables the use of the Apache HTTP Client by Feign.
|feign.httpclient.max-connections | 200 | |feign.httpclient.follow-redirects | `true` |
|feign.httpclient.max-connections-per-route | 50 | |feign.httpclient.hc5.enabled | `false` | Enables the use of the Apache HTTP Client 5 by Feign.
|feign.httpclient.time-to-live | 900 | |feign.httpclient.hc5.pool-concurrency-policy | | Pool concurrency policies.
|feign.httpclient.hc5.pool-reuse-policy | | Pool connection re-use policies.
|feign.httpclient.hc5.socket-timeout | `5` | Default value for socket timeout.
|feign.httpclient.hc5.socket-timeout-unit | | Default value for socket timeout unit.
|feign.httpclient.max-connections | `200` |
|feign.httpclient.max-connections-per-route | `50` |
|feign.httpclient.time-to-live | `900` |
|feign.httpclient.time-to-live-unit | | |feign.httpclient.time-to-live-unit | |
|feign.hystrix.enabled | false | If true, an OpenFeign client will be wrapped with a Hystrix circuit breaker. |feign.hystrix.enabled | `false` | If true, an OpenFeign client will be wrapped with a Hystrix circuit breaker.
|feign.okhttp.enabled | false | Enables the use of the OK HTTP Client by Feign. |feign.okhttp.enabled | `false` | Enables the use of the OK HTTP Client by Feign.
|=== |===
+15
View File
@@ -24,3 +24,18 @@ public class WebApplication {
} }
``` ```
## Contributing
We welcome contributions. You can read more on how to contribute to the project https://github.com/spring-cloud/spring-cloud-openfeign/blob/master/README.adoc#3-contributing[here].
## Community Support
* You can report issues through https://github.com/spring-cloud/spring-cloud-openfeign/issues[Github].
* We monitor https://stackoverflow.com/[StackOverflow] for questions with the `spring-cloud-feign` tag.
* You can contact our team at https://gitter.im/spring-cloud/spring-cloud[Gitter].
## Commercial Support
Commercial Support is provided as part of the https://spring.io/support[VMware Spring Runtime] offering.
@@ -15,7 +15,7 @@ To use Feign create an interface and annotate it.
It has pluggable annotation support including Feign annotations and JAX-RS annotations. It has pluggable annotation support including Feign annotations and JAX-RS annotations.
Feign also supports pluggable encoders and decoders. Feign also supports pluggable encoders and decoders.
Spring Cloud adds support for Spring MVC annotations and for using the same `HttpMessageConverters` used by default in Spring Web. Spring Cloud adds support for Spring MVC annotations and for using the same `HttpMessageConverters` used by default in Spring Web.
Spring Cloud integrates Ribbon and Eureka, as well as Spring Cloud LoadBalancer to provide a load-balanced http client when using Feign. Spring Cloud integrates Ribbon and Eureka, Spring Cloud CircuitBreaker, as well as Spring Cloud LoadBalancer to provide a load-balanced http client when using Feign.
[[netflix-feign-starter]] [[netflix-feign-starter]]
=== How to Include Feign === How to Include Feign
@@ -55,11 +55,11 @@ public interface StoreClient {
} }
---- ----
In the `@FeignClient` annotation the String value ("stores" above) is an arbitrary client name, which is used to create either a https://github.com/Netflix/ribbon[Ribbon] load-balancer (see <<spring-cloud-ribbon,below for details of Ribbon support>>) or https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancer.java[Spring Cloud LoadBalancer]. In the `@FeignClient` annotation the String value ("stores" above) is an arbitrary client name, which is used to create either a https://github.com/Netflix/ribbon[Ribbon] load-balancer (see <<spring-cloud-ribbon,below for details of Ribbon support>> and <<spring-cloud-circuitbreaker,below for details of Spring Cloud CircuitBreaker support>>) or https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancer.java[Spring Cloud LoadBalancer].
You can also specify a URL using the `url` attribute You can also specify a URL using the `url` attribute
(absolute value or just a hostname). The name of the bean in the (absolute value or just a hostname). The name of the bean in the
application context is the fully qualified name of the interface. application context is the fully qualified name of the interface.
To specify your own alias value you can use the `qualifier` value To specify your own alias value you can use the `qualifiers` value
of the `@FeignClient` annotation. of the `@FeignClient` annotation.
The load-balancer client above will want to discover the physical addresses The load-balancer client above will want to discover the physical addresses
@@ -119,13 +119,14 @@ Spring Cloud OpenFeign provides the following beans by default for feign (`BeanT
* `Logger` feignLogger: `Slf4jLogger` * `Logger` feignLogger: `Slf4jLogger`
* `Contract` feignContract: `SpringMvcContract` * `Contract` feignContract: `SpringMvcContract`
* `Feign.Builder` feignBuilder: `HystrixFeign.Builder` * `Feign.Builder` feignBuilder: `HystrixFeign.Builder`
* `Feign.Builder` feignBuilder: `FeignCircuitBreaker.Builder`
* `Client` feignClient: if Ribbon is in the classpath and is enabled it is a `LoadBalancerFeignClient`, otherwise if Spring Cloud LoadBalancer is in the classpath, `FeignBlockingLoadBalancerClient` is used. * `Client` feignClient: if Ribbon is in the classpath and is enabled it is a `LoadBalancerFeignClient`, otherwise if Spring Cloud LoadBalancer is in the classpath, `FeignBlockingLoadBalancerClient` is used.
If none of them is in the classpath, the default feign client is used. If none of them is in the classpath, the default feign client is used.
NOTE: `spring-cloud-starter-openfeign` supports both `spring-cloud-starter-netflix-ribbon` and `spring-cloud-starter-loadbalancer`. However, as they are optional dependencies, you need to make sure the one you want to use has been added to your project. NOTE: `spring-cloud-starter-openfeign` supports both `spring-cloud-starter-netflix-ribbon` and `spring-cloud-starter-loadbalancer`. However, as they are optional dependencies, you need to make sure the one you want to use has been added to your project.
The OkHttpClient and ApacheHttpClient feign clients can be used by setting `feign.okhttp.enabled` or `feign.httpclient.enabled` to `true`, respectively, and having them on the classpath. The OkHttpClient and ApacheHttpClient and ApacheHC5 feign clients can be used by setting `feign.okhttp.enabled` or `feign.httpclient.enabled` or `feign.httpclient.hc5.enabled` to `true`, respectively, and having them on the classpath.
You can customize the HTTP client used by providing a bean of either `org.apache.http.impl.client.CloseableHttpClient` when using Apache or `okhttp3.OkHttpClient` when using OK HTTP. You can customize the HTTP client used by providing a bean of either `org.apache.http.impl.client.CloseableHttpClient` when using Apache or `okhttp3.OkHttpClient` when using OK HTTP or `org.apache.hc.client5.http.impl.classic.CloseableHttpClient` when using Apache HC5.
Spring Cloud OpenFeign _does not_ provide the following beans by default for feign, but still looks up beans of these types from the application context to create the feign client: Spring Cloud OpenFeign _does not_ provide the following beans by default for feign, but still looks up beans of these types from the application context to create the feign client:
@@ -276,6 +277,12 @@ public FeignClientConfigurer feignClientConfigurer() {
TIP: By default, Feign clients do not encode slash `/` characters. You can change this behaviour, by setting the value of `feign.client.decodeSlash` to `false`. TIP: By default, Feign clients do not encode slash `/` characters. You can change this behaviour, by setting the value of `feign.client.decodeSlash` to `false`.
==== `SpringEncoder` configuration
In the `SpringEncoder` that we provide, we set `null` charset for binary content types and `UTF-8` for all the other ones.
You can modify this behaviour to derive the charset from the `Content-Type` header charset instead by setting the value of `feign.encoder.charset-from-content-type` to `true`.
[[timeout-handling]] [[timeout-handling]]
=== Timeout Handling === Timeout Handling
@@ -386,7 +393,7 @@ favor for an opt-in approach.
[[spring-cloud-feign-hystrix-fallback]] [[spring-cloud-feign-hystrix-fallback]]
=== Feign Hystrix Fallbacks === Feign Hystrix Fallbacks
Hystrix supports the notion of a fallback: a default code path that is executed when they circuit is open or there is an error. To enable fallbacks for a given `@FeignClient` set the `fallback` attribute to the class name that implements the fallback. You also need to declare your implementation as a Spring bean. Hystrix supports the notion of a fallback: a default code path that is executed when the circuit is open or there is an error. To enable fallbacks for a given `@FeignClient` set the `fallback` attribute to the class name that implements the fallback. You also need to declare your implementation as a Spring bean.
[source,java,indent=0] [source,java,indent=0]
---- ----
@@ -430,6 +437,44 @@ static class HystrixClientFallbackFactory implements FallbackFactory<HystrixClie
WARNING: There is a limitation with the implementation of fallbacks in Feign and how Hystrix fallbacks work. Fallbacks are currently not supported for methods that return `com.netflix.hystrix.HystrixCommand` and `rx.Observable`. WARNING: There is a limitation with the implementation of fallbacks in Feign and how Hystrix fallbacks work. Fallbacks are currently not supported for methods that return `com.netflix.hystrix.HystrixCommand` and `rx.Observable`.
[[spring-cloud-feign-circuitbreaker]]
=== Feign Spring Cloud CircuitBreaker Support
If Spring Cloud CircuitBreaker is on the classpath and `feign.circuitbreaker.enabled=true`, Feign will wrap all methods with a circuit breaker.
To disable Spring Cloud CircuitBreaker support on a per-client basis create a vanilla `Feign.Builder` with the "prototype" scope, e.g.:
[source,java,indent=0]
----
@Configuration
public class FooConfiguration {
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder();
}
}
----
The circuit breaker name follows this pattern `<feignClientName>#<calledMethod>`. When calling a `@FeignClient` with name `foo` and the called interface method is `bar` then the circuit breaker name will be `foo_bar`.
[[spring-cloud-feign-circuitbreaker-fallback]]
=== Feign Spring Cloud CircuitBreaker Fallbacks
Spring Cloud CircuitBreaker supports the notion of a fallback: a default code path that is executed when the circuit is open or there is an error. To enable fallbacks for a given `@FeignClient` set the `fallback` attribute to the class name that implements the fallback. You also need to declare your implementation as a Spring bean.
[source,java,indent=0]
----
include::{core_path}/src/test/java/org/springframework/cloud/openfeign/circuitbreaker/CircuitBreakerTests.java[tags=client_with_fallback, indent=0]
----
If one needs access to the cause that made the fallback trigger, one can use the `fallbackFactory` attribute inside `@FeignClient`.
[source,java,indent=0]
----
include::{core_path}/src/test/java/org/springframework/cloud/openfeign/circuitbreaker/CircuitBreakerTests.java[tags=client_with_fallback_factory, indent=0]
----
=== Feign and `@Primary` === Feign and `@Primary`
When using Feign with Hystrix fallbacks, there are multiple beans in the `ApplicationContext` of the same type. This will cause `@Autowired` to not work because there isn't exactly one bean, or one marked as primary. To work around this, Spring Cloud OpenFeign marks all Feign instances as `@Primary`, so Spring Framework will know which bean to inject. In some cases, this may not be desirable. To turn off this behavior set the `primary` attribute of `@FeignClient` to false. When using Feign with Hystrix fallbacks, there are multiple beans in the `ApplicationContext` of the same type. This will cause `@Autowired` to not work because there isn't exactly one bean, or one marked as primary. To work around this, Spring Cloud OpenFeign marks all Feign instances as `@Primary`, so Spring Framework will know which bean to inject. In some cases, this may not be desirable. To turn off this behavior set the `primary` attribute of `@FeignClient` to false.
@@ -665,6 +710,14 @@ To work around this problem you can use an `ObjectProvider` when autowiring your
ObjectProvider<TestFeginClient> testFeginClient; ObjectProvider<TestFeginClient> testFeginClient;
---- ----
=== Spring Data Support
You may consider enabling Jackson Modules for the support `org.springframework.data.domain.Page` and `org.springframework.data.domain.Sort` decoding.
[source,java]
----
feign.autoconfiguration.jackson.enabled=true
----
== Configuration properties == Configuration properties
To see the list of all Sleuth related configuration properties please check link:appendix.html[the Appendix page]. To see the list of all Spring Cloud OpenFeign related configuration properties please check link:appendix.html[the Appendix page].
+4 -4
View File
@@ -4,14 +4,14 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-openfeign</artifactId> <artifactId>spring-cloud-openfeign</artifactId>
<version>2.2.7.BUILD-SNAPSHOT</version> <version>2.2.8.RELEASE</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>Spring Cloud OpenFeign</name> <name>Spring Cloud OpenFeign</name>
<description>Spring Cloud OpenFeign</description> <description>Spring Cloud OpenFeign</description>
<parent> <parent>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-build</artifactId> <artifactId>spring-cloud-build</artifactId>
<version>2.3.1.RELEASE</version> <version>2.3.4.RELEASE</version>
<relativePath/> <relativePath/>
</parent> </parent>
<scm> <scm>
@@ -26,8 +26,8 @@
<properties> <properties>
<main.basedir>${basedir}</main.basedir> <main.basedir>${basedir}</main.basedir>
<jackson.version>2.11.3</jackson.version> <jackson.version>2.11.3</jackson.version>
<spring-cloud-commons.version>2.2.7.BUILD-SNAPSHOT</spring-cloud-commons.version> <spring-cloud-commons.version>2.2.8.RELEASE</spring-cloud-commons.version>
<spring-cloud-netflix.version>2.2.7.BUILD-SNAPSHOT</spring-cloud-netflix.version> <spring-cloud-netflix.version>2.2.8.RELEASE</spring-cloud-netflix.version>
<!-- Plugin versions --> <!-- Plugin versions -->
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version> <maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
+6 -1
View File
@@ -6,7 +6,7 @@
<parent> <parent>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId> <artifactId>spring-cloud-openfeign</artifactId>
<version>2.2.7.BUILD-SNAPSHOT</version> <version>2.2.8.RELEASE</version>
<relativePath>..</relativePath> <!-- lookup parent from repository --> <relativePath>..</relativePath> <!-- lookup parent from repository -->
</parent> </parent>
<artifactId>spring-cloud-openfeign-core</artifactId> <artifactId>spring-cloud-openfeign-core</artifactId>
@@ -108,6 +108,11 @@
<artifactId>feign-slf4j</artifactId> <artifactId>feign-slf4j</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-hc5</artifactId>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>io.github.openfeign</groupId> <groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId> <artifactId>feign-httpclient</artifactId>
@@ -0,0 +1,87 @@
/*
* Copyright 2013-2020 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
*
* https://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.openfeign;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import static feign.Util.checkNotNull;
/**
* Used to control the fallback given its cause.
*
* Ex.
*
* <pre>
* {@code
* // This instance will be invoked if there are errors of any kind.
* FallbackFactory<GitHub> fallbackFactory = cause -> (owner, repo) -> {
* if (cause instanceof FeignException && ((FeignException) cause).status() == 403) {
* return Collections.emptyList();
* } else {
* return Arrays.asList("yogi");
* }
* };
*
* GitHub github = FeignCircuitBreaker.builder()
* ...
* .target(GitHub.class, "https://api.github.com", fallbackFactory);
* }
* </pre>
*
* @param <T> the feign interface type
*/
public interface FallbackFactory<T> {
/**
* Returns an instance of the fallback appropriate for the given cause.
* @param cause cause of an exception.
* @return fallback
*/
T create(Throwable cause);
final class Default<T> implements FallbackFactory<T> {
final Log logger;
final T constant;
public Default(T constant) {
this(constant, LogFactory.getLog(Default.class));
}
Default(T constant, Log logger) {
this.constant = checkNotNull(constant, "fallback");
this.logger = checkNotNull(logger, "logger");
}
@Override
public T create(Throwable cause) {
if (logger.isTraceEnabled()) {
logger.trace("fallback due to: " + cause.getMessage(), cause);
}
return constant;
}
@Override
public String toString() {
return constant.toString();
}
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -25,8 +25,10 @@ import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy; import javax.annotation.PreDestroy;
import com.fasterxml.jackson.databind.Module;
import feign.Client; import feign.Client;
import feign.Feign; import feign.Feign;
import feign.hc5.ApacheHttp5Client;
import feign.httpclient.ApacheHttpClient; import feign.httpclient.ApacheHttpClient;
import feign.okhttp.OkHttpClient; import feign.okhttp.OkHttpClient;
import okhttp3.ConnectionPool; import okhttp3.ConnectionPool;
@@ -39,30 +41,45 @@ import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.AllNestedConditions;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.actuator.HasFeatures; import org.springframework.cloud.client.actuator.HasFeatures;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory; import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory;
import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory; import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory;
import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory; import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory;
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory; import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
import org.springframework.cloud.openfeign.support.DefaultGzipDecoderConfiguration; import org.springframework.cloud.openfeign.support.DefaultGzipDecoderConfiguration;
import org.springframework.cloud.openfeign.support.FeignEncoderProperties;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties; import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.cloud.openfeign.support.PageJacksonModule;
import org.springframework.cloud.openfeign.support.SortJacksonModule;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
* @author Julien Roy * @author Julien Roy
* @author Grzegorz Poznachowski
* @author Nikita Konev
* @author Tim Peeters
* @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Feign.class) @ConditionalOnClass(Feign.class)
@EnableConfigurationProperties({ FeignClientProperties.class, @EnableConfigurationProperties({ FeignClientProperties.class,
FeignHttpClientProperties.class }) FeignHttpClientProperties.class, FeignEncoderProperties.class })
@Import(DefaultGzipDecoderConfiguration.class) @Import(DefaultGzipDecoderConfiguration.class)
public class FeignAutoConfiguration { public class FeignAutoConfiguration {
@@ -84,7 +101,42 @@ public class FeignAutoConfiguration {
} }
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Module.class, Page.class, Sort.class })
@ConditionalOnProperty(value = "feign.autoconfiguration.jackson.enabled",
havingValue = "true")
protected static class FeignJacksonConfiguration {
@Bean
@ConditionalOnMissingBean(PageJacksonModule.class)
public PageJacksonModule pageJacksonModule() {
return new PageJacksonModule();
}
@Bean
@ConditionalOnMissingBean(SortJacksonModule.class)
public SortJacksonModule sortModule() {
return new SortJacksonModule();
}
}
@Configuration(proxyBeanMethods = false)
@Conditional(DefaultFeignTargeterConditions.class)
protected static class DefaultFeignTargeterConfiguration {
@Bean
@ConditionalOnMissingBean
public Targeter feignTargeter() {
return new DefaultTargeter();
}
}
@Configuration(proxyBeanMethods = false)
@Conditional(FeignCircuitBreakerDisabledConditions.class)
@ConditionalOnClass(name = "feign.hystrix.HystrixFeign") @ConditionalOnClass(name = "feign.hystrix.HystrixFeign")
@ConditionalOnProperty(value = "feign.hystrix.enabled", havingValue = "true",
matchIfMissing = true)
protected static class HystrixFeignTargeterConfiguration { protected static class HystrixFeignTargeterConfiguration {
@Bean @Bean
@@ -96,13 +148,16 @@ public class FeignAutoConfiguration {
} }
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnMissingClass("feign.hystrix.HystrixFeign") @ConditionalOnClass(CircuitBreaker.class)
protected static class DefaultFeignTargeterConfiguration { @ConditionalOnProperty(value = "feign.circuitbreaker.enabled", havingValue = "true")
protected static class CircuitBreakerPresentFeignTargeterConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public Targeter feignTargeter() { @ConditionalOnBean(CircuitBreakerFactory.class)
return new DefaultTargeter(); public Targeter circuitBreakerFeignTargeter(
CircuitBreakerFactory circuitBreakerFactory) {
return new FeignCircuitBreakerTargeter(circuitBreakerFactory);
} }
} }
@@ -116,6 +171,7 @@ public class FeignAutoConfiguration {
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer") @ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
@ConditionalOnMissingBean(CloseableHttpClient.class) @ConditionalOnMissingBean(CloseableHttpClient.class)
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true) @ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
@Conditional(HttpClient5DisabledConditions.class)
protected static class HttpClientFeignConfiguration { protected static class HttpClientFeignConfiguration {
private final Timer connectionManagerTimer = new Timer( private final Timer connectionManagerTimer = new Timer(
@@ -234,4 +290,39 @@ public class FeignAutoConfiguration {
} }
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttp5Client.class)
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
@ConditionalOnMissingBean(org.apache.hc.client5.http.impl.classic.CloseableHttpClient.class)
@ConditionalOnProperty(value = "feign.httpclient.hc5.enabled", havingValue = "true")
@Import(org.springframework.cloud.openfeign.clientconfig.HttpClient5FeignConfiguration.class)
protected static class HttpClient5FeignConfiguration {
@Bean
@ConditionalOnMissingBean(Client.class)
public Client feignClient(
org.apache.hc.client5.http.impl.classic.CloseableHttpClient httpClient5) {
return new ApacheHttp5Client(httpClient5);
}
}
static class DefaultFeignTargeterConditions extends AllNestedConditions {
DefaultFeignTargeterConditions() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@Conditional(FeignCircuitBreakerDisabledConditions.class)
static class FeignCircuitBreakerDisabled {
}
@Conditional(HystrixDisabledConditions.class)
static class HystrixDisabled {
}
}
} }
@@ -0,0 +1,89 @@
/*
* Copyright 2013-2020 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
*
* https://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.openfeign;
import feign.Feign;
import feign.Target;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
/**
* Allows Feign interfaces to work with {@link CircuitBreaker}.
*
* @author Marcin Grzejszczak
* @since 3.0.0
*/
public final class FeignCircuitBreaker {
private FeignCircuitBreaker() {
throw new IllegalStateException("Don't instantiate a utility class");
}
/**
* @return builder for Feign CircuitBreaker integration
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for Feign CircuitBreaker integration.
*/
public static final class Builder extends Feign.Builder {
private CircuitBreakerFactory circuitBreakerFactory;
private String feignClientName;
Builder circuitBreakerFactory(CircuitBreakerFactory circuitBreakerFactory) {
this.circuitBreakerFactory = circuitBreakerFactory;
return this;
}
Builder feignClientName(String feignClientName) {
this.feignClientName = feignClientName;
return this;
}
public <T> T target(Target<T> target, T fallback) {
return build(
fallback != null ? new FallbackFactory.Default<T>(fallback) : null)
.newInstance(target);
}
public <T> T target(Target<T> target,
FallbackFactory<? extends T> fallbackFactory) {
return build(fallbackFactory).newInstance(target);
}
@Override
public <T> T target(Target<T> target) {
return build(null).newInstance(target);
}
public Feign build(final FallbackFactory<?> nullableFallbackFactory) {
super.invocationHandlerFactory(
(target, dispatch) -> new FeignCircuitBreakerInvocationHandler(
circuitBreakerFactory, target, dispatch,
nullableFallbackFactory));
return super.build();
}
}
}
@@ -0,0 +1,40 @@
/*
* Copyright 2013-2020 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
*
* https://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.openfeign;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
class FeignCircuitBreakerDisabledConditions extends AnyNestedCondition {
FeignCircuitBreakerDisabledConditions() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnMissingClass("org.springframework.cloud.client.circuitbreaker.CircuitBreaker")
static class CircuitBreakerClassMissing {
}
@ConditionalOnProperty(value = "feign.circuitbreaker.enabled", havingValue = "false",
matchIfMissing = true)
static class CircuitBreakerDisabled {
}
}
@@ -0,0 +1,149 @@
/*
* Copyright 2013-2020 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
*
* https://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.openfeign;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import feign.Feign;
import feign.InvocationHandlerFactory;
import feign.Target;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import static feign.Util.checkNotNull;
class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
private final CircuitBreakerFactory factory;
private final Target<?> target;
private final Map<Method, InvocationHandlerFactory.MethodHandler> dispatch;
private final FallbackFactory<?> nullableFallbackFactory;
private final Map<Method, Method> fallbackMethodMap;
FeignCircuitBreakerInvocationHandler(CircuitBreakerFactory factory, Target<?> target,
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch,
FallbackFactory<?> nullableFallbackFactory) {
this.factory = factory;
this.target = checkNotNull(target, "target");
this.dispatch = checkNotNull(dispatch, "dispatch");
this.fallbackMethodMap = toFallbackMethod(dispatch);
this.nullableFallbackFactory = nullableFallbackFactory;
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args)
throws Throwable {
// early exit if the invoked method is from java.lang.Object
// code is the same as ReflectiveFeign.FeignInvocationHandler
if ("equals".equals(method.getName())) {
try {
Object otherHandler = args.length > 0 && args[0] != null
? Proxy.getInvocationHandler(args[0]) : null;
return equals(otherHandler);
}
catch (IllegalArgumentException e) {
return false;
}
}
else if ("hashCode".equals(method.getName())) {
return hashCode();
}
else if ("toString".equals(method.getName())) {
return toString();
}
String circuitName = Feign.configKey(target.type(), method);
CircuitBreaker circuitBreaker = this.factory.create(circuitName);
Supplier<Object> supplier = asSupplier(method, args);
if (this.nullableFallbackFactory != null) {
Function<Throwable, Object> fallbackFunction = throwable -> {
Object fallback = this.nullableFallbackFactory.create(throwable);
try {
return this.fallbackMethodMap.get(method).invoke(fallback, args);
}
catch (Exception e) {
throw new IllegalStateException(e);
}
};
return circuitBreaker.run(supplier, fallbackFunction);
}
return circuitBreaker.run(supplier);
}
private Supplier<Object> asSupplier(final Method method, final Object[] args) {
return () -> {
try {
return this.dispatch.get(method).invoke(args);
}
catch (RuntimeException throwable) {
throw throwable;
}
catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
};
}
/**
* If the method param of InvocationHandler.invoke is not accessible, i.e in a
* package-private interface, the fallback call will cause of access restrictions. But
* methods in dispatch are copied methods. So setting access to dispatch method
* doesn't take effect to the method in InvocationHandler.invoke. Use map to store a
* copy of method to invoke the fallback to bypass this and reducing the count of
* reflection calls.
* @return cached methods map for fallback invoking
*/
static Map<Method, Method> toFallbackMethod(
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch) {
Map<Method, Method> result = new LinkedHashMap<Method, Method>();
for (Method method : dispatch.keySet()) {
method.setAccessible(true);
result.put(method, method);
}
return result;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof FeignCircuitBreakerInvocationHandler) {
FeignCircuitBreakerInvocationHandler other = (FeignCircuitBreakerInvocationHandler) obj;
return this.target.equals(other.target);
}
return false;
}
@Override
public int hashCode() {
return this.target.hashCode();
}
@Override
public String toString() {
return this.target.toString();
}
}
@@ -0,0 +1,97 @@
/*
* Copyright 2013-2020 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
*
* https://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.openfeign;
import feign.Feign;
import feign.Target;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.util.StringUtils;
@SuppressWarnings("unchecked")
class FeignCircuitBreakerTargeter implements Targeter {
private final CircuitBreakerFactory circuitBreakerFactory;
FeignCircuitBreakerTargeter(CircuitBreakerFactory circuitBreakerFactory) {
this.circuitBreakerFactory = circuitBreakerFactory;
}
@Override
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign,
FeignContext context, Target.HardCodedTarget<T> target) {
if (!(feign instanceof FeignCircuitBreaker.Builder)) {
return feign.target(target);
}
FeignCircuitBreaker.Builder builder = (FeignCircuitBreaker.Builder) feign;
String name = !StringUtils.hasText(factory.getContextId()) ? factory.getName()
: factory.getContextId();
Class<?> fallback = factory.getFallback();
if (fallback != void.class) {
return targetWithFallback(name, context, target, builder, fallback);
}
Class<?> fallbackFactory = factory.getFallbackFactory();
if (fallbackFactory != void.class) {
return targetWithFallbackFactory(name, context, target, builder,
fallbackFactory);
}
return builder(name, builder).target(target);
}
private <T> T targetWithFallbackFactory(String feignClientName, FeignContext context,
Target.HardCodedTarget<T> target, FeignCircuitBreaker.Builder builder,
Class<?> fallbackFactoryClass) {
FallbackFactory<? extends T> fallbackFactory = (FallbackFactory<? extends T>) getFromContext(
"fallbackFactory", feignClientName, context, fallbackFactoryClass,
FallbackFactory.class);
return builder(feignClientName, builder).target(target, fallbackFactory);
}
private <T> T targetWithFallback(String feignClientName, FeignContext context,
Target.HardCodedTarget<T> target, FeignCircuitBreaker.Builder builder,
Class<?> fallback) {
T fallbackInstance = getFromContext("fallback", feignClientName, context,
fallback, target.type());
return builder(feignClientName, builder).target(target, fallbackInstance);
}
private <T> T getFromContext(String fallbackMechanism, String feignClientName,
FeignContext context, Class<?> beanType, Class<T> targetType) {
Object fallbackInstance = context.getInstance(feignClientName, beanType);
if (fallbackInstance == null) {
throw new IllegalStateException(String.format(
"No " + fallbackMechanism
+ " instance of type %s found for feign client %s",
beanType, feignClientName));
}
if (!targetType.isAssignableFrom(beanType)) {
throw new IllegalStateException(String.format("Incompatible "
+ fallbackMechanism
+ " instance. Fallback/fallbackFactory of type %s is not assignable to %s for feign client %s",
beanType, targetType, feignClientName));
}
return (T) fallbackInstance;
}
private FeignCircuitBreaker.Builder builder(String feignClientName,
FeignCircuitBreaker.Builder builder) {
return builder.circuitBreakerFactory(this.circuitBreakerFactory)
.feignClientName(feignClientName);
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -33,6 +33,7 @@ import org.springframework.core.annotation.AliasFor;
* *
* @author Spencer Gibb * @author Spencer Gibb
* @author Venil Noronha * @author Venil Noronha
* @author Olga Maciaszek-Sharma
*/ */
@Target(ElementType.TYPE) @Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@@ -73,9 +74,28 @@ public @interface FeignClient {
/** /**
* @return the <code>@Qualifier</code> value for the feign client. * @return the <code>@Qualifier</code> value for the feign client.
* @deprecated in favour of {@link #qualifiers()}.
*
* If both {@link #qualifier()} and {@link #qualifiers()} are present, we will use the
* latter, unless the array returned by {@link #qualifiers()} is empty or only
* contains <code>null</code> or whitespace values, in which case we'll fall back
* first to {@link #qualifier()} and, if that's also not present, to the default =
* <code>contextId + "FeignClient"</code>.
*/ */
@Deprecated
String qualifier() default ""; String qualifier() default "";
/**
* @return the <code>@Qualifiers</code> value for the feign client.
*
* If both {@link #qualifier()} and {@link #qualifiers()} are present, we will use the
* latter, unless the array returned by {@link #qualifiers()} is empty or only
* contains <code>null</code> or whitespace values, in which case we'll fall back
* first to {@link #qualifier()} and, if that's also not present, to the default =
* <code>contextId + "FeignClient"</code>.
*/
String[] qualifiers() default {};
/** /**
* @return an absolute URL or resolvable hostname (the protocol is optional). * @return an absolute URL or resolvable hostname (the protocol is optional).
*/ */
@@ -109,6 +129,7 @@ public @interface FeignClient {
* annotated by {@link FeignClient}. The fallback factory must be a valid spring bean. * annotated by {@link FeignClient}. The fallback factory must be a valid spring bean.
* *
* @see feign.hystrix.FallbackFactory for details. * @see feign.hystrix.FallbackFactory for details.
* @see FallbackFactory for details.
* @return fallback factory for the specified Feign client interface * @return fallback factory for the specified Feign client interface
*/ */
Class<?> fallbackFactory() default void.class; Class<?> fallbackFactory() default void.class;
@@ -16,6 +16,7 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import feign.Feign;
import feign.hystrix.FallbackFactory; import feign.hystrix.FallbackFactory;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
@@ -28,6 +29,7 @@ import org.springframework.context.ApplicationContext;
* *
* @author Sven Döring * @author Sven Döring
* @author Matt King * @author Matt King
* @author Sam Kruglov
*/ */
public class FeignClientBuilder { public class FeignClientBuilder {
@@ -69,6 +71,18 @@ public class FeignClientBuilder {
return this; return this;
} }
/**
* Applies a {@link FeignBuilderCustomizer} to the underlying
* {@link Feign.Builder}. May be called multiple times.
* @param customizer applied in the same order as supplied here after applying
* customizers found in the context.
* @return the {@link Builder} with the customizer added
*/
public Builder<T> customize(final FeignBuilderCustomizer customizer) {
this.feignClientFactoryBean.addCustomizer(customizer);
return this;
}
public Builder<T> contextId(final String contextId) { public Builder<T> contextId(final String contextId) {
this.feignClientFactoryBean.setContextId(contextId); this.feignClientFactoryBean.setContextId(contextId);
return this; return this;
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -35,14 +35,19 @@ import feign.Target.HardCodedTarget;
import feign.codec.Decoder; import feign.codec.Decoder;
import feign.codec.Encoder; import feign.codec.Encoder;
import feign.codec.ErrorDecoder; import feign.codec.ErrorDecoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer; import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer;
import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient; import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient;
import org.springframework.cloud.openfeign.loadbalancer.RetryableFeignBlockingLoadBalancerClient;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient; import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
@@ -58,15 +63,19 @@ import org.springframework.util.StringUtils;
* @author Matt King * @author Matt King
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Ilia Ilinykh * @author Ilia Ilinykh
* @author Marcin Grzejszczak
* @author Sam Kruglov
*/ */
class FeignClientFactoryBean public class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean,
implements FactoryBean<Object>, InitializingBean, ApplicationContextAware { ApplicationContextAware, BeanFactoryAware {
/*********************************** /***********************************
* WARNING! Nothing in this class should be @Autowired. It causes NPEs because of some * WARNING! Nothing in this class should be @Autowired. It causes NPEs because of some
* lifecycle race condition. * lifecycle race condition.
***********************************/ ***********************************/
private static Log LOG = LogFactory.getLog(FeignClientFactoryBean.class);
private Class<?> type; private Class<?> type;
private String name; private String name;
@@ -83,6 +92,8 @@ class FeignClientFactoryBean
private ApplicationContext applicationContext; private ApplicationContext applicationContext;
private BeanFactory beanFactory;
private Class<?> fallback = void.class; private Class<?> fallback = void.class;
private Class<?> fallbackFactory = void.class; private Class<?> fallbackFactory = void.class;
@@ -91,6 +102,10 @@ class FeignClientFactoryBean
private int connectTimeoutMillis = new Request.Options().connectTimeoutMillis(); private int connectTimeoutMillis = new Request.Options().connectTimeoutMillis();
private boolean followRedirects = new Request.Options().isFollowRedirects();
private List<FeignBuilderCustomizer> additionalCustomizers = new ArrayList<>();
@Override @Override
public void afterPropertiesSet() { public void afterPropertiesSet() {
Assert.hasText(contextId, "Context id must be set"); Assert.hasText(contextId, "Context id must be set");
@@ -126,11 +141,13 @@ class FeignClientFactoryBean
.forEach(feignBuilderCustomizer -> feignBuilderCustomizer .forEach(feignBuilderCustomizer -> feignBuilderCustomizer
.customize(builder)); .customize(builder));
} }
additionalCustomizers.forEach(customizer -> customizer.customize(builder));
} }
protected void configureFeign(FeignContext context, Feign.Builder builder) { protected void configureFeign(FeignContext context, Feign.Builder builder) {
FeignClientProperties properties = applicationContext FeignClientProperties properties = beanFactory != null
.getBean(FeignClientProperties.class); ? beanFactory.getBean(FeignClientProperties.class)
: applicationContext.getBean(FeignClientProperties.class);
FeignClientConfigurer feignClientConfigurer = getOptional(context, FeignClientConfigurer feignClientConfigurer = getOptional(context,
FeignClientConfigurer.class); FeignClientConfigurer.class);
@@ -186,6 +203,7 @@ class FeignClientFactoryBean
builder.options(options); builder.options(options);
readTimeoutMillis = options.readTimeoutMillis(); readTimeoutMillis = options.readTimeoutMillis();
connectTimeoutMillis = options.connectTimeoutMillis(); connectTimeoutMillis = options.connectTimeoutMillis();
followRedirects = options.isFollowRedirects();
} }
Map<String, RequestInterceptor> requestInterceptors = getInheritedAwareInstances( Map<String, RequestInterceptor> requestInterceptors = getInheritedAwareInstances(
context, RequestInterceptor.class); context, RequestInterceptor.class);
@@ -225,9 +243,11 @@ class FeignClientFactoryBean
? config.getConnectTimeout() : connectTimeoutMillis; ? config.getConnectTimeout() : connectTimeoutMillis;
readTimeoutMillis = config.getReadTimeout() != null ? config.getReadTimeout() readTimeoutMillis = config.getReadTimeout() != null ? config.getReadTimeout()
: readTimeoutMillis; : readTimeoutMillis;
followRedirects = config.isFollowRedirects() != null ? config.isFollowRedirects()
: followRedirects;
builder.options(new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS, builder.options(new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS,
readTimeoutMillis, TimeUnit.MILLISECONDS, true)); readTimeoutMillis, TimeUnit.MILLISECONDS, followRedirects));
if (config.getRetryer() != null) { if (config.getRetryer() != null) {
Retryer retryer = getOrInstantiate(config.getRetryer()); Retryer retryer = getOrInstantiate(config.getRetryer());
@@ -283,7 +303,8 @@ class FeignClientFactoryBean
private <T> T getOrInstantiate(Class<T> tClass) { private <T> T getOrInstantiate(Class<T> tClass) {
try { try {
return applicationContext.getBean(tClass); return beanFactory != null ? beanFactory.getBean(tClass)
: applicationContext.getBean(tClass);
} }
catch (NoSuchBeanDefinitionException e) { catch (NoSuchBeanDefinitionException e) {
return BeanUtils.instantiateClass(tClass); return BeanUtils.instantiateClass(tClass);
@@ -332,11 +353,11 @@ class FeignClientFactoryBean
} }
throw new IllegalStateException( throw new IllegalStateException(
"No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-netflix-ribbon?"); "No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-netflix-ribbon or spring-cloud-starter-loadbalancer?");
} }
@Override @Override
public Object getObject() throws Exception { public Object getObject() {
return getTarget(); return getTarget();
} }
@@ -346,10 +367,19 @@ class FeignClientFactoryBean
* information * information
*/ */
<T> T getTarget() { <T> T getTarget() {
FeignContext context = applicationContext.getBean(FeignContext.class); FeignContext context = beanFactory != null
? beanFactory.getBean(FeignContext.class)
: applicationContext.getBean(FeignContext.class);
Feign.Builder builder = feign(context); Feign.Builder builder = feign(context);
if (!StringUtils.hasText(url)) { if (!StringUtils.hasText(url)) {
if (url != null && LOG.isWarnEnabled()) {
LOG.warn(
"The provided URL is empty. Will try picking an instance via load-balancing.");
}
else if (LOG.isDebugEnabled()) {
LOG.debug("URL not provided. Will use LoadBalancer.");
}
if (!name.startsWith("http")) { if (!name.startsWith("http")) {
url = "http://" + name; url = "http://" + name;
} }
@@ -376,6 +406,12 @@ class FeignClientFactoryBean
// but Spring Cloud LoadBalancer is on the classpath, so unwrap // but Spring Cloud LoadBalancer is on the classpath, so unwrap
client = ((FeignBlockingLoadBalancerClient) client).getDelegate(); client = ((FeignBlockingLoadBalancerClient) client).getDelegate();
} }
if (client instanceof RetryableFeignBlockingLoadBalancerClient) {
// not load balancing because we have a url,
// but Spring Cloud LoadBalancer is on the classpath, so unwrap
client = ((RetryableFeignBlockingLoadBalancerClient) client)
.getDelegate();
}
builder.client(client); builder.client(client);
} }
Targeter targeter = get(context, Targeter.class); Targeter targeter = get(context, Targeter.class);
@@ -462,13 +498,18 @@ class FeignClientFactoryBean
this.inheritParentContext = inheritParentContext; this.inheritParentContext = inheritParentContext;
} }
public void addCustomizer(FeignBuilderCustomizer customizer) {
additionalCustomizers.add(customizer);
}
public ApplicationContext getApplicationContext() { public ApplicationContext getApplicationContext() {
return applicationContext; return applicationContext;
} }
@Override @Override
public void setApplicationContext(ApplicationContext context) throws BeansException { public void setApplicationContext(ApplicationContext context) throws BeansException {
this.applicationContext = context; applicationContext = context;
beanFactory = context;
} }
public Class<?> getFallback() { public Class<?> getFallback() {
@@ -497,18 +538,23 @@ class FeignClientFactoryBean
} }
FeignClientFactoryBean that = (FeignClientFactoryBean) o; FeignClientFactoryBean that = (FeignClientFactoryBean) o;
return Objects.equals(applicationContext, that.applicationContext) return Objects.equals(applicationContext, that.applicationContext)
&& Objects.equals(beanFactory, that.beanFactory)
&& decode404 == that.decode404 && decode404 == that.decode404
&& inheritParentContext == that.inheritParentContext && inheritParentContext == that.inheritParentContext
&& Objects.equals(fallback, that.fallback) && Objects.equals(fallback, that.fallback)
&& Objects.equals(fallbackFactory, that.fallbackFactory) && Objects.equals(fallbackFactory, that.fallbackFactory)
&& Objects.equals(name, that.name) && Objects.equals(path, that.path) && Objects.equals(name, that.name) && Objects.equals(path, that.path)
&& Objects.equals(type, that.type) && Objects.equals(url, that.url); && Objects.equals(type, that.type) && Objects.equals(url, that.url)
&& Objects.equals(connectTimeoutMillis, that.connectTimeoutMillis)
&& Objects.equals(readTimeoutMillis, that.readTimeoutMillis)
&& Objects.equals(followRedirects, that.followRedirects);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(applicationContext, decode404, inheritParentContext, fallback, return Objects.hash(applicationContext, beanFactory, decode404,
fallbackFactory, name, path, type, url); inheritParentContext, fallback, fallbackFactory, name, path, type, url,
readTimeoutMillis, connectTimeoutMillis, followRedirects);
} }
@Override @Override
@@ -519,9 +565,18 @@ class FeignClientFactoryBean
.append("decode404=").append(decode404).append(", ") .append("decode404=").append(decode404).append(", ")
.append("inheritParentContext=").append(inheritParentContext).append(", ") .append("inheritParentContext=").append(inheritParentContext).append(", ")
.append("applicationContext=").append(applicationContext).append(", ") .append("applicationContext=").append(applicationContext).append(", ")
.append("beanFactory=").append(beanFactory).append(", ")
.append("fallback=").append(fallback).append(", ") .append("fallback=").append(fallback).append(", ")
.append("fallbackFactory=").append(fallbackFactory).append("}") .append("fallbackFactory=").append(fallbackFactory).append("}")
.append("connectTimeoutMillis=").append(connectTimeoutMillis).append("}")
.append("readTimeoutMillis=").append(readTimeoutMillis).append("}")
.append("followRedirects=").append(followRedirects).append("}")
.toString(); .toString();
} }
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -37,6 +37,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
* @author Eko Kurniawan Khannedy * @author Eko Kurniawan Khannedy
* @author Ilia Ilinykh * @author Ilia Ilinykh
* @author Ram Anaswara * @author Ram Anaswara
* @author Olga Maciaszek-Sharma
*/ */
@ConfigurationProperties("feign.client") @ConfigurationProperties("feign.client")
public class FeignClientProperties { public class FeignClientProperties {
@@ -136,6 +137,8 @@ public class FeignClientProperties {
private ExceptionPropagationPolicy exceptionPropagationPolicy; private ExceptionPropagationPolicy exceptionPropagationPolicy;
private Boolean followRedirects;
public Logger.Level getLoggerLevel() { public Logger.Level getLoggerLevel() {
return loggerLevel; return loggerLevel;
} }
@@ -244,6 +247,14 @@ public class FeignClientProperties {
this.exceptionPropagationPolicy = exceptionPropagationPolicy; this.exceptionPropagationPolicy = exceptionPropagationPolicy;
} }
public Boolean isFollowRedirects() {
return followRedirects;
}
public void setFollowRedirects(Boolean followRedirects) {
this.followRedirects = followRedirects;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o) {
@@ -266,8 +277,8 @@ public class FeignClientProperties {
&& Objects.equals(exceptionPropagationPolicy, && Objects.equals(exceptionPropagationPolicy,
that.exceptionPropagationPolicy) that.exceptionPropagationPolicy)
&& Objects.equals(defaultRequestHeaders, that.defaultRequestHeaders) && Objects.equals(defaultRequestHeaders, that.defaultRequestHeaders)
&& Objects.equals(defaultQueryParameters, && Objects.equals(defaultQueryParameters, that.defaultQueryParameters)
that.defaultQueryParameters); && Objects.equals(followRedirects, that.followRedirects);
} }
@Override @Override
@@ -275,7 +286,7 @@ public class FeignClientProperties {
return Objects.hash(loggerLevel, connectTimeout, readTimeout, retryer, return Objects.hash(loggerLevel, connectTimeout, readTimeout, retryer,
errorDecoder, requestInterceptors, decode404, encoder, decoder, errorDecoder, requestInterceptors, decode404, encoder, decoder,
contract, exceptionPropagationPolicy, defaultQueryParameters, contract, exceptionPropagationPolicy, defaultQueryParameters,
defaultRequestHeaders); defaultRequestHeaders, followRedirects);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -19,11 +19,11 @@ package org.springframework.cloud.openfeign;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.fasterxml.jackson.databind.Module;
import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommand;
import feign.Contract; import feign.Contract;
import feign.Feign; import feign.Feign;
import feign.Logger; import feign.Logger;
import feign.QueryMapEncoder;
import feign.Retryer; import feign.Retryer;
import feign.codec.Decoder; import feign.codec.Decoder;
import feign.codec.Encoder; import feign.codec.Encoder;
@@ -35,18 +35,21 @@ import feign.optionals.OptionalDecoder;
import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties; import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer; import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer;
import org.springframework.cloud.openfeign.support.AbstractFormWriter; import org.springframework.cloud.openfeign.support.AbstractFormWriter;
import org.springframework.cloud.openfeign.support.PageJacksonModule; import org.springframework.cloud.openfeign.support.FeignEncoderProperties;
import org.springframework.cloud.openfeign.support.PageableSpringEncoder; import org.springframework.cloud.openfeign.support.PageableSpringEncoder;
import org.springframework.cloud.openfeign.support.PageableSpringQueryMapEncoder;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SortJacksonModule;
import org.springframework.cloud.openfeign.support.SpringDecoder; import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder; import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.cloud.openfeign.support.SpringMvcContract; import org.springframework.cloud.openfeign.support.SpringMvcContract;
@@ -63,6 +66,8 @@ import static feign.form.ContentType.MULTIPART;
* @author Dave Syer * @author Dave Syer
* @author Venil Noronha * @author Venil Noronha
* @author Darren Foong * @author Darren Foong
* @author Olga Maciaszek-Sharma
* @author Hyeonmin Park
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
public class FeignClientsConfiguration { public class FeignClientsConfiguration {
@@ -85,6 +90,9 @@ public class FeignClientsConfiguration {
@Autowired(required = false) @Autowired(required = false)
private FeignClientProperties feignClientProperties; private FeignClientProperties feignClientProperties;
@Autowired(required = false)
private FeignEncoderProperties encoderProperties;
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public Decoder feignDecoder() { public Decoder feignDecoder() {
@@ -96,7 +104,7 @@ public class FeignClientsConfiguration {
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnMissingClass("org.springframework.data.domain.Pageable") @ConditionalOnMissingClass("org.springframework.data.domain.Pageable")
public Encoder feignEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider) { public Encoder feignEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider) {
return springEncoder(formWriterProvider); return springEncoder(formWriterProvider, encoderProperties);
} }
@Bean @Bean
@@ -105,7 +113,7 @@ public class FeignClientsConfiguration {
public Encoder feignEncoderPageable( public Encoder feignEncoderPageable(
ObjectProvider<AbstractFormWriter> formWriterProvider) { ObjectProvider<AbstractFormWriter> formWriterProvider) {
PageableSpringEncoder encoder = new PageableSpringEncoder( PageableSpringEncoder encoder = new PageableSpringEncoder(
springEncoder(formWriterProvider)); springEncoder(formWriterProvider, encoderProperties));
if (springDataWebProperties != null) { if (springDataWebProperties != null) {
encoder.setPageParameter( encoder.setPageParameter(
@@ -118,6 +126,13 @@ public class FeignClientsConfiguration {
return encoder; return encoder;
} }
@Bean
@ConditionalOnClass(name = "org.springframework.data.domain.Pageable")
@ConditionalOnMissingBean
public QueryMapEncoder feignQueryMapEncoderPageable() {
return new PageableSpringQueryMapEncoder();
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public Contract feignContract(ConversionService feignConversionService) { public Contract feignContract(ConversionService feignConversionService) {
@@ -155,18 +170,6 @@ public class FeignClientsConfiguration {
return new DefaultFeignLoggerFactory(this.logger); return new DefaultFeignLoggerFactory(this.logger);
} }
@Bean
@ConditionalOnClass(name = "org.springframework.data.domain.Page")
public Module pageJacksonModule() {
return new PageJacksonModule();
}
@Bean
@ConditionalOnClass(name = "org.springframework.data.domain.Page")
public Module sortModule() {
return new SortJacksonModule();
}
@Bean @Bean
@ConditionalOnMissingBean(FeignClientConfigurer.class) @ConditionalOnMissingBean(FeignClientConfigurer.class)
public FeignClientConfigurer feignClientConfigurer() { public FeignClientConfigurer feignClientConfigurer() {
@@ -174,15 +177,17 @@ public class FeignClientsConfiguration {
}; };
} }
private Encoder springEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider) { private Encoder springEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider,
FeignEncoderProperties encoderProperties) {
AbstractFormWriter formWriter = formWriterProvider.getIfAvailable(); AbstractFormWriter formWriter = formWriterProvider.getIfAvailable();
if (formWriter != null) { if (formWriter != null) {
return new SpringEncoder(new SpringPojoFormEncoder(formWriter), return new SpringEncoder(new SpringPojoFormEncoder(formWriter),
this.messageConverters); this.messageConverters, encoderProperties);
} }
else { else {
return new SpringEncoder(new SpringFormEncoder(), this.messageConverters); return new SpringEncoder(new SpringFormEncoder(), this.messageConverters,
encoderProperties);
} }
} }
@@ -212,4 +217,26 @@ public class FeignClientsConfiguration {
} }
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(CircuitBreaker.class)
@ConditionalOnProperty("feign.circuitbreaker.enabled")
protected static class CircuitBreakerPresentFeignBuilderConfiguration {
@Bean
@Scope("prototype")
@ConditionalOnMissingBean({ Feign.Builder.class, CircuitBreakerFactory.class })
public Feign.Builder defaultFeignBuilder(Retryer retryer) {
return Feign.builder().retryer(retryer);
}
@Bean
@Scope("prototype")
@ConditionalOnMissingBean
@ConditionalOnBean(CircuitBreakerFactory.class)
public Feign.Builder circuitBreakerFeignBuilder() {
return FeignCircuitBreaker.builder();
}
}
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -20,8 +20,12 @@ import java.net.MalformedURLException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@@ -30,6 +34,9 @@ import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition; import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.beans.factory.config.BeanExpressionResolver;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
@@ -45,6 +52,7 @@ import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
@@ -53,6 +61,8 @@ import org.springframework.util.StringUtils;
* @author Venil Noronha * @author Venil Noronha
* @author Gang Li * @author Gang Li
* @author Michal Domagala * @author Michal Domagala
* @author Marcin Grzejszczak
* @author Olga Maciaszek-Sharma
*/ */
class FeignClientsRegistrar class FeignClientsRegistrar
implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware { implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
@@ -164,8 +174,6 @@ class FeignClientsRegistrar
LinkedHashSet<BeanDefinition> candidateComponents = new LinkedHashSet<>(); LinkedHashSet<BeanDefinition> candidateComponents = new LinkedHashSet<>();
Map<String, Object> attrs = metadata Map<String, Object> attrs = metadata
.getAnnotationAttributes(EnableFeignClients.class.getName()); .getAnnotationAttributes(EnableFeignClients.class.getName());
AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
FeignClient.class);
final Class<?>[] clients = attrs == null ? null final Class<?>[] clients = attrs == null ? null
: (Class<?>[]) attrs.get("clients"); : (Class<?>[]) attrs.get("clients");
if (clients == null || clients.length == 0) { if (clients == null || clients.length == 0) {
@@ -206,37 +214,57 @@ class FeignClientsRegistrar
private void registerFeignClient(BeanDefinitionRegistry registry, private void registerFeignClient(BeanDefinitionRegistry registry,
AnnotationMetadata annotationMetadata, Map<String, Object> attributes) { AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
String className = annotationMetadata.getClassName(); String className = annotationMetadata.getClassName();
BeanDefinitionBuilder definition = BeanDefinitionBuilder Class clazz = ClassUtils.resolveClassName(className, null);
.genericBeanDefinition(FeignClientFactoryBean.class); ConfigurableBeanFactory beanFactory = registry instanceof ConfigurableBeanFactory
validate(attributes); ? (ConfigurableBeanFactory) registry : null;
definition.addPropertyValue("url", getUrl(attributes)); String contextId = getContextId(beanFactory, attributes);
definition.addPropertyValue("path", getPath(attributes));
String name = getName(attributes); String name = getName(attributes);
definition.addPropertyValue("name", name); FeignClientFactoryBean factoryBean = new FeignClientFactoryBean();
String contextId = getContextId(attributes); factoryBean.setBeanFactory(beanFactory);
definition.addPropertyValue("contextId", contextId); factoryBean.setName(name);
definition.addPropertyValue("type", className); factoryBean.setContextId(contextId);
definition.addPropertyValue("decode404", attributes.get("decode404")); factoryBean.setType(clazz);
definition.addPropertyValue("fallback", attributes.get("fallback")); BeanDefinitionBuilder definition = BeanDefinitionBuilder
definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory")); .genericBeanDefinition(clazz, () -> {
factoryBean.setUrl(getUrl(beanFactory, attributes));
factoryBean.setPath(getPath(beanFactory, attributes));
factoryBean.setDecode404(Boolean
.parseBoolean(String.valueOf(attributes.get("decode404"))));
Object fallback = attributes.get("fallback");
if (fallback != null) {
factoryBean.setFallback(fallback instanceof Class
? (Class<?>) fallback
: ClassUtils.resolveClassName(fallback.toString(), null));
}
Object fallbackFactory = attributes.get("fallbackFactory");
if (fallbackFactory != null) {
factoryBean.setFallbackFactory(fallbackFactory instanceof Class
? (Class<?>) fallbackFactory
: ClassUtils.resolveClassName(fallbackFactory.toString(),
null));
}
return factoryBean.getObject();
});
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
definition.setLazyInit(true);
validate(attributes);
String alias = contextId + "FeignClient";
AbstractBeanDefinition beanDefinition = definition.getBeanDefinition(); AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
beanDefinition.setAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE, className); beanDefinition.setAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE, className);
beanDefinition.setAttribute("feignClientsRegistrarFactoryBean", factoryBean);
// has a default, won't be null // has a default, won't be null
boolean primary = (Boolean) attributes.get("primary"); boolean primary = (Boolean) attributes.get("primary");
beanDefinition.setPrimary(primary); beanDefinition.setPrimary(primary);
String qualifier = getQualifier(attributes); String[] qualifiers = getQualifiers(attributes);
if (StringUtils.hasText(qualifier)) { if (ObjectUtils.isEmpty(qualifiers)) {
alias = qualifier; qualifiers = new String[] { contextId + "FeignClient" };
} }
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
new String[] { alias }); qualifiers);
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry); BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
} }
@@ -249,6 +277,10 @@ class FeignClientsRegistrar
} }
/* for testing */ String getName(Map<String, Object> attributes) { /* for testing */ String getName(Map<String, Object> attributes) {
return getName(null, attributes);
}
String getName(ConfigurableBeanFactory beanFactory, Map<String, Object> attributes) {
String name = (String) attributes.get("serviceId"); String name = (String) attributes.get("serviceId");
if (!StringUtils.hasText(name)) { if (!StringUtils.hasText(name)) {
name = (String) attributes.get("name"); name = (String) attributes.get("name");
@@ -256,34 +288,46 @@ class FeignClientsRegistrar
if (!StringUtils.hasText(name)) { if (!StringUtils.hasText(name)) {
name = (String) attributes.get("value"); name = (String) attributes.get("value");
} }
name = resolve(name); name = resolve(beanFactory, name);
return getName(name); return getName(name);
} }
private String getContextId(Map<String, Object> attributes) { private String getContextId(ConfigurableBeanFactory beanFactory,
Map<String, Object> attributes) {
String contextId = (String) attributes.get("contextId"); String contextId = (String) attributes.get("contextId");
if (!StringUtils.hasText(contextId)) { if (!StringUtils.hasText(contextId)) {
return getName(attributes); return getName(attributes);
} }
contextId = resolve(contextId); contextId = resolve(beanFactory, contextId);
return getName(contextId); return getName(contextId);
} }
private String resolve(String value) { private String resolve(ConfigurableBeanFactory beanFactory, String value) {
if (StringUtils.hasText(value)) { if (StringUtils.hasText(value)) {
return this.environment.resolvePlaceholders(value); if (beanFactory == null) {
return this.environment.resolvePlaceholders(value);
}
BeanExpressionResolver resolver = beanFactory.getBeanExpressionResolver();
String resolved = beanFactory.resolveEmbeddedValue(value);
if (resolver == null) {
return resolved;
}
return String.valueOf(resolver.evaluate(resolved,
new BeanExpressionContext(beanFactory, null)));
} }
return value; return value;
} }
private String getUrl(Map<String, Object> attributes) { private String getUrl(ConfigurableBeanFactory beanFactory,
String url = resolve((String) attributes.get("url")); Map<String, Object> attributes) {
String url = resolve(beanFactory, (String) attributes.get("url"));
return getUrl(url); return getUrl(url);
} }
private String getPath(Map<String, Object> attributes) { private String getPath(ConfigurableBeanFactory beanFactory,
String path = resolve((String) attributes.get("path")); Map<String, Object> attributes) {
String path = resolve(beanFactory, (String) attributes.get("path"));
return getPath(path); return getPath(path);
} }
@@ -340,6 +384,19 @@ class FeignClientsRegistrar
return null; return null;
} }
private String[] getQualifiers(Map<String, Object> client) {
if (client == null) {
return null;
}
List<String> qualifierList = new ArrayList<>(
Arrays.asList((String[]) client.get("qualifiers")));
qualifierList.removeIf(qualifier -> !StringUtils.hasText(qualifier));
if (qualifierList.isEmpty() && getQualifier(client) != null) {
qualifierList = Collections.singletonList(getQualifier(client));
}
return !qualifierList.isEmpty() ? qualifierList.toArray(new String[0]) : null;
}
private String getClientName(Map<String, Object> client) { private String getClientName(Map<String, Object> client) {
if (client == null) { if (client == null) {
return null; return null;
@@ -0,0 +1,43 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
/**
* @author Nguyen Ky Thanh
*/
public class HttpClient5DisabledConditions extends AnyNestedCondition {
public HttpClient5DisabledConditions() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnMissingClass("feign.hc5.ApacheHttp5Client")
static class ApacheHttp5ClientClassMissing {
}
@ConditionalOnProperty(value = "feign.httpclient.hc5.enabled", havingValue = "false",
matchIfMissing = true)
static class HttpClient5Disabled {
}
}
@@ -0,0 +1,42 @@
/*
* Copyright 2013-2020 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
*
* https://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.openfeign;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
/**
* @author Tim Peeters
*/
class HystrixDisabledConditions extends AnyNestedCondition {
HystrixDisabledConditions() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnMissingClass("feign.hystrix.HystrixFeign")
static class HystrixFeignClassMissing {
}
@ConditionalOnProperty(value = "feign.hystrix.enabled", havingValue = "false")
static class HystrixFeignDisabled {
}
}
@@ -0,0 +1,162 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign.clientconfig;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.socket.LayeredConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
import org.apache.hc.core5.http.io.SocketConfig;
import org.apache.hc.core5.http.ssl.TLS;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.pool.PoolConcurrencyPolicy;
import org.apache.hc.core5.pool.PoolReusePolicy;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Default configuration for {@link CloseableHttpClient}.
*
* @author Nguyen Ky Thanh
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(CloseableHttpClient.class)
public class HttpClient5FeignConfiguration {
private static final Log LOG = LogFactory.getLog(HttpClient5FeignConfiguration.class);
private CloseableHttpClient httpClient5;
@Bean
@ConditionalOnMissingBean(HttpClientConnectionManager.class)
public HttpClientConnectionManager hc5ConnectionManager(
FeignHttpClientProperties httpClientProperties) {
return PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(httpsSSLConnectionSocketFactory(
httpClientProperties.isDisableSslValidation()))
.setMaxConnTotal(httpClientProperties.getMaxConnections())
.setMaxConnPerRoute(httpClientProperties.getMaxConnectionsPerRoute())
.setConnPoolPolicy(PoolReusePolicy.valueOf(
httpClientProperties.getHc5().getPoolReusePolicy().name()))
.setPoolConcurrencyPolicy(PoolConcurrencyPolicy.valueOf(
httpClientProperties.getHc5().getPoolConcurrencyPolicy().name()))
.setConnectionTimeToLive(
TimeValue.of(httpClientProperties.getTimeToLive(),
httpClientProperties.getTimeToLiveUnit()))
.setDefaultSocketConfig(SocketConfig.custom()
.setSoTimeout(Timeout.of(
httpClientProperties.getHc5().getSocketTimeout(),
httpClientProperties.getHc5().getSocketTimeoutUnit()))
.build())
.build();
}
@Bean
public CloseableHttpClient httpClient5(HttpClientConnectionManager connectionManager,
FeignHttpClientProperties httpClientProperties) {
httpClient5 = HttpClients.custom().disableCookieManagement().useSystemProperties()
.setConnectionManager(connectionManager).evictExpiredConnections()
.setDefaultRequestConfig(
RequestConfig.custom()
.setConnectTimeout(Timeout.of(
httpClientProperties.getConnectionTimeout(),
TimeUnit.MILLISECONDS))
.setRedirectsEnabled(
httpClientProperties.isFollowRedirects())
.build())
.build();
return httpClient5;
}
@PreDestroy
public void destroy() {
if (httpClient5 != null) {
httpClient5.close(CloseMode.GRACEFUL);
}
}
private LayeredConnectionSocketFactory httpsSSLConnectionSocketFactory(
boolean isDisableSslValidation) {
final SSLConnectionSocketFactoryBuilder sslConnectionSocketFactoryBuilder = SSLConnectionSocketFactoryBuilder
.create().setTlsVersions(TLS.V_1_3, TLS.V_1_2);
if (isDisableSslValidation) {
try {
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null,
new TrustManager[] { new DisabledValidationTrustManager() },
new SecureRandom());
sslConnectionSocketFactoryBuilder.setSslContext(sslContext);
}
catch (NoSuchAlgorithmException e) {
LOG.warn("Error creating SSLContext", e);
}
catch (KeyManagementException e) {
LOG.warn("Error creating SSLContext", e);
}
}
else {
sslConnectionSocketFactoryBuilder
.setSslContext(SSLContexts.createSystemDefault());
}
return sslConnectionSocketFactoryBuilder.build();
}
static class DisabledValidationTrustManager implements X509TrustManager {
DisabledValidationTrustManager() {
}
public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -38,6 +38,7 @@ import org.springframework.context.annotation.Import;
* <code>spring.cloud.loadbalancer.ribbon.enabled</code> to <code>true</code>. * <code>spring.cloud.loadbalancer.ribbon.enabled</code> to <code>true</code>.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh
* @since 2.2.0 * @since 2.2.0
*/ */
@ConditionalOnClass(Feign.class) @ConditionalOnClass(Feign.class)
@@ -51,6 +52,7 @@ import org.springframework.context.annotation.Import;
// https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653 // https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653
@Import({ HttpClientFeignLoadBalancerConfiguration.class, @Import({ HttpClientFeignLoadBalancerConfiguration.class,
OkHttpFeignLoadBalancerConfiguration.class, OkHttpFeignLoadBalancerConfiguration.class,
HttpClient5FeignLoadBalancerConfiguration.class,
DefaultFeignLoadBalancerConfiguration.class }) DefaultFeignLoadBalancerConfiguration.class })
public class FeignLoadBalancerAutoConfiguration { public class FeignLoadBalancerAutoConfiguration {
@@ -0,0 +1,75 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign.loadbalancer;
import java.util.List;
import feign.Client;
import feign.hc5.ApacheHttp5Client;
import org.apache.hc.client5.http.classic.HttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.cloud.openfeign.clientconfig.HttpClient5FeignConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
/**
* Configuration instantiating a {@link BlockingLoadBalancerClient}-based {@link Client}
* object that uses {@link ApacheHttp5Client} under the hood.
*
* @author Nguyen Ky Thanh
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttp5Client.class)
@ConditionalOnBean(BlockingLoadBalancerClient.class)
@ConditionalOnProperty(value = "feign.httpclient.hc5.enabled", havingValue = "true")
@Import(HttpClient5FeignConfiguration.class)
class HttpClient5FeignLoadBalancerConfiguration {
@Bean
@ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(BlockingLoadBalancerClient loadBalancerClient,
HttpClient httpClient5) {
Client delegate = new ApacheHttp5Client(httpClient5);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
@ConditionalOnBean(LoadBalancedRetryFactory.class)
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled",
havingValue = "true", matchIfMissing = true)
public Client feignRetryClient(BlockingLoadBalancerClient loadBalancerClient,
HttpClient httpClient5,
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) {
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories);
Client delegate = new ApacheHttp5Client(httpClient5);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient,
loadBalancedRetryFactories.get(0));
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -28,6 +28,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient; import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.cloud.openfeign.HttpClient5DisabledConditions;
import org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration; import org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Conditional;
@@ -40,12 +41,14 @@ import org.springframework.core.annotation.AnnotationAwareOrderComparator;
* object that uses {@link ApacheHttpClient} under the hood. * object that uses {@link ApacheHttpClient} under the hood.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh
* @since 2.2.0 * @since 2.2.0
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttpClient.class) @ConditionalOnClass(ApacheHttpClient.class)
@ConditionalOnBean(BlockingLoadBalancerClient.class) @ConditionalOnBean(BlockingLoadBalancerClient.class)
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true) @ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
@Conditional(HttpClient5DisabledConditions.class)
@Import(HttpClientFeignConfiguration.class) @Import(HttpClientFeignConfiguration.class)
class HttpClientFeignLoadBalancerConfiguration { class HttpClientFeignLoadBalancerConfiguration {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -24,6 +24,7 @@ import java.util.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.netflix.client.AbstractLoadBalancerAwareClient; import com.netflix.client.AbstractLoadBalancerAwareClient;
import com.netflix.client.ClientRequest; import com.netflix.client.ClientRequest;
@@ -65,16 +66,19 @@ public class FeignLoadBalancer extends
protected ServerIntrospector serverIntrospector; protected ServerIntrospector serverIntrospector;
protected boolean followRedirects;
public FeignLoadBalancer(ILoadBalancer lb, IClientConfig clientConfig, public FeignLoadBalancer(ILoadBalancer lb, IClientConfig clientConfig,
ServerIntrospector serverIntrospector) { ServerIntrospector serverIntrospector) {
super(lb, clientConfig); super(lb, clientConfig);
this.setRetryHandler(RetryHandler.DEFAULT); setRetryHandler(RetryHandler.DEFAULT);
this.clientConfig = clientConfig; this.clientConfig = clientConfig;
this.ribbon = RibbonProperties.from(clientConfig); this.ribbon = RibbonProperties.from(clientConfig);
RibbonProperties ribbon = this.ribbon; RibbonProperties ribbon = this.ribbon;
this.connectTimeout = ribbon.getConnectTimeout(); connectTimeout = ribbon.getConnectTimeout();
this.readTimeout = ribbon.getReadTimeout(); readTimeout = ribbon.getReadTimeout();
this.serverIntrospector = serverIntrospector; this.serverIntrospector = serverIntrospector;
followRedirects = ribbon.isFollowRedirects();
} }
@Override @Override
@@ -83,11 +87,13 @@ public class FeignLoadBalancer extends
Request.Options options; Request.Options options;
if (configOverride != null) { if (configOverride != null) {
RibbonProperties override = RibbonProperties.from(configOverride); RibbonProperties override = RibbonProperties.from(configOverride);
options = new Request.Options(override.connectTimeout(this.connectTimeout), options = new Request.Options(override.connectTimeout(connectTimeout),
override.readTimeout(this.readTimeout)); TimeUnit.MILLISECONDS, override.readTimeout(readTimeout),
TimeUnit.MILLISECONDS, override.isFollowRedirects(followRedirects));
} }
else { else {
options = new Request.Options(this.connectTimeout, this.readTimeout); options = new Request.Options(connectTimeout, TimeUnit.MILLISECONDS,
readTimeout, TimeUnit.MILLISECONDS, followRedirects);
} }
Response response = request.client().execute(request.toRequest(), options); Response response = request.client().execute(request.toRequest(), options);
return new RibbonResponse(request.getUri(), response); return new RibbonResponse(request.getUri(), response);
@@ -96,24 +102,24 @@ public class FeignLoadBalancer extends
@Override @Override
public RequestSpecificRetryHandler getRequestSpecificRetryHandler( public RequestSpecificRetryHandler getRequestSpecificRetryHandler(
RibbonRequest request, IClientConfig requestConfig) { RibbonRequest request, IClientConfig requestConfig) {
if (this.ribbon.isOkToRetryOnAllOperations()) { if (ribbon.isOkToRetryOnAllOperations()) {
return new RequestSpecificRetryHandler(true, true, this.getRetryHandler(), return new RequestSpecificRetryHandler(true, true, getRetryHandler(),
requestConfig); requestConfig);
} }
if (!request.toRequest().httpMethod().name().equals("GET")) { if (!request.toRequest().httpMethod().name().equals("GET")) {
return new RequestSpecificRetryHandler(true, false, this.getRetryHandler(), return new RequestSpecificRetryHandler(true, false, getRetryHandler(),
requestConfig); requestConfig);
} }
else { else {
return new RequestSpecificRetryHandler(true, true, this.getRetryHandler(), return new RequestSpecificRetryHandler(true, true, getRetryHandler(),
requestConfig); requestConfig);
} }
} }
@Override @Override
public URI reconstructURIWithServer(Server server, URI original) { public URI reconstructURIWithServer(Server server, URI original) {
URI uri = updateToSecureConnectionIfNeeded(original, this.clientConfig, URI uri = updateToSecureConnectionIfNeeded(original, clientConfig,
this.serverIntrospector, server); serverIntrospector, server);
return super.reconstructURIWithServer(server, uri); return super.reconstructURIWithServer(server, uri);
} }
@@ -137,11 +143,11 @@ public class FeignLoadBalancer extends
} }
Request toRequest() { Request toRequest() {
return toRequest(this.request); return toRequest(request);
} }
Client client() { Client client() {
return this.client; return client;
} }
HttpRequest toHttpRequest() { HttpRequest toHttpRequest() {
@@ -179,16 +185,16 @@ public class FeignLoadBalancer extends
} }
public Request getRequest() { public Request getRequest() {
return this.request; return request;
} }
public Client getClient() { public Client getClient() {
return this.client; return client;
} }
@Override @Override
public Object clone() { public Object clone() {
return new RibbonRequest(this.client, this.request, getUri()); return new RibbonRequest(client, request, getUri());
} }
} }
@@ -206,37 +212,37 @@ public class FeignLoadBalancer extends
@Override @Override
public Object getPayload() { public Object getPayload() {
return this.response.body(); return response.body();
} }
@Override @Override
public boolean hasPayload() { public boolean hasPayload() {
return this.response.body() != null; return response.body() != null;
} }
@Override @Override
public boolean isSuccess() { public boolean isSuccess() {
return this.response.status() == 200; return response.status() == 200;
} }
@Override @Override
public URI getRequestedURI() { public URI getRequestedURI() {
return this.uri; return uri;
} }
@Override @Override
public Map<String, Collection<String>> getHeaders() { public Map<String, Collection<String>> getHeaders() {
return this.response.headers(); return response.headers();
} }
Response toResponse() { Response toResponse() {
return this.response; return response;
} }
@Override @Override
public void close() throws IOException { public void close() throws IOException {
if (this.response != null && this.response.body() != null) { if (response != null && response.body() != null) {
this.response.body().close(); response.body().close();
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -41,6 +41,7 @@ import org.springframework.context.annotation.Primary;
* *
* @author Dave Syer * @author Dave Syer
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh
*/ */
@ConditionalOnClass({ ILoadBalancer.class, Feign.class }) @ConditionalOnClass({ ILoadBalancer.class, Feign.class })
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.ribbon.enabled", @ConditionalOnProperty(value = "spring.cloud.loadbalancer.ribbon.enabled",
@@ -53,6 +54,7 @@ import org.springframework.context.annotation.Primary;
// https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653 // https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653
@Import({ HttpClientFeignLoadBalancedConfiguration.class, @Import({ HttpClientFeignLoadBalancedConfiguration.class,
OkHttpFeignLoadBalancedConfiguration.class, OkHttpFeignLoadBalancedConfiguration.class,
HttpClient5FeignLoadBalancedConfiguration.class,
DefaultFeignLoadBalancedConfiguration.class }) DefaultFeignLoadBalancedConfiguration.class })
public class FeignRibbonClientAutoConfiguration { public class FeignRibbonClientAutoConfiguration {
@@ -0,0 +1,52 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign.ribbon;
import feign.Client;
import feign.hc5.ApacheHttp5Client;
import org.apache.hc.client5.http.classic.HttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.openfeign.clientconfig.HttpClient5FeignConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Configuration instantiating a {@link LoadBalancerFeignClient}-based {@link Client}
* object that uses {@link ApacheHttp5Client} under the hood.
*
* @author Nguyen Ky Thanh
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttp5Client.class)
@ConditionalOnProperty(value = "feign.httpclient.hc5.enabled", havingValue = "true")
@Import(HttpClient5FeignConfiguration.class)
class HttpClient5FeignLoadBalancedConfiguration {
@Bean
@ConditionalOnMissingBean(Client.class)
public Client feignClient(CachingSpringLoadBalancerFactory cachingFactory,
SpringClientFactory clientFactory, HttpClient httpClient5) {
Client delegate = new ApacheHttp5Client(httpClient5);
return new LoadBalancerFeignClient(delegate, cachingFactory, clientFactory);
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -24,18 +24,22 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.openfeign.HttpClient5DisabledConditions;
import org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration; import org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttpClient.class) @ConditionalOnClass(ApacheHttpClient.class)
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true) @ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
@Conditional(HttpClient5DisabledConditions.class)
@Import(HttpClientFeignConfiguration.class) @Import(HttpClientFeignConfiguration.class)
class HttpClientFeignLoadBalancedConfiguration { class HttpClientFeignLoadBalancedConfiguration {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -31,6 +31,7 @@ import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
/** /**
* @author Dave Syer * @author Dave Syer
* @author Olga Maciaszek-Sharma
* *
*/ */
public class LoadBalancerFeignClient implements Client { public class LoadBalancerFeignClient implements Client {
@@ -126,6 +127,8 @@ public class LoadBalancerFeignClient implements Client {
setProperty(CommonClientConfigKey.ConnectTimeout, setProperty(CommonClientConfigKey.ConnectTimeout,
options.connectTimeoutMillis()); options.connectTimeoutMillis());
setProperty(CommonClientConfigKey.ReadTimeout, options.readTimeoutMillis()); setProperty(CommonClientConfigKey.ReadTimeout, options.readTimeoutMillis());
setProperty(CommonClientConfigKey.FollowRedirects,
options.isFollowRedirects());
} }
@Override @Override
@@ -0,0 +1,44 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign.support;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Properties for {@link SpringEncoder}.
*
* @author Olga Maciaszek-Sharma
* @since 2.2.8
*/
@ConfigurationProperties("feign.encoder")
public class FeignEncoderProperties {
/**
* Indicates whether the charset should be derived from the {@code Content-Type}
* header.
*/
private boolean charsetFromContentType = false;
public boolean isCharsetFromContentType() {
return charsetFromContentType;
}
public void setCharsetFromContentType(boolean charsetFromContentType) {
this.charsetFromContentType = charsetFromContentType;
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -22,6 +22,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
/** /**
* @author Ryan Baxter * @author Ryan Baxter
* @author Nguyen Ky Thanh
*/ */
@ConfigurationProperties(prefix = "feign.httpclient") @ConfigurationProperties(prefix = "feign.httpclient")
public class FeignHttpClientProperties { public class FeignHttpClientProperties {
@@ -82,6 +83,11 @@ public class FeignHttpClientProperties {
private int connectionTimerRepeat = DEFAULT_CONNECTION_TIMER_REPEAT; private int connectionTimerRepeat = DEFAULT_CONNECTION_TIMER_REPEAT;
/**
* Apache HttpClient5 additional properties.
*/
private Hc5Properties hc5 = new Hc5Properties();
public int getConnectionTimerRepeat() { public int getConnectionTimerRepeat() {
return this.connectionTimerRepeat; return this.connectionTimerRepeat;
} }
@@ -146,4 +152,125 @@ public class FeignHttpClientProperties {
this.connectionTimeout = connectionTimeout; this.connectionTimeout = connectionTimeout;
} }
public Hc5Properties getHc5() {
return hc5;
}
public void setHc5(Hc5Properties hc5) {
this.hc5 = hc5;
}
public static class Hc5Properties {
/**
* Default value for pool concurrency policy.
*/
public static final PoolConcurrencyPolicy DEFAULT_POOL_CONCURRENCY_POLICY = PoolConcurrencyPolicy.STRICT;
/**
* Default value for pool reuse policy.
*/
public static final PoolReusePolicy DEFAULT_POOL_REUSE_POLICY = PoolReusePolicy.FIFO;
/**
* Default value for socket timeout.
*/
public static final int DEFAULT_SOCKET_TIMEOUT = 5;
/**
* Default value for socket timeout unit.
*/
public static final TimeUnit DEFAULT_SOCKET_TIMEOUT_UNIT = TimeUnit.SECONDS;
/**
* Pool concurrency policies.
*/
private PoolConcurrencyPolicy poolConcurrencyPolicy = DEFAULT_POOL_CONCURRENCY_POLICY;
/**
* Pool connection re-use policies.
*/
private PoolReusePolicy poolReusePolicy = DEFAULT_POOL_REUSE_POLICY;
/**
* Default value for socket timeout.
*/
private int socketTimeout = DEFAULT_SOCKET_TIMEOUT;
/**
* Default value for socket timeout unit.
*/
private TimeUnit socketTimeoutUnit = DEFAULT_SOCKET_TIMEOUT_UNIT;
public PoolConcurrencyPolicy getPoolConcurrencyPolicy() {
return this.poolConcurrencyPolicy;
}
public void setPoolConcurrencyPolicy(
PoolConcurrencyPolicy poolConcurrencyPolicy) {
this.poolConcurrencyPolicy = poolConcurrencyPolicy;
}
public PoolReusePolicy getPoolReusePolicy() {
return poolReusePolicy;
}
public void setPoolReusePolicy(PoolReusePolicy poolReusePolicy) {
this.poolReusePolicy = poolReusePolicy;
}
public TimeUnit getSocketTimeoutUnit() {
return socketTimeoutUnit;
}
public void setSocketTimeoutUnit(TimeUnit socketTimeoutUnit) {
this.socketTimeoutUnit = socketTimeoutUnit;
}
public int getSocketTimeout() {
return socketTimeout;
}
public void setSocketTimeout(int socketTimeout) {
this.socketTimeout = socketTimeout;
}
/**
* Enumeration of pool concurrency policies.
*/
public enum PoolConcurrencyPolicy {
/**
* Higher concurrency but with lax connection max limit guarantees.
*/
LAX,
/**
* Strict connection max limit guarantees.
*/
STRICT
}
/**
* Enumeration of pooled connection re-use policies.
*/
public enum PoolReusePolicy {
/**
* Re-use as few connections as possible making it possible for connections to
* become idle and expire.
*/
LIFO,
/**
* Re-use all connections equally preventing them from becoming idle and
* expiring.
*/
FIFO
}
}
} }
@@ -20,6 +20,7 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.function.Function; import java.util.function.Function;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.core.Version;
@@ -36,6 +37,7 @@ import org.springframework.data.domain.Sort;
* This Jackson module provides support to deserialize Spring {@link Page} objects. * This Jackson module provides support to deserialize Spring {@link Page} objects.
* *
* @author Pascal Büttiker * @author Pascal Büttiker
* @author Olga Maciaszek-Sharma
*/ */
public class PageJacksonModule extends Module { public class PageJacksonModule extends Module {
@@ -65,7 +67,9 @@ public class PageJacksonModule extends Module {
SimplePageImpl(@JsonProperty("content") List<T> content, SimplePageImpl(@JsonProperty("content") List<T> content,
@JsonProperty("number") int number, @JsonProperty("size") int size, @JsonProperty("number") int number, @JsonProperty("size") int size,
@JsonProperty("totalElements") long totalElements, @JsonProperty("totalElements") @JsonAlias({ "total-elements",
"total_elements", "totalelements",
"TotalElements" }) long totalElements,
@JsonProperty("sort") Sort sort) { @JsonProperty("sort") Sort sort) {
PageRequest pageRequest; PageRequest pageRequest;
if (sort != null) { if (sort != null) {
@@ -120,7 +120,7 @@ public class PageableSpringEncoder implements Encoder {
} }
} }
for (Sort.Order order : sort) { for (Sort.Order order : sort) {
sortQueries.add(order.getProperty() + "," + order.getDirection()); sortQueries.add(order.getProperty() + "%2C" + order.getDirection());
} }
if (!sortQueries.isEmpty()) { if (!sortQueries.isEmpty()) {
template.query(sortParameter, sortQueries); template.query(sortParameter, sortQueries);
@@ -0,0 +1,80 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign.support;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import feign.querymap.BeanQueryMapEncoder;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
/**
* Provides support for encoding Pageable annotated as
* {@link org.springframework.cloud.openfeign.SpringQueryMap}.
*
* @author Hyeonmin Park
* @since 2.2.8
*/
public class PageableSpringQueryMapEncoder extends BeanQueryMapEncoder {
@Override
public Map<String, Object> encode(Object object) {
if (supports(object)) {
Map<String, Object> queryMap = new HashMap<>();
if (object instanceof Pageable) {
Pageable pageable = (Pageable) object;
if (pageable.isPaged()) {
queryMap.put("page", pageable.getPageNumber());
queryMap.put("size", pageable.getPageSize());
}
if (pageable.getSort() != null) {
applySort(queryMap, pageable.getSort());
}
}
else if (object instanceof Sort) {
Sort sort = (Sort) object;
applySort(queryMap, sort);
}
return queryMap;
}
else {
return super.encode(object);
}
}
private void applySort(Map<String, Object> queryMap, Sort sort) {
List<String> sortQueries = new ArrayList<>();
for (Sort.Order order : sort) {
sortQueries.add(order.getProperty() + "%2C" + order.getDirection());
}
if (!sortQueries.isEmpty()) {
queryMap.put("sort", sortQueries);
}
}
protected boolean supports(Object object) {
return object instanceof Pageable || object instanceof Sort;
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -26,16 +26,16 @@ import feign.Response;
import feign.codec.Decoder; import feign.codec.Decoder;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/** /**
* Decoder adds compatibility for Spring MVC's ResponseEntity to any other decoder via * Decoder adds compatibility for Spring MVC's ResponseEntity to any other decoder via
* composition. * composition.
* *
* @author chad jaros * @author chad jaros
* @author Olga Maciaszek-Sharma
*/ */
public class ResponseEntityDecoder implements Decoder { public class ResponseEntityDecoder implements Decoder {
@@ -81,7 +81,7 @@ public class ResponseEntityDecoder implements Decoder {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T> ResponseEntity<T> createResponse(Object instance, Response response) { private <T> ResponseEntity<T> createResponse(Object instance, Response response) {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); HttpHeaders headers = new HttpHeaders();
for (String key : response.headers().keySet()) { for (String key : response.headers().keySet()) {
headers.put(key, new LinkedList<>(response.headers().get(key))); headers.put(key, new LinkedList<>(response.headers().get(key)));
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -22,10 +22,10 @@ import java.io.OutputStream;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Objects; import java.util.stream.Stream;
import feign.Request;
import feign.RequestTemplate; import feign.RequestTemplate;
import feign.codec.EncodeException; import feign.codec.EncodeException;
import feign.codec.Encoder; import feign.codec.Encoder;
@@ -55,7 +55,9 @@ import static org.springframework.cloud.openfeign.support.FeignUtils.getHttpHead
* @author Ahmad Mozafarnia * @author Ahmad Mozafarnia
* @author Aaron Whiteside * @author Aaron Whiteside
* @author Darren Foong * @author Darren Foong
* @author Olga Maciaszek-Sharma
*/ */
@SuppressWarnings("rawtypes")
public class SpringEncoder implements Encoder { public class SpringEncoder implements Encoder {
private static final Log log = LogFactory.getLog(SpringEncoder.class); private static final Log log = LogFactory.getLog(SpringEncoder.class);
@@ -64,15 +66,23 @@ public class SpringEncoder implements Encoder {
private final ObjectFactory<HttpMessageConverters> messageConverters; private final ObjectFactory<HttpMessageConverters> messageConverters;
private final FeignEncoderProperties encoderProperties;
public SpringEncoder(ObjectFactory<HttpMessageConverters> messageConverters) { public SpringEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
this.springFormEncoder = new SpringFormEncoder(); this(new SpringFormEncoder(), messageConverters);
this.messageConverters = messageConverters;
} }
public SpringEncoder(SpringFormEncoder springFormEncoder, public SpringEncoder(SpringFormEncoder springFormEncoder,
ObjectFactory<HttpMessageConverters> messageConverters) { ObjectFactory<HttpMessageConverters> messageConverters) {
this(springFormEncoder, messageConverters, new FeignEncoderProperties());
}
public SpringEncoder(SpringFormEncoder springFormEncoder,
ObjectFactory<HttpMessageConverters> messageConverters,
FeignEncoderProperties encoderProperties) {
this.springFormEncoder = springFormEncoder; this.springFormEncoder = springFormEncoder;
this.messageConverters = messageConverters; this.messageConverters = messageConverters;
this.encoderProperties = encoderProperties;
} }
@Override @Override
@@ -89,7 +99,7 @@ public class SpringEncoder implements Encoder {
requestContentType = MediaType.valueOf(type); requestContentType = MediaType.valueOf(type);
} }
if (Objects.equals(requestContentType, MediaType.MULTIPART_FORM_DATA)) { if (isMultipartType(requestContentType)) {
this.springFormEncoder.encode(requestBody, bodyType, request); this.springFormEncoder.encode(requestBody, bodyType, request);
return; return;
} }
@@ -100,58 +110,76 @@ public class SpringEncoder implements Encoder {
+ "should be specified as MediaType.MULTIPART_FORM_DATA_VALUE"); + "should be specified as MediaType.MULTIPART_FORM_DATA_VALUE");
} }
} }
encodeWithMessageConverter(requestBody, bodyType, request,
for (HttpMessageConverter messageConverter : this.messageConverters requestContentType);
.getObject().getConverters()) {
FeignOutputMessage outputMessage;
try {
if (messageConverter instanceof GenericHttpMessageConverter) {
outputMessage = checkAndWrite(requestBody, bodyType,
requestContentType,
(GenericHttpMessageConverter) messageConverter, request);
}
else {
outputMessage = checkAndWrite(requestBody, requestContentType,
messageConverter, request);
}
}
catch (IOException | HttpMessageConversionException ex) {
throw new EncodeException("Error converting request body", ex);
}
if (outputMessage != null) {
// clear headers
request.headers(null);
// converters can modify headers, so update the request
// with the modified headers
request.headers(getHeaders(outputMessage.getHeaders()));
// do not use charset for binary data and protobuf
Charset charset;
if (messageConverter instanceof ByteArrayHttpMessageConverter) {
charset = null;
}
else if (messageConverter instanceof ProtobufHttpMessageConverter
&& ProtobufHttpMessageConverter.PROTOBUF.isCompatibleWith(
outputMessage.getHeaders().getContentType())) {
charset = null;
}
else {
charset = StandardCharsets.UTF_8;
}
request.body(Request.Body.encoded(
outputMessage.getOutputStream().toByteArray(), charset));
return;
}
}
String message = "Could not write request: no suitable HttpMessageConverter "
+ "found for request type [" + requestBody.getClass().getName() + "]";
if (requestContentType != null) {
message += " and content type [" + requestContentType + "]";
}
throw new EncodeException(message);
} }
} }
private void encodeWithMessageConverter(Object requestBody, Type bodyType,
RequestTemplate request, MediaType requestContentType) {
for (HttpMessageConverter messageConverter : this.messageConverters.getObject()
.getConverters()) {
FeignOutputMessage outputMessage;
try {
if (messageConverter instanceof GenericHttpMessageConverter) {
outputMessage = checkAndWrite(requestBody, bodyType,
requestContentType,
(GenericHttpMessageConverter) messageConverter, request);
}
else {
outputMessage = checkAndWrite(requestBody, requestContentType,
messageConverter, request);
}
}
catch (IOException | HttpMessageConversionException ex) {
throw new EncodeException("Error converting request body", ex);
}
if (outputMessage != null) {
// clear headers
request.headers(null);
// converters can modify headers, so update the request
// with the modified headers
request.headers(getHeaders(outputMessage.getHeaders()));
// do not use charset for binary data and protobuf
Charset charset;
MediaType contentType = outputMessage.getHeaders().getContentType();
Charset charsetFromContentType = contentType != null
? contentType.getCharset() : null;
if (encoderProperties != null
&& encoderProperties.isCharsetFromContentType()
&& charsetFromContentType != null) {
charset = charsetFromContentType;
}
else if (shouldHaveNullCharset(messageConverter, outputMessage)) {
charset = null;
}
else {
charset = StandardCharsets.UTF_8;
}
request.body(outputMessage.getOutputStream().toByteArray(), charset);
return;
}
}
String message = "Could not write request: no suitable HttpMessageConverter "
+ "found for request type [" + requestBody.getClass().getName() + "]";
if (requestContentType != null) {
message += " and content type [" + requestContentType + "]";
}
throw new EncodeException(message);
}
private boolean shouldHaveNullCharset(HttpMessageConverter messageConverter,
FeignOutputMessage outputMessage) {
return binaryContentType(outputMessage)
|| messageConverter instanceof ByteArrayHttpMessageConverter
|| messageConverter instanceof ProtobufHttpMessageConverter
&& ProtobufHttpMessageConverter.PROTOBUF.isCompatibleWith(
outputMessage.getHeaders().getContentType());
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private FeignOutputMessage checkAndWrite(Object body, MediaType contentType, private FeignOutputMessage checkAndWrite(Object body, MediaType contentType,
HttpMessageConverter converter, RequestTemplate request) throws IOException { HttpMessageConverter converter, RequestTemplate request) throws IOException {
@@ -195,6 +223,20 @@ public class SpringEncoder implements Encoder {
} }
} }
private boolean isMultipartType(MediaType requestContentType) {
return Arrays.asList(MediaType.MULTIPART_FORM_DATA, MediaType.MULTIPART_MIXED,
MediaType.MULTIPART_RELATED).contains(requestContentType);
}
private boolean binaryContentType(FeignOutputMessage outputMessage) {
MediaType contentType = outputMessage.getHeaders().getContentType();
return contentType == null || Stream
.of(MediaType.APPLICATION_CBOR, MediaType.APPLICATION_OCTET_STREAM,
MediaType.APPLICATION_PDF, MediaType.IMAGE_GIF,
MediaType.IMAGE_JPEG, MediaType.IMAGE_PNG)
.anyMatch(mediaType -> mediaType.includes(contentType));
}
private final class FeignOutputMessage implements HttpOutputMessage { private final class FeignOutputMessage implements HttpOutputMessage {
private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
@@ -8,12 +8,30 @@
"description": "If true, an OpenFeign client will be wrapped with a Hystrix circuit breaker.", "description": "If true, an OpenFeign client will be wrapped with a Hystrix circuit breaker.",
"defaultValue": "false" "defaultValue": "false"
}, },
{
"name": "feign.autoconfiguration.jackson.enabled",
"type": "java.lang.Boolean",
"description": "If true, PageJacksonModule and SortJacksonModule bean will be provided for Jackson page decoding.",
"defaultValue": "false"
},
{
"name": "feign.circuitbreaker.enabled",
"type": "java.lang.Boolean",
"description": "If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker.",
"defaultValue": "false"
},
{ {
"name": "feign.httpclient.enabled", "name": "feign.httpclient.enabled",
"type": "java.lang.Boolean", "type": "java.lang.Boolean",
"description": "Enables the use of the Apache HTTP Client by Feign.", "description": "Enables the use of the Apache HTTP Client by Feign.",
"defaultValue": "true" "defaultValue": "true"
}, },
{
"name": "feign.httpclient.hc5.enabled",
"type": "java.lang.Boolean",
"description": "Enables the use of the Apache HTTP Client 5 by Feign.",
"defaultValue": "false"
},
{ {
"name": "feign.okhttp.enabled", "name": "feign.okhttp.enabled",
"type": "java.lang.Boolean", "type": "java.lang.Boolean",
@@ -0,0 +1,107 @@
/*
* Copyright 2013-2020 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
*
* https://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.openfeign;
import feign.hystrix.HystrixFeign;
import org.assertj.core.api.Condition;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.FilteredClassLoader;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* @author Tim Peeters
*/
class FeignAutoConfigurationTests {
private final ApplicationContextRunner runner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(FeignAutoConfiguration.class));
@Test
void shouldInstantiateHystrixTargeterToMaintainBackwardsCompatibility() {
runner.run(ctx -> assertOnlyOneTargeterPresent(ctx, HystrixTargeter.class));
}
@Test
void shouldInstantiateHystrixTargeterWhenExplicitlyEnabled() {
runner.withPropertyValues("feign.hystrix.enabled=true")
.run(ctx -> assertOnlyOneTargeterPresent(ctx, HystrixTargeter.class));
}
@Test
void shouldInstantiateDefaultTargeterWhenHystrixIsDisabled() {
runner.withPropertyValues("feign.hystrix.enabled=false")
.run(ctx -> assertOnlyOneTargeterPresent(ctx, DefaultTargeter.class));
}
@Test
void shouldInstantiateDefaultTargeterWhenHystrixFeignClassIsMissing() {
runner.withPropertyValues("feign.hystrix.enabled=true")
.withClassLoader(new FilteredClassLoader(HystrixFeign.class))
.run(ctx -> assertOnlyOneTargeterPresent(ctx, DefaultTargeter.class));
}
@Test
void shouldInstantiateDefaultTargeterWhenHystrixFeignAndCircuitBreakerClassesAreMissing() {
runner.withPropertyValues("feign.hystrix.enabled=true",
"feign.circuitbreaker.enabled=true")
.withClassLoader(
new FilteredClassLoader(HystrixFeign.class, CircuitBreaker.class))
.run(ctx -> assertOnlyOneTargeterPresent(ctx, DefaultTargeter.class));
}
@Test
void shouldInstantiateDefaultTargeterWhenHystrixFeignClassIsMissingAndFeignCircuitBreakerIsDisabled() {
runner.withClassLoader(new FilteredClassLoader(HystrixFeign.class))
.withPropertyValues("feign.circuitbreaker.enabled=false")
.run(ctx -> assertOnlyOneTargeterPresent(ctx, DefaultTargeter.class));
}
@Test
void shouldInstantiateFeignCircuitBreakerTargeterWhenEnabled() {
runner.withBean(CircuitBreakerFactory.class,
() -> mock(CircuitBreakerFactory.class))
.withPropertyValues("feign.circuitbreaker.enabled=true")
.run(ctx -> assertOnlyOneTargeterPresent(ctx,
FeignCircuitBreakerTargeter.class));
}
@Test
void shouldInstantiateFeignCircuitBreakerTargeterWhenBothHystrixAndCircuitBreakerAreEnabled() {
runner.withBean(CircuitBreakerFactory.class,
() -> mock(CircuitBreakerFactory.class))
.withPropertyValues("feign.hystrix.enabled=true",
"feign.circuitbreaker.enabled=true")
.run(ctx -> assertOnlyOneTargeterPresent(ctx,
FeignCircuitBreakerTargeter.class));
}
private void assertOnlyOneTargeterPresent(ConfigurableApplicationContext ctx,
Class<?> beanClass) {
assertThat(ctx.getBeansOfType(Targeter.class)).hasSize(1)
.hasValueSatisfying(new Condition<>(beanClass::isInstance, String
.format("Targeter should be an instance of %s", beanClass)));
}
}
@@ -33,6 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Matt King * @author Matt King
* @author Sam Kruglov
*/ */
public class FeignBuilderCustomizerTests { public class FeignBuilderCustomizerTests {
@@ -78,6 +79,25 @@ public class FeignBuilderCustomizerTests {
context.close(); context.close();
} }
@Test
public void testBuildCustomizerOrderedWithAdditional() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
FeignBuilderCustomizerTests.SampleConfiguration3.class);
FeignClientFactoryBean clientFactoryBean = context
.getBean(FeignClientFactoryBean.class);
clientFactoryBean.addCustomizer(builder -> builder.logLevel(Logger.Level.BASIC));
clientFactoryBean.addCustomizer(Feign.Builder::doNotCloseAfterDecode);
FeignContext feignContext = context.getBean(FeignContext.class);
Feign.Builder builder = clientFactoryBean.feign(feignContext);
assertFeignBuilderField(builder, "logLevel", Logger.Level.BASIC);
assertFeignBuilderField(builder, "decode404", true);
assertFeignBuilderField(builder, "closeAfterDecode", false);
context.close();
}
private static FeignClientFactoryBean defaultFeignClientFactoryBean() { private static FeignClientFactoryBean defaultFeignClientFactoryBean() {
FeignClientFactoryBean feignClientFactoryBean = new FeignClientFactoryBean(); FeignClientFactoryBean feignClientFactoryBean = new FeignClientFactoryBean();
feignClientFactoryBean.setContextId("test"); feignClientFactoryBean.setContextId("test");
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -24,6 +24,7 @@ import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import feign.Feign;
import feign.hystrix.FallbackFactory; import feign.hystrix.FallbackFactory;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.Before; import org.junit.Before;
@@ -40,6 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Sven Döring * @author Sven Döring
* @author Sam Kruglov
*/ */
public class FeignClientBuilderTests { public class FeignClientBuilderTests {
@@ -58,6 +60,14 @@ public class FeignClientBuilderTests {
private static void assertFactoryBeanField(final FeignClientBuilder.Builder builder, private static void assertFactoryBeanField(final FeignClientBuilder.Builder builder,
final String fieldName, final Object expectedValue) { final String fieldName, final Object expectedValue) {
final Object value = getFactoryBeanField(builder, fieldName);
assertThat(value).as("Expected value for the field '" + fieldName + "':")
.isEqualTo(expectedValue);
}
@SuppressWarnings("unchecked")
private static <T> T getFactoryBeanField(final FeignClientBuilder.Builder builder,
final String fieldName) {
final Field factoryBeanField = ReflectionUtils final Field factoryBeanField = ReflectionUtils
.findField(FeignClientBuilder.Builder.class, "feignClientFactoryBean"); .findField(FeignClientBuilder.Builder.class, "feignClientFactoryBean");
ReflectionUtils.makeAccessible(factoryBeanField); ReflectionUtils.makeAccessible(factoryBeanField);
@@ -67,9 +77,7 @@ public class FeignClientBuilderTests {
final Field field = ReflectionUtils.findField(FeignClientFactoryBean.class, final Field field = ReflectionUtils.findField(FeignClientFactoryBean.class,
fieldName); fieldName);
ReflectionUtils.makeAccessible(field); ReflectionUtils.makeAccessible(field);
final Object value = ReflectionUtils.getField(field, factoryBean); return (T) ReflectionUtils.getField(field, factoryBean);
assertThat(value).as("Expected value for the field '" + fieldName + "':")
.isEqualTo(expectedValue);
} }
@Before @Before
@@ -84,9 +92,9 @@ public class FeignClientBuilderTests {
for (final Method method : FeignClient.class.getMethods()) { for (final Method method : FeignClient.class.getMethods()) {
methodNames.add(method.getName()); methodNames.add(method.getName());
} }
methodNames.removeAll( methodNames.removeAll(Arrays.asList("annotationType", "value", "serviceId",
Arrays.asList("annotationType", "value", "serviceId", "qualifier", "qualifier", "qualifiers", "configuration", "primary", "equals",
"configuration", "primary", "equals", "hashCode", "toString")); "hashCode", "toString"));
Collections.sort(methodNames); Collections.sort(methodNames);
// If this safety check fails the Builder has to be updated. // If this safety check fails the Builder has to be updated.
// (1) Either a field was removed from the FeignClient annotation and so it has to // (1) Either a field was removed from the FeignClient annotation and so it has to
@@ -131,7 +139,8 @@ public class FeignClientBuilderTests {
.forType(TestFeignClient.class, "TestClient").inheritParentContext(false) .forType(TestFeignClient.class, "TestClient").inheritParentContext(false)
.fallback(TestFeignClientFallback.class) .fallback(TestFeignClientFallback.class)
.fallbackFactory(TestFeignClientFallbackFactory.class).decode404(true) .fallbackFactory(TestFeignClientFallbackFactory.class).decode404(true)
.url("Url/").path("/Path").contextId("TestContext"); .url("Url/").path("/Path").contextId("TestContext")
.customize(Feign.Builder::doNotCloseAfterDecode);
// then: // then:
assertFactoryBeanField(builder, "applicationContext", this.applicationContext); assertFactoryBeanField(builder, "applicationContext", this.applicationContext);
@@ -147,14 +156,21 @@ public class FeignClientBuilderTests {
assertFactoryBeanField(builder, "fallback", TestFeignClientFallback.class); assertFactoryBeanField(builder, "fallback", TestFeignClientFallback.class);
assertFactoryBeanField(builder, "fallbackFactory", assertFactoryBeanField(builder, "fallbackFactory",
TestFeignClientFallbackFactory.class); TestFeignClientFallbackFactory.class);
List<FeignBuilderCustomizer> additionalCustomizers = getFactoryBeanField(builder,
"additionalCustomizers");
assertThat(additionalCustomizers).hasSize(1);
} }
@Test @Test
public void forType_build() { public void forType_build() {
// given: // given:
Mockito.when(this.applicationContext.getBean(FeignContext.class)) Mockito.when(this.applicationContext.getBean(FeignContext.class))
.thenThrow(new ClosedFileSystemException()); // throw an unusual exception .thenThrow(new ClosedFileSystemException()); // throw
// in the // an
// unusual
// exception
// in
// the
// FeignClientFactoryBean // FeignClientFactoryBean
final FeignClientBuilder.Builder builder = this.feignClientBuilder final FeignClientBuilder.Builder builder = this.feignClientBuilder
.forType(TestClient.class, "TestClient"); .forType(TestClient.class, "TestClient");
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import java.util.concurrent.TimeUnit;
import feign.Contract; import feign.Contract;
import feign.ExceptionPropagationPolicy; import feign.ExceptionPropagationPolicy;
import feign.Feign; import feign.Feign;
@@ -45,13 +47,13 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
* @author Olga Maciaszek-Sharma
*/ */
@SpringBootTest(classes = FeignClientOverrideDefaultsTests.TestConfiguration.class) @SpringBootTest(classes = FeignClientOverrideDefaultsTests.TestConfiguration.class)
@DirtiesContext @DirtiesContext
@@ -128,6 +130,7 @@ class FeignClientOverrideDefaultsTests {
Request.Options options = context.getInstance("bar", Request.Options.class); Request.Options options = context.getInstance("bar", Request.Options.class);
assertThat(options.connectTimeoutMillis()).isEqualTo(1); assertThat(options.connectTimeoutMillis()).isEqualTo(1);
assertThat(options.readTimeoutMillis()).isEqualTo(1); assertThat(options.readTimeoutMillis()).isEqualTo(1);
assertThat(options.isFollowRedirects()).isFalse();
} }
@Test @Test
@@ -166,7 +169,7 @@ class FeignClientOverrideDefaultsTests {
configuration = BarConfiguration.class) configuration = BarConfiguration.class)
interface BarClient { interface BarClient {
@RequestMapping(value = "/", method = RequestMethod.GET) @GetMapping("/")
String get(); String get();
} }
@@ -238,7 +241,8 @@ class FeignClientOverrideDefaultsTests {
@Bean @Bean
Request.Options feignRequestOptions() { Request.Options feignRequestOptions() {
return new Request.Options(1, 1); return new Request.Options(1, TimeUnit.MILLISECONDS, 1, TimeUnit.MILLISECONDS,
false);
} }
@Bean @Bean
@@ -26,10 +26,10 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer; import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext;
@@ -49,18 +49,19 @@ import static org.assertj.core.api.Assertions.assertThat;
"feign.client.config.default.requestInterceptors[1]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.BarRequestInterceptor" }) "feign.client.config.default.requestInterceptors[1]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.BarRequestInterceptor" })
public class FeignClientUsingConfigurerTest { public class FeignClientUsingConfigurerTest {
private static final String BEAN_NAME_PREFIX = "&org.springframework.cloud.openfeign.FeignClientUsingConfigurerTest$"; private static final String BEAN_NAME_PREFIX = "org.springframework.cloud.openfeign.FeignClientUsingConfigurerTest$";
@Autowired @Autowired
private ApplicationContext applicationContext; private ConfigurableListableBeanFactory beanFactory;
@Autowired @Autowired
private FeignContext context; private FeignContext context;
@Test @Test
public void testFeignClient() { public void testFeignClient() {
FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) applicationContext FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) beanFactory
.getBean(BEAN_NAME_PREFIX + "TestFeignClient"); .getBeanDefinition(BEAN_NAME_PREFIX + "TestFeignClient")
.getAttribute("feignClientsRegistrarFactoryBean");
Feign.Builder builder = factoryBean.feign(context); Feign.Builder builder = factoryBean.feign(context);
List<RequestInterceptor> interceptors = (List) getBuilderValue(builder, List<RequestInterceptor> interceptors = (List) getBuilderValue(builder,
@@ -79,8 +80,9 @@ public class FeignClientUsingConfigurerTest {
@Test @Test
public void testNoInheritFeignClient() { public void testNoInheritFeignClient() {
FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) applicationContext FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) beanFactory
.getBean(BEAN_NAME_PREFIX + "NoInheritFeignClient"); .getBeanDefinition(BEAN_NAME_PREFIX + "NoInheritFeignClient")
.getAttribute("feignClientsRegistrarFactoryBean");
Feign.Builder builder = factoryBean.feign(context); Feign.Builder builder = factoryBean.feign(context);
List<RequestInterceptor> interceptors = (List) getBuilderValue(builder, List<RequestInterceptor> interceptors = (List) getBuilderValue(builder,
@@ -93,8 +95,9 @@ public class FeignClientUsingConfigurerTest {
@Test @Test
public void testNoInheritFeignClient_ignoreProperties() { public void testNoInheritFeignClient_ignoreProperties() {
FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) applicationContext FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) beanFactory
.getBean(BEAN_NAME_PREFIX + "NoInheritFeignClient"); .getBeanDefinition(BEAN_NAME_PREFIX + "NoInheritFeignClient")
.getAttribute("feignClientsRegistrarFactoryBean");
Feign.Builder builder = factoryBean.feign(context); Feign.Builder builder = factoryBean.feign(context);
assertThat(getBuilderValue(builder, "logLevel")).as("log level not set") assertThat(getBuilderValue(builder, "logLevel")).as("log level not set")
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -246,6 +246,21 @@ public class FeignClientUsingPropertiesTests {
assertThat(options.readTimeoutMillis()).isEqualTo(5000); assertThat(options.readTimeoutMillis()).isEqualTo(5000);
} }
@Test
public void shouldSetFollowRedirects() {
FeignClientFactoryBean testFactoryBean = new FeignClientFactoryBean();
testFactoryBean.setContextId("test");
testFactoryBean.setType(FeignClientFactoryBean.class);
testFactoryBean.setApplicationContext(applicationContext);
TimeoutClient client = testFactoryBean.feign(context).target(TimeoutClient.class,
"http://localhost:" + port);
Request.Options options = getRequestOptions((Proxy) client);
assertThat(options.isFollowRedirects()).isFalse();
}
private Request.Options getRequestOptions(Proxy client) { private Request.Options getRequestOptions(Proxy client) {
Object invocationHandler = ReflectionTestUtils.getField(client, "h"); Object invocationHandler = ReflectionTestUtils.getField(client, "h");
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch = (Map<Method, InvocationHandlerFactory.MethodHandler>) ReflectionTestUtils Map<Method, InvocationHandlerFactory.MethodHandler> dispatch = (Map<Method, InvocationHandlerFactory.MethodHandler>) ReflectionTestUtils
@@ -0,0 +1,135 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.openfeign.test.NoSecurityConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link FeignClientsRegistrar}.
*
* @author Olga Maciaszek-Sharma
*/
@SpringBootTest(
classes = FeignClientsRegistrarIntegrationTests.QualifiersTestConfig.class)
class FeignClientsRegistrarIntegrationTests {
@Autowired
ConfigurableApplicationContext context;
@Test
void shouldUseQualifiersIfPresent() {
assertThat(context.getBean("qualifier1")).isNotNull();
assertThat(context.getBean("qualifier2")).isNotNull();
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> context.getBean("qualifier3"));
}
@Test
void shouldUseQualifierIfQualifiersArrayNotPresent() {
assertThat(context.getBean("qualifier4")).isNotNull();
}
@Test
void shouldUseDefaultQualifierWhenNonePresent() {
assertThat(context.getBean("noQualifiersFeignClient")).isNotNull();
}
@Test
void shouldUseQualifierWhenEmptyQualifiers() {
assertThat(context.getBean("test1")).isNotNull();
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> context.getBean("emptyQualifiersFeignClient"));
}
@Test
void shouldUseQualifierWhenWhitespaceQualifiers() {
assertThat(context.getBean("test2")).isNotNull();
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> context.getBean("whitespaceQualifiersFeignClient"));
}
@Test
void shouldUseDefaultQualifierWhenEmptyQualifiers() {
assertThat(context.getBean("emptyQualifiersNoQualifierFeignClient")).isNotNull();
}
@Test
void shouldUseDefaultQualifierWhenWhitespaceQualifiers() {
assertThat(context.getBean("whitespaceQualifiersNoQualifierFeignClient"))
.isNotNull();
}
@FeignClient(name = "qualifiersClient", qualifiers = { "qualifier1", "qualifier2" },
qualifier = "qualifier3")
protected interface QualifiersClient {
}
@FeignClient(name = "qualifierClient", qualifier = "qualifier4")
protected interface QualifierClient {
}
@FeignClient(name = "noQualifiers")
protected interface NoQualifiersClient {
}
@FeignClient(name = "emptyQualifiers", qualifier = "test1", qualifiers = {})
protected interface EmptyQualifiersClient {
}
@FeignClient(name = "whitespaceQualifiers", qualifier = "test2", qualifiers = { " " })
protected interface WhitespaceQualifiersClient {
}
@FeignClient(name = "emptyQualifiersNoQualifier", qualifiers = {})
protected interface EmptyQualifiersNoQualifierClient {
}
@FeignClient(name = "whitespaceQualifiersNoQualifier", qualifiers = { " " })
protected interface WhitespaceQualifiersNoQualifierClient {
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@Import(NoSecurityConfiguration.class)
@EnableFeignClients(clients = { QualifiersClient.class, QualifierClient.class,
NoQualifiersClient.class, EmptyQualifiersClient.class,
WhitespaceQualifiersClient.class, EmptyQualifiersNoQualifierClient.class,
WhitespaceQualifiersNoQualifierClient.class })
protected static class QualifiersTestConfig {
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -80,7 +80,7 @@ public class FeignClientsRegistrarTests {
private String testGetName(String name) { private String testGetName(String name) {
FeignClientsRegistrar registrar = new FeignClientsRegistrar(); FeignClientsRegistrar registrar = new FeignClientsRegistrar();
registrar.setEnvironment(new MockEnvironment()); registrar.setEnvironment(new MockEnvironment());
return registrar.getName(Collections.<String, Object>singletonMap("name", name)); return registrar.getName(Collections.singletonMap("name", name));
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
@@ -102,7 +102,6 @@ public class FeignClientsRegistrarTests {
assertThatCode(() -> config.refresh()).as( assertThatCode(() -> config.refresh()).as(
"Case https://github.com/spring-cloud/spring-cloud-openfeign/issues/331 should be solved") "Case https://github.com/spring-cloud/spring-cloud-openfeign/issues/331 should be solved")
.doesNotThrowAnyException(); .doesNotThrowAnyException();
} }
@FeignClient(name = "fallbackTestClient", url = "http://localhost:8080/", @FeignClient(name = "fallbackTestClient", url = "http://localhost:8080/",
@@ -0,0 +1,157 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign;
import feign.Client;
import feign.hc5.ApacheHttp5Client;
import feign.httpclient.ApacheHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.commons.httpclient.HttpClientConfiguration;
import org.springframework.cloud.test.ClassPathExclusions;
import org.springframework.cloud.test.ModifiedClassPathRunner;
import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Nguyen Ky Thanh
*/
public class FeignHttpClient5ConfigurationTests {
private static void verifyHc4BeansAvailable(ConfigurableApplicationContext context) {
org.apache.http.impl.client.CloseableHttpClient httpClient4 = context
.getBean(org.apache.http.impl.client.CloseableHttpClient.class);
assertThat(httpClient4).isNotNull();
org.apache.http.conn.HttpClientConnectionManager connectionManager4 = context
.getBean(org.apache.http.conn.HttpClientConnectionManager.class);
assertThat(connectionManager4).isInstanceOf(
org.apache.http.impl.conn.PoolingHttpClientConnectionManager.class);
Client client = context.getBean(Client.class);
assertThat(client).isInstanceOf(ApacheHttpClient.class);
}
private static void verifyHc5BeansAvailable(ConfigurableApplicationContext context) {
CloseableHttpClient httpClient = context.getBean(CloseableHttpClient.class);
assertThat(httpClient).isNotNull();
HttpClientConnectionManager connectionManager = context
.getBean(HttpClientConnectionManager.class);
assertThat(connectionManager)
.isInstanceOf(PoolingHttpClientConnectionManager.class);
Client client = context.getBean(Client.class);
assertThat(client).isInstanceOf(ApacheHttp5Client.class);
}
@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions("ribbon-loadbalancer-{version:\\d.*}.jar")
public static class WithoutLoadBalancerInClasspath {
@Test
public void verifyHttpClient5AutoConfig() {
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.properties("feign.httpclient.hc5.enabled=true",
"feign.httpclient.enabled=false")
.web(WebApplicationType.NONE)
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
.run();
verifyHc5BeansAvailable(context);
if (context != null) {
context.close();
}
}
@Test
public void hc5ShouldWinIfTheBothVersionsAvailable() {
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.properties("feign.httpclient.hc5.enabled=true",
"feign.httpclient.enabled=true")
.web(WebApplicationType.NONE)
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
.run();
Client client = context.getBean(Client.class);
assertThat(client).isInstanceOf(ApacheHttp5Client.class);
if (context != null) {
context.close();
}
}
@Test
public void hc4ShouldBeTheDefaultIfHc5NotEnabled() {
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.properties("feign.httpclient.hc5.enabled=false",
"feign.httpclient.enabled=true")
.web(WebApplicationType.NONE)
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
.run();
verifyHc4BeansAvailable(context);
if (context != null) {
context.close();
}
}
}
@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions({ "ribbon-loadbalancer-{version:\\d.*}.jar",
"feign-hc5-{version:\\d.*}.jar", "httpclient5-{version:\\d.*}.jar",
"httpcore5-{version:\\d.*}.jar", "httpcore5-h2-{version:\\d.*}.jar" })
public static class WithoutLoadBalancerAndHc5InClasspath {
@Test
public void hc4ShouldWinEvenHc5ConfigEnabled() {
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.properties("feign.httpclient.hc5.enabled=true")
.web(WebApplicationType.NONE)
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
.run();
verifyHc4BeansAvailable(context);
if (context != null) {
context.close();
}
}
@Test
public void hc4ShouldBeTheDefault() {
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.web(WebApplicationType.NONE)
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
.run();
verifyHc4BeansAvailable(context);
if (context != null) {
context.close();
}
}
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -23,10 +23,9 @@ import feign.Client;
import feign.Feign; import feign.Feign;
import feign.Target; import feign.Target;
import feign.httpclient.ApacheHttpClient; import feign.httpclient.ApacheHttpClient;
import org.junit.AfterClass; import org.junit.jupiter.api.AfterAll;
import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeAll;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -36,7 +35,6 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
import org.springframework.util.SocketUtils; import org.springframework.util.SocketUtils;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
@@ -48,14 +46,14 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
/** /**
* @author Spencer Gibb * @author Spencer Gibb
* @author Olga Maciaszek-Sharma
*/ */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = FeignHttpClientUrlTests.TestConfig.class, @SpringBootTest(classes = FeignHttpClientUrlTests.TestConfig.class,
webEnvironment = DEFINED_PORT, webEnvironment = DEFINED_PORT,
value = { "spring.application.name=feignclienturltest", value = { "spring.application.name=feignclienturltest",
"feign.hystrix.enabled=false", "feign.okhttp.enabled=false" }) "feign.hystrix.enabled=false", "feign.okhttp.enabled=false" })
@DirtiesContext @DirtiesContext
public class FeignHttpClientUrlTests { class FeignHttpClientUrlTests {
static int port; static int port;
@@ -68,37 +66,37 @@ public class FeignHttpClientUrlTests {
@Autowired @Autowired
private BeanUrlClient beanClient; private BeanUrlClient beanClient;
@BeforeClass @BeforeAll
public static void beforeClass() { static void beforeClass() {
port = SocketUtils.findAvailableTcpPort(); port = SocketUtils.findAvailableTcpPort();
System.setProperty("server.port", String.valueOf(port)); System.setProperty("server.port", String.valueOf(port));
} }
@AfterClass @AfterAll
public static void afterClass() { static void afterClass() {
System.clearProperty("server.port"); System.clearProperty("server.port");
} }
@Test @Test
public void testUrlHttpClient() { void testUrlHttpClient() {
assertThat(this.urlClient).as("UrlClient was null").isNotNull(); assertThat(urlClient).as("UrlClient was null").isNotNull();
Hello hello = this.urlClient.getHello(); Hello hello = urlClient.getHello();
assertThat(hello).as("hello was null").isNotNull(); assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match") assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1")); .isEqualTo(new Hello("hello world 1"));
} }
@Test @Test
public void testBeanUrl() { void testBeanUrl() {
Hello hello = this.beanClient.getHello(); Hello hello = beanClient.getHello();
assertThat(hello).as("hello was null").isNotNull(); assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match") assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1")); .isEqualTo(new Hello("hello world 1"));
} }
@Test @Test
public void testBeanUrlNoProtocol() { void testBeanUrlNoProtocol() {
Hello hello = this.beanClientNoProtocol.getHello(); Hello hello = beanClientNoProtocol.getHello();
assertThat(hello).as("hello was null").isNotNull(); assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match") assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1")); .isEqualTo(new Hello("hello world 1"));
@@ -182,15 +180,16 @@ public class FeignHttpClientUrlTests {
private String message; private String message;
public Hello() { Hello() {
} }
public Hello(String message) { Hello(String message) {
this.message = message; this.message = message;
} }
public String getMessage() { public String getMessage() {
return this.message; return message;
} }
public void setMessage(String message) { public void setMessage(String message) {
@@ -206,12 +205,12 @@ public class FeignHttpClientUrlTests {
return false; return false;
} }
Hello that = (Hello) o; Hello that = (Hello) o;
return Objects.equals(this.message, that.message); return Objects.equals(message, that.message);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(this.message); return Objects.hash(message);
} }
} }
@@ -0,0 +1,221 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign;
import java.lang.reflect.Field;
import java.util.Objects;
import feign.Client;
import feign.Feign;
import feign.Target;
import feign.httpclient.ApacheHttpClient;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.openfeign.test.NoSecurityConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.SocketUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
/**
* @author Spencer Gibb
* @author Olga Maciaszek-Sharma
*/
@SpringBootTest(classes = FeignHttpClientUrlTestsWithLoadBalancer.TestConfig.class,
webEnvironment = DEFINED_PORT,
value = { "spring.application.name=feignclienturlwithloadbalancertest",
"feign.hystrix.enabled=false", "feign.okhttp.enabled=false",
"spring.cloud.loadbalancer.ribbon.enabled=false",
"spring.cloud.loadbalancer.retry.enabled=false" })
@DirtiesContext
class FeignHttpClientUrlTestsWithLoadBalancer {
static int port;
@Autowired
BeanUrlClientNoProtocol beanClientNoProtocol;
@Autowired
private UrlClient urlClient;
@Autowired
private BeanUrlClient beanClient;
@BeforeAll
static void beforeClass() {
port = SocketUtils.findAvailableTcpPort();
System.setProperty("server.port", String.valueOf(port));
}
@AfterAll
static void afterClass() {
System.clearProperty("server.port");
}
@Test
void testUrlHttpClient() {
assertThat(urlClient).as("UrlClient was null").isNotNull();
Hello hello = urlClient.getHello();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
}
@Test
void testBeanUrl() {
Hello hello = beanClient.getHello();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
}
@Test
void testBeanUrlNoProtocol() {
Hello hello = beanClientNoProtocol.getHello();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
}
// this tests that
@FeignClient(name = "localappurl", url = "http://localhost:${server.port}/")
protected interface UrlClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello getHello();
}
@FeignClient(name = "beanappurl", url = "#{SERVER_URL}path")
protected interface BeanUrlClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello getHello();
}
@FeignClient(name = "beanappurlnoprotocol", url = "#{SERVER_URL_NO_PROTOCOL}path")
protected interface BeanUrlClientNoProtocol {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello getHello();
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@RestController
@EnableFeignClients(clients = { UrlClient.class, BeanUrlClient.class,
BeanUrlClientNoProtocol.class })
@Import(NoSecurityConfiguration.class)
protected static class TestConfig {
@GetMapping("/hello")
public Hello getHello() {
return new Hello("hello world 1");
}
@GetMapping("/path/hello")
public Hello getHelloWithPath() {
return getHello();
}
@Bean(name = "SERVER_URL")
public String serverUrl() {
return "http://localhost:" + port + "/";
}
@Bean(name = "SERVER_URL_NO_PROTOCOL")
public String serverUrlNoProtocol() {
return "localhost:" + port + "/";
}
@Bean
public Targeter feignTargeter() {
return new Targeter() {
@Override
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign,
FeignContext context, Target.HardCodedTarget<T> target) {
Field field = ReflectionUtils.findField(Feign.Builder.class,
"client");
ReflectionUtils.makeAccessible(field);
Client client = (Client) ReflectionUtils.getField(field, feign);
if (target.name().equals("localappurl")) {
assertThat(client).isInstanceOf(ApacheHttpClient.class)
.as("client was wrong type");
}
return feign.target(target);
}
};
}
}
public static class Hello {
private String message;
Hello() {
}
Hello(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Hello that = (Hello) o;
return Objects.equals(message, that.message);
}
@Override
public int hashCode() {
return Objects.hash(message);
}
}
}
@@ -0,0 +1,221 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign;
import java.lang.reflect.Field;
import java.util.Objects;
import feign.Client;
import feign.Feign;
import feign.Target;
import feign.httpclient.ApacheHttpClient;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.openfeign.test.NoSecurityConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.SocketUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
/**
* @author Spencer Gibb
* @author Olga Maciaszek-Sharma
*/
@SpringBootTest(
classes = FeignHttpClientUrlTestsWithRetryableLoadBalancer.TestConfig.class,
webEnvironment = DEFINED_PORT,
value = { "spring.application.name=feignclienturlwithretryableloadbalancertest",
"feign.hystrix.enabled=false", "feign.okhttp.enabled=false",
"spring.cloud.loadbalancer.ribbon.enabled=false" })
@DirtiesContext
class FeignHttpClientUrlTestsWithRetryableLoadBalancer {
static int port;
@Autowired
BeanUrlClientNoProtocol beanClientNoProtocol;
@Autowired
private UrlClient urlClient;
@Autowired
private BeanUrlClient beanClient;
@BeforeAll
static void beforeClass() {
port = SocketUtils.findAvailableTcpPort();
System.setProperty("server.port", String.valueOf(port));
}
@AfterAll
static void afterClass() {
System.clearProperty("server.port");
}
@Test
void testUrlHttpClient() {
assertThat(urlClient).as("UrlClient was null").isNotNull();
Hello hello = urlClient.getHello();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
}
@Test
void testBeanUrl() {
Hello hello = beanClient.getHello();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
}
@Test
void testBeanUrlNoProtocol() {
Hello hello = beanClientNoProtocol.getHello();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
}
// this tests that
@FeignClient(name = "localappurl", url = "http://localhost:${server.port}/")
protected interface UrlClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello getHello();
}
@FeignClient(name = "beanappurl", url = "#{SERVER_URL}path")
protected interface BeanUrlClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello getHello();
}
@FeignClient(name = "beanappurlnoprotocol", url = "#{SERVER_URL_NO_PROTOCOL}path")
protected interface BeanUrlClientNoProtocol {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello getHello();
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@RestController
@EnableFeignClients(clients = { UrlClient.class, BeanUrlClient.class,
BeanUrlClientNoProtocol.class })
@Import(NoSecurityConfiguration.class)
protected static class TestConfig {
@GetMapping("/hello")
public Hello getHello() {
return new Hello("hello world 1");
}
@GetMapping("/path/hello")
public Hello getHelloWithPath() {
return getHello();
}
@Bean(name = "SERVER_URL")
public String serverUrl() {
return "http://localhost:" + port + "/";
}
@Bean(name = "SERVER_URL_NO_PROTOCOL")
public String serverUrlNoProtocol() {
return "localhost:" + port + "/";
}
@Bean
public Targeter feignTargeter() {
return new Targeter() {
@Override
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign,
FeignContext context, Target.HardCodedTarget<T> target) {
Field field = ReflectionUtils.findField(Feign.Builder.class,
"client");
ReflectionUtils.makeAccessible(field);
Client client = (Client) ReflectionUtils.getField(field, feign);
if (target.name().equals("localappurl")) {
assertThat(client).isInstanceOf(ApacheHttpClient.class)
.as("client was wrong type");
}
return feign.target(target);
}
};
}
}
public static class Hello {
private String message;
Hello() {
}
Hello(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Hello that = (Hello) o;
return Objects.equals(message, that.message);
}
@Override
public int hashCode() {
return Objects.hash(message);
}
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -32,7 +32,9 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.cloud.openfeign.test.NoSecurityConfiguration; import org.springframework.cloud.openfeign.test.NoSecurityConfiguration;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -45,6 +47,7 @@ import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
* @author Olga Maciaszek-Sharma
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringDecoderTests.Application.class, @SpringBootTest(classes = SpringDecoderTests.Application.class,
@@ -152,6 +155,14 @@ public class SpringDecoderTests extends FeignClientFactoryBean {
assertThat(response.getBody()).as("response body was not null").isNull(); assertThat(response.getBody()).as("response body was not null").isNull();
} }
@Test
// Issue: https://github.com/spring-cloud/spring-cloud-openfeign/issues/456
public void testResponseEntityHeaders() {
ResponseEntity<String> response = testClient().getContentType();
assertThat(response.getHeaders().getContentType())
.isEqualTo(MediaType.APPLICATION_JSON);
}
protected interface TestClient { protected interface TestClient {
@RequestMapping(method = RequestMethod.GET, value = "/helloresponse") @RequestMapping(method = RequestMethod.GET, value = "/helloresponse")
@@ -175,6 +186,9 @@ public class SpringDecoderTests extends FeignClientFactoryBean {
@GetMapping("/helloWildcard") @GetMapping("/helloWildcard")
ResponseEntity<?> getWildcard(); ResponseEntity<?> getWildcard();
@GetMapping(path = "/contentType", produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> getContentType();
} }
public static class Hello { public static class Hello {
@@ -262,6 +276,13 @@ public class SpringDecoderTests extends FeignClientFactoryBean {
return ResponseEntity.ok(new Hello("wildcard")); return ResponseEntity.ok(new Hello("wildcard"));
} }
@Override
public ResponseEntity<String> getContentType() {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body("test");
}
} }
} }
@@ -0,0 +1,246 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign.circuitbreaker;
import java.util.function.Function;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.ConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.NoFallbackAvailableException;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.test.NoSecurityConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.SocketUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Spencer Gibb
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = CircuitBreakerTests.Application.class,
webEnvironment = WebEnvironment.DEFINED_PORT,
value = { "spring.application.name=springcircuittest", "spring.jmx.enabled=false",
"feign.circuitbreaker.enabled=true" })
@DirtiesContext
public class CircuitBreakerTests {
@Autowired
MyCircuitBreaker myCircuitBreaker;
@Autowired
TestClient testClient;
@Autowired
TestClientWithFactory testClientWithFactory;
@BeforeAll
public static void beforeClass() {
System.setProperty("server.port",
String.valueOf(SocketUtils.findAvailableTcpPort()));
}
@AfterAll
public static void afterClass() {
System.clearProperty("server.port");
}
@Before
public void setup() {
this.myCircuitBreaker.clear();
}
@Test
public void testSimpleTypeWithFallback() {
Hello hello = testClient.getHello();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
assertThat(myCircuitBreaker.runWasCalled).as("Circuit Breaker was called")
.isTrue();
}
@Test
public void test404WithFallback() {
assertThat(testClient.getException()).isEqualTo("Fixed response");
}
@Test
public void testSimpleTypeWithFallbackFactory() {
Hello hello = testClientWithFactory.getHello();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
assertThat(myCircuitBreaker.runWasCalled).as("Circuit Breaker was called")
.isTrue();
}
@Test
public void test404WithFallbackFactory() {
assertThat(testClientWithFactory.getException()).isEqualTo("Fixed response");
}
// tag::client_with_fallback[]
@FeignClient(name = "test", url = "http://localhost:${server.port}/",
fallback = Fallback.class)
protected interface TestClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello getHello();
@RequestMapping(method = RequestMethod.GET, value = "/hellonotfound")
String getException();
}
@Component
static class Fallback implements TestClient {
@Override
public Hello getHello() {
throw new NoFallbackAvailableException("Boom!", new RuntimeException());
}
@Override
public String getException() {
return "Fixed response";
}
}
// end::client_with_fallback[]
// tag::client_with_fallback_factory[]
@FeignClient(name = "testClientWithFactory", url = "http://localhost:${server.port}/",
fallbackFactory = TestFallbackFactory.class)
protected interface TestClientWithFactory {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello getHello();
@RequestMapping(method = RequestMethod.GET, value = "/hellonotfound")
String getException();
}
@Component
static class TestFallbackFactory implements FallbackFactory<FallbackWithFactory> {
@Override
public FallbackWithFactory create(Throwable cause) {
return new FallbackWithFactory();
}
}
static class FallbackWithFactory implements TestClientWithFactory {
@Override
public Hello getHello() {
throw new NoFallbackAvailableException("Boom!", new RuntimeException());
}
@Override
public String getException() {
return "Fixed response";
}
}
// end::client_with_fallback_factory[]
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@RestController
@EnableFeignClients(clients = { TestClient.class, TestClientWithFactory.class })
@Import(NoSecurityConfiguration.class)
protected static class Application implements TestClient {
static final Log log = LogFactory.getLog(Application.class);
@Bean
MyCircuitBreaker myCircuitBreaker() {
return new MyCircuitBreaker();
}
@Bean
CircuitBreakerFactory circuitBreakerFactory(MyCircuitBreaker myCircuitBreaker) {
return new CircuitBreakerFactory() {
@Override
public CircuitBreaker create(String id) {
log.info("Creating a circuit breaker with id [" + id + "]");
return myCircuitBreaker;
}
@Override
protected ConfigBuilder configBuilder(String id) {
return Object::new;
}
@Override
public void configureDefault(Function defaultConfiguration) {
}
};
}
@Override
public Hello getHello() {
return new Hello("hello world 1");
}
@Override
public String getException() {
throw new IllegalStateException("BOOM!");
}
@Bean
Fallback fallback() {
return new Fallback();
}
@Bean
TestFallbackFactory testFallbackFactory() {
return new TestFallbackFactory();
}
}
}
@@ -0,0 +1,159 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign.circuitbreaker;
import java.util.function.Function;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.ConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.NoFallbackAvailableException;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.test.NoSecurityConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.util.SocketUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Tests for Feign calls with CircuitBreaker, without fallbacks.
*
* @author Olga Maciaszek-Sharma
*/
@SpringBootTest(classes = CircuitBreakerWithNoFallbackTests.Application.class,
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
value = { "spring.application.name=springcircuittest", "spring.jmx.enabled=false",
"feign.circuitbreaker.enabled=true" })
@DirtiesContext
public class CircuitBreakerWithNoFallbackTests {
@Autowired
MyCircuitBreaker myCircuitBreaker;
@Autowired
CircuitBreakerTestClient testClient;
@BeforeAll
public static void beforeClass() {
System.setProperty("server.port",
String.valueOf(SocketUtils.findAvailableTcpPort()));
}
@AfterAll
public static void afterClass() {
System.clearProperty("server.port");
}
@BeforeEach
public void setup() {
this.myCircuitBreaker.clear();
}
@Test
public void testSimpleTypeWithFallback() {
Hello hello = testClient.getHello();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
assertThat(myCircuitBreaker.runWasCalled).as("Circuit Breaker was called")
.isTrue();
}
@Test
public void test404WithoutFallback() {
assertThatThrownBy(() -> testClient.getException())
.isInstanceOf(NoFallbackAvailableException.class);
}
@FeignClient(name = "test", url = "http://localhost:${server.port}/")
protected interface CircuitBreakerTestClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello getHello();
@RequestMapping(method = RequestMethod.GET, value = "/hellonotfound")
String getException();
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@RestController
@EnableFeignClients(clients = { CircuitBreakerTestClient.class })
@Import(NoSecurityConfiguration.class)
protected static class Application implements CircuitBreakerTestClient {
static final Log log = LogFactory.getLog(Application.class);
@Bean
MyCircuitBreaker myCircuitBreaker() {
return new MyCircuitBreaker();
}
@Bean
CircuitBreakerFactory circuitBreakerFactory(MyCircuitBreaker myCircuitBreaker) {
return new CircuitBreakerFactory() {
@Override
public CircuitBreaker create(String id) {
log.info("Creating a circuit breaker with id [" + id + "]");
return myCircuitBreaker;
}
@Override
protected ConfigBuilder configBuilder(String id) {
return Object::new;
}
@Override
public void configureDefault(Function defaultConfiguration) {
}
};
}
@Override
public Hello getHello() {
return new Hello("hello world 1");
}
@Override
public String getException() {
throw new IllegalStateException("BOOM!");
}
}
}
@@ -0,0 +1,60 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign.circuitbreaker;
import java.util.Objects;
/**
* @author Marcin Grzejszczak
*/
class Hello {
private String message;
public Hello() {
}
public Hello(String message) {
this.message = message;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Hello that = (Hello) o;
return Objects.equals(this.message, that.message);
}
@Override
public int hashCode() {
return Objects.hash(this.message);
}
}
@@ -0,0 +1,59 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign.circuitbreaker;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.NoFallbackAvailableException;
/**
* @author Marcin Grzejszczak
* @author Olga Maciaszek-Sharma
*/
class MyCircuitBreaker implements CircuitBreaker {
AtomicBoolean runWasCalled = new AtomicBoolean();
@Override
public <T> T run(Supplier<T> toRun) {
try {
this.runWasCalled.set(true);
return toRun.get();
}
catch (Throwable throwable) {
throw new NoFallbackAvailableException("No fallback available.", throwable);
}
}
@Override
public <T> T run(Supplier<T> toRun, Function<Throwable, T> fallback) {
try {
return run(toRun);
}
catch (Throwable throwable) {
return fallback.apply(throwable);
}
}
public void clear() {
this.runWasCalled.set(false);
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package org.springframework.cloud.openfeign.encoding; package org.springframework.cloud.openfeign.encoding;
import java.util.Collections; import java.util.Collections;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.BaseLoadBalancer;
@@ -32,7 +33,6 @@ import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoCon
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.cloud.openfeign.encoding.app.client.InvoiceClient; import org.springframework.cloud.openfeign.encoding.app.client.InvoiceClient;
import org.springframework.cloud.openfeign.encoding.app.domain.Invoice; import org.springframework.cloud.openfeign.encoding.app.domain.Invoice;
import org.springframework.cloud.openfeign.test.NoSecurityConfiguration; import org.springframework.cloud.openfeign.test.NoSecurityConfiguration;
@@ -55,10 +55,12 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* Tests the pagination encoding. * Tests the pagination encoding.
* *
* @author Charlie Mordant. * @author Charlie Mordant.
* @author Hyeonmin Park
*/ */
@SpringBootTest(classes = FeignPageableEncodingTests.Application.class, @SpringBootTest(classes = FeignPageableEncodingTests.Application.class,
webEnvironment = RANDOM_PORT, webEnvironment = RANDOM_PORT,
value = { "feign.compression.request.enabled=true", value = { "feign.compression.request.enabled=true",
"feign.autoconfiguration.jackson.enabled=true",
"hystrix.command.default.execution.isolation.strategy=SEMAPHORE", "hystrix.command.default.execution.isolation.strategy=SEMAPHORE",
"ribbon.OkToRetryOnAllOperations=false" }) "ribbon.OkToRetryOnAllOperations=false" })
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@@ -69,7 +71,6 @@ public class FeignPageableEncodingTests {
@Test @Test
public void testPageable() { public void testPageable() {
// given // given
Pageable pageable = PageRequest.of(0, 10, Sort.Direction.ASC, "sortProperty"); Pageable pageable = PageRequest.of(0, 10, Sort.Direction.ASC, "sortProperty");
@@ -90,7 +91,191 @@ public class FeignPageableEncodingTests {
assertThat(order.getDirection()).isEqualTo(Sort.Direction.ASC); assertThat(order.getDirection()).isEqualTo(Sort.Direction.ASC);
assertThat(order.getProperty()).isEqualTo("sortProperty"); assertThat(order.getProperty()).isEqualTo("sortProperty");
} }
}
@Test
public void testPageableWithDescDirection() {
// given
Pageable pageable = PageRequest.of(0, 10, Sort.Direction.DESC, "sortProperty");
// when
final ResponseEntity<Page<Invoice>> response = this.invoiceClient
.getInvoicesPaged(pageable);
// then
assertThat(response).isNotNull();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isNotNull();
assertThat(pageable.getPageSize()).isEqualTo(response.getBody().getSize());
Sort sort = response.getBody().getPageable().getSort();
assertThat(sort).hasSize(1);
assertThat(sort.get()).hasSize(1);
Optional<Sort.Order> optionalOrder = sort.get().findFirst();
assertThat(optionalOrder.isPresent()).isTrue();
Sort.Order order = optionalOrder.get();
assertThat(order.getDirection()).isEqualTo(Sort.Direction.DESC);
assertThat(order.getProperty()).isEqualTo("sortProperty");
}
@Test
public void testPageableWithMultipleSort() {
// given
Pageable pageable = PageRequest.of(0, 10, Sort
.by(Sort.Order.desc("sortProperty1"), Sort.Order.asc("sortProperty2")));
// when
final ResponseEntity<Page<Invoice>> response = this.invoiceClient
.getInvoicesPaged(pageable);
// then
assertThat(response).isNotNull();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isNotNull();
assertThat(pageable.getPageSize()).isEqualTo(response.getBody().getSize());
Sort sort = response.getBody().getPageable().getSort();
assertThat(sort).hasSize(2);
List<Sort.Order> orderList = sort.toList();
assertThat(orderList).hasSize(2);
Sort.Order firstOrder = orderList.get(0);
assertThat(firstOrder.getDirection()).isEqualTo(Sort.Direction.DESC);
assertThat(firstOrder.getProperty()).isEqualTo("sortProperty1");
Sort.Order secondOrder = orderList.get(1);
assertThat(secondOrder.getDirection()).isEqualTo(Sort.Direction.ASC);
assertThat(secondOrder.getProperty()).isEqualTo("sortProperty2");
}
@Test
public void testPageableWithoutSort() {
// given
Pageable pageable = PageRequest.of(0, 10);
// when
final ResponseEntity<Page<Invoice>> response = this.invoiceClient
.getInvoicesPaged(pageable);
// then
assertThat(response).isNotNull();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isNotNull();
assertThat(pageable.getPageSize()).isEqualTo(response.getBody().getSize());
assertThat(response.getBody().getPageable().getSort().isSorted()).isFalse();
List<Invoice> invoiceList = response.getBody().getContent();
assertThat(invoiceList).hasSizeGreaterThanOrEqualTo(1);
}
@Test
public void testPageableWithoutSortWithBody() {
// given
Pageable pageable = PageRequest.of(0, 10);
// when
final ResponseEntity<Page<Invoice>> response = this.invoiceClient
.getInvoicesPagedWithBody(pageable, "InvoiceTitleFromBody");
// then
assertThat(response).isNotNull();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isNotNull();
assertThat(pageable.getPageSize()).isEqualTo(response.getBody().getSize());
List<Invoice> invoiceList = response.getBody().getContent();
assertThat(invoiceList).hasSizeGreaterThanOrEqualTo(1);
Invoice firstInvoice = invoiceList.get(0);
assertThat(firstInvoice.getTitle()).startsWith("InvoiceTitleFromBody");
}
@Test
public void testPageableWithBody() {
// given
Pageable pageable = PageRequest.of(0, 10, Sort
.by(Sort.Order.desc("sortProperty1"), Sort.Order.asc("sortProperty2")));
// when
final ResponseEntity<Page<Invoice>> response = this.invoiceClient
.getInvoicesPagedWithBody(pageable, "InvoiceTitleFromBody");
// then
assertThat(response).isNotNull();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isNotNull();
assertThat(pageable.getPageSize()).isEqualTo(response.getBody().getSize());
List<Invoice> invoiceList = response.getBody().getContent();
assertThat(invoiceList).hasSizeGreaterThanOrEqualTo(1);
Invoice firstInvoice = invoiceList.get(0);
assertThat(firstInvoice.getTitle()).startsWith("InvoiceTitleFromBody");
Sort sort = response.getBody().getPageable().getSort();
assertThat(sort).hasSize(2);
List<Sort.Order> orderList = sort.toList();
assertThat(orderList).hasSize(2);
Sort.Order firstOrder = orderList.get(0);
assertThat(firstOrder.getDirection()).isEqualTo(Sort.Direction.DESC);
assertThat(firstOrder.getProperty()).isEqualTo("sortProperty1");
Sort.Order secondOrder = orderList.get(1);
assertThat(secondOrder.getDirection()).isEqualTo(Sort.Direction.ASC);
assertThat(secondOrder.getProperty()).isEqualTo("sortProperty2");
}
@Test
public void testUnpagedWithBody() {
// given
Pageable unpaged = Pageable.unpaged();
// when
final ResponseEntity<Page<Invoice>> response = this.invoiceClient
.getInvoicesPagedWithBody(unpaged, "InvoiceTitleFromBody");
// then
assertThat(response).isNotNull();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isNotNull();
List<Invoice> invoiceList = response.getBody().getContent();
assertThat(invoiceList).hasSizeGreaterThanOrEqualTo(1);
Invoice firstInvoice = invoiceList.get(0);
assertThat(firstInvoice.getTitle()).startsWith("InvoiceTitleFromBody");
}
@Test
public void testSortWithBody() {
// given
Sort sort = Sort.by(Sort.Order.desc("amount"));
// when
final ResponseEntity<Page<Invoice>> response = this.invoiceClient
.getInvoicesSortedWithBody(sort, "InvoiceTitleFromBody");
// then
assertThat(response).isNotNull();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).isNotNull();
assertThat(sort).isEqualTo(response.getBody().getSort());
List<Invoice> invoiceList = response.getBody().getContent();
assertThat(invoiceList).hasSizeGreaterThanOrEqualTo(1);
Invoice firstInvoice = invoiceList.get(0);
assertThat(firstInvoice.getTitle()).startsWith("InvoiceTitleFromBody");
for (int ind = 0; ind < invoiceList.size() - 1; ind++) {
assertThat(invoiceList.get(ind).getAmount())
.isGreaterThanOrEqualTo(invoiceList.get(ind + 1).getAmount());
}
} }
@EnableFeignClients(clients = InvoiceClient.class) @EnableFeignClients(clients = InvoiceClient.class)
@@ -99,7 +284,7 @@ public class FeignPageableEncodingTests {
scanBasePackages = "org.springframework.cloud.openfeign.encoding.app", scanBasePackages = "org.springframework.cloud.openfeign.encoding.app",
exclude = { RepositoryRestMvcAutoConfiguration.class }) exclude = { RepositoryRestMvcAutoConfiguration.class })
@EnableSpringDataWebSupport @EnableSpringDataWebSupport
@Import({ NoSecurityConfiguration.class, FeignClientsConfiguration.class }) @Import({ NoSecurityConfiguration.class })
public static class Application { public static class Application {
} }
@@ -19,10 +19,12 @@ package org.springframework.cloud.openfeign.encoding.app.client;
import java.util.List; import java.util.List;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.cloud.openfeign.encoding.app.domain.Invoice; import org.springframework.cloud.openfeign.encoding.app.domain.Invoice;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
@@ -30,6 +32,7 @@ import org.springframework.web.bind.annotation.RequestMethod;
* Simple Feign client for retrieving the invoice list. * Simple Feign client for retrieving the invoice list.
* *
* @author Jakub Narloch * @author Jakub Narloch
* @author Hyeonmin Park
*/ */
@FeignClient("local") @FeignClient("local")
public interface InvoiceClient { public interface InvoiceClient {
@@ -39,6 +42,20 @@ public interface InvoiceClient {
ResponseEntity<Page<Invoice>> getInvoicesPaged( ResponseEntity<Page<Invoice>> getInvoicesPaged(
org.springframework.data.domain.Pageable pageable); org.springframework.data.domain.Pageable pageable);
@RequestMapping(value = "invoicesPagedWithBody", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<Page<Invoice>> getInvoicesPagedWithBody(
@SpringQueryMap org.springframework.data.domain.Pageable pageable,
@RequestBody String titlePrefix);
@RequestMapping(value = "invoicesSortedWithBody", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<Page<Invoice>> getInvoicesSortedWithBody(
@SpringQueryMap org.springframework.data.domain.Sort sort,
@RequestBody String titlePrefix);
@RequestMapping(value = "invoices", method = RequestMethod.GET, @RequestMapping(value = "invoices", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE) produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<List<Invoice>> getInvoices(); ResponseEntity<List<Invoice>> getInvoices();
@@ -18,12 +18,14 @@ package org.springframework.cloud.openfeign.encoding.app.resource;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import org.springframework.cloud.openfeign.encoding.app.domain.Invoice; import org.springframework.cloud.openfeign.encoding.app.domain.Invoice;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
@@ -35,6 +37,7 @@ import org.springframework.web.bind.annotation.RestController;
* An sample REST controller, that potentially returns large response - used for testing. * An sample REST controller, that potentially returns large response - used for testing.
* *
* @author Jakub Narloch * @author Jakub Narloch
* @author Hyeonmin Park
*/ */
@RestController @RestController
public class InvoiceResource { public class InvoiceResource {
@@ -43,7 +46,7 @@ public class InvoiceResource {
produces = MediaType.APPLICATION_JSON_VALUE) produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Invoice>> getInvoices() { public ResponseEntity<List<Invoice>> getInvoices() {
return ResponseEntity.ok(createInvoiceList(100)); return ResponseEntity.ok(createInvoiceList(null, 100, null));
} }
@RequestMapping(value = "invoices", method = RequestMethod.POST, @RequestMapping(value = "invoices", method = RequestMethod.POST,
@@ -58,20 +61,76 @@ public class InvoiceResource {
produces = MediaType.APPLICATION_JSON_VALUE) produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Page<Invoice>> getInvoicesPaged( public ResponseEntity<Page<Invoice>> getInvoicesPaged(
org.springframework.data.domain.Pageable pageable) { org.springframework.data.domain.Pageable pageable) {
Page<Invoice> page = new PageImpl<>(createInvoiceList(pageable.getPageSize()), Page<Invoice> page = new PageImpl<>(
createInvoiceList(null, pageable.getPageSize(), pageable.getSort()),
pageable, 100); pageable, 100);
return ResponseEntity.ok(page); return ResponseEntity.ok(page);
} }
private List<Invoice> createInvoiceList(int count) { @RequestMapping(value = "invoicesPagedWithBody", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Page<Invoice>> getInvoicesPagedWithBody(
org.springframework.data.domain.Pageable pageable,
@RequestBody String titlePrefix) {
Page<Invoice> page = new PageImpl<>(createInvoiceList(titlePrefix,
pageable.getPageSize(), pageable.getSort()), pageable, 100);
return ResponseEntity.ok(page);
}
@RequestMapping(value = "invoicesSortedWithBody", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Page<Invoice>> getInvoicesSortedWithBody(
org.springframework.data.domain.Sort sort, @RequestBody String titlePrefix) {
Page<Invoice> page = new PageImpl<>(createInvoiceList(titlePrefix, 100, sort),
PageRequest.of(0, 100, sort), 100);
return ResponseEntity.ok(page);
}
private List<Invoice> createInvoiceList(String titlePrefix, int count,
org.springframework.data.domain.Sort sort) {
if (titlePrefix == null) {
titlePrefix = "Invoice";
}
final List<Invoice> invoices = new ArrayList<>(); final List<Invoice> invoices = new ArrayList<>();
for (int ind = 0; ind < count; ind++) { for (int ind = 0; ind < count; ind++) {
final Invoice invoice = new Invoice(); final Invoice invoice = new Invoice();
invoice.setTitle("Invoice " + (ind + 1)); invoice.setTitle(titlePrefix + " " + (ind + 1));
invoice.setAmount(new BigDecimal( invoice.setAmount(new BigDecimal(
String.format(Locale.US, "%.2f", Math.random() * 1000))); String.format(Locale.US, "%.2f", Math.random() * 1000)));
invoices.add(invoice); invoices.add(invoice);
} }
if (sort != null) {
Comparator<Invoice> comparatorForSort = null;
for (org.springframework.data.domain.Sort.Order order : sort) {
Comparator<Invoice> comparatorForOrder;
if (order.getProperty().equals("title")) {
comparatorForOrder = Comparator.comparing(Invoice::getTitle);
}
else if (order.getProperty().equals("amount")) {
comparatorForOrder = Comparator.comparing(Invoice::getAmount);
}
else {
continue;
}
if (order.isDescending()) {
comparatorForOrder = comparatorForOrder.reversed();
}
if (comparatorForSort == null) {
comparatorForSort = comparatorForOrder;
}
else {
comparatorForSort = comparatorForSort
.thenComparing(comparatorForOrder);
}
}
if (comparatorForSort != null) {
invoices.sort(comparatorForSort);
}
}
return invoices; return invoices;
} }
@@ -20,7 +20,6 @@ import feign.RequestTemplate;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder; import org.springframework.cloud.openfeign.support.SpringEncoder;
@@ -41,12 +40,8 @@ public class ProtobufNotInClasspathTest {
@Test @Test
public void testEncodeWhenProtobufNotInClasspath() { public void testEncodeWhenProtobufNotInClasspath() {
ObjectFactory<HttpMessageConverters> converters = new ObjectFactory<HttpMessageConverters>() { ObjectFactory<HttpMessageConverters> converters = () -> new HttpMessageConverters(
@Override new StringHttpMessageConverter());
public HttpMessageConverters getObject() throws BeansException {
return new HttpMessageConverters(new StringHttpMessageConverter());
}
};
RequestTemplate requestTemplate = new RequestTemplate(); RequestTemplate requestTemplate = new RequestTemplate();
requestTemplate.method(POST); requestTemplate.method(POST);
new SpringEncoder(converters).encode("a=b", String.class, requestTemplate); new SpringEncoder(converters).encode("a=b", String.class, requestTemplate);
@@ -40,11 +40,9 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers; import org.mockito.ArgumentMatchers;
import org.mockito.BDDMockito; import org.mockito.BDDMockito;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder; import org.springframework.cloud.openfeign.support.SpringEncoder;
@@ -73,7 +71,7 @@ public class ProtobufSpringEncoderTest {
.build(); .build();
@Test @Test
public void testProtobuf() throws IOException, URISyntaxException { public void testProtobuf() throws IOException {
// protobuf convert to request by feign and ProtobufHttpMessageConverter // protobuf convert to request by feign and ProtobufHttpMessageConverter
RequestTemplate requestTemplate = newRequestTemplate(); RequestTemplate requestTemplate = newRequestTemplate();
newEncoder().encode(this.request, Request.class, requestTemplate); newEncoder().encode(this.request, Request.class, requestTemplate);
@@ -110,12 +108,8 @@ public class ProtobufSpringEncoderTest {
} }
private SpringEncoder newEncoder() { private SpringEncoder newEncoder() {
ObjectFactory<HttpMessageConverters> converters = new ObjectFactory<HttpMessageConverters>() { ObjectFactory<HttpMessageConverters> converters = () -> new HttpMessageConverters(
@Override new ProtobufHttpMessageConverter());
public HttpMessageConverters getObject() throws BeansException {
return new HttpMessageConverters(new ProtobufHttpMessageConverter());
}
};
return new SpringEncoder(converters); return new SpringEncoder(converters);
} }
@@ -126,17 +120,13 @@ public class ProtobufSpringEncoderTest {
} }
private HttpEntity toApacheHttpEntity(RequestTemplate requestTemplate) private HttpEntity toApacheHttpEntity(RequestTemplate requestTemplate)
throws IOException, URISyntaxException { throws IOException {
final List<HttpUriRequest> request = new ArrayList<>(1); final List<HttpUriRequest> request = new ArrayList<>(1);
BDDMockito.given(this.httpClient.execute(ArgumentMatchers.<HttpUriRequest>any())) BDDMockito.given(this.httpClient.execute(ArgumentMatchers.any()))
.will(new Answer<HttpResponse>() { .will((Answer<HttpResponse>) invocationOnMock -> {
@Override request.add((HttpUriRequest) invocationOnMock.getArguments()[0]);
public HttpResponse answer(InvocationOnMock invocationOnMock) return new BasicHttpResponse(new BasicStatusLine(
throws Throwable { new ProtocolVersion("http", 1, 1), 200, null));
request.add((HttpUriRequest) invocationOnMock.getArguments()[0]);
return new BasicHttpResponse(new BasicStatusLine(
new ProtocolVersion("http", 1, 1), 200, null));
}
}); });
new ApacheHttpClient(this.httpClient).execute( new ApacheHttpClient(this.httpClient).execute(
requestTemplate.resolve(new HashMap<>()).request(), requestTemplate.resolve(new HashMap<>()).request(),
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@ package org.springframework.cloud.openfeign.loadbalancer;
import java.util.Map; import java.util.Map;
import feign.Client; import feign.Client;
import feign.hc5.ApacheHttp5Client;
import feign.httpclient.ApacheHttpClient; import feign.httpclient.ApacheHttpClient;
import feign.okhttp.OkHttpClient; import feign.okhttp.OkHttpClient;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -38,6 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat;
/** /**
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh
*/ */
class FeignLoadBalancerAutoConfigurationTests { class FeignLoadBalancerAutoConfigurationTests {
@@ -73,6 +75,30 @@ class FeignLoadBalancerAutoConfigurationTests {
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class); assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
} }
@Test
void shouldInstantiateHttpFeignClient5WhenEnabled() {
ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false",
"feign.httpclient.enabled=false", "feign.okhttp.enabled=false",
"feign.httpclient.hc5.enabled=true",
"spring.cloud.loadbalancer.retry.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalanced(context, ApacheHttp5Client.class);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
}
@Test
void shouldInstantiateHttpFeignClient5WhenBothHttpClientAndHttpClient5Enabled() {
ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false",
"feign.httpclient.enabled=true", "feign.okhttp.enabled=false",
"feign.httpclient.hc5.enabled=true",
"spring.cloud.loadbalancer.retry.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalanced(context, ApacheHttp5Client.class);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
}
@Test @Test
void shouldInstantiateRetryableDefaultFeignBlockingLoadBalancerClientWhenHttpClientDisabled() { void shouldInstantiateRetryableDefaultFeignBlockingLoadBalancerClientWhenHttpClientDisabled() {
ConfigurableApplicationContext context = initContext( ConfigurableApplicationContext context = initContext(
@@ -102,6 +128,28 @@ class FeignLoadBalancerAutoConfigurationTests {
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class); assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
} }
@Test
void shouldInstantiateRetryableHttpFeignClient5WhenEnabled() {
ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false",
"feign.httpclient.enabled=false", "feign.okhttp.enabled=false",
"feign.httpclient.hc5.enabled=true");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalancedWithRetries(context, ApacheHttp5Client.class);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
}
@Test
void shouldInstantiateRetryableHttpFeignClient5WhenBothHttpClientAndHttpClient5Enabled() {
ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false",
"feign.httpclient.enabled=true", "feign.okhttp.enabled=false",
"feign.httpclient.hc5.enabled=true");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalancedWithRetries(context, ApacheHttp5Client.class);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
}
@Test @Test
void shouldNotProcessLoadBalancerConfigurationWhenRibbonEnabled() { void shouldNotProcessLoadBalancerConfigurationWhenRibbonEnabled() {
ConfigurableApplicationContext context = initContext( ConfigurableApplicationContext context = initContext(
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -44,6 +44,7 @@ import org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer.RibbonReques
import org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer.RibbonResponse; import org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer.RibbonResponse;
import static com.netflix.client.config.CommonClientConfigKey.ConnectTimeout; import static com.netflix.client.config.CommonClientConfigKey.ConnectTimeout;
import static com.netflix.client.config.CommonClientConfigKey.FollowRedirects;
import static com.netflix.client.config.CommonClientConfigKey.IsSecure; import static com.netflix.client.config.CommonClientConfigKey.IsSecure;
import static com.netflix.client.config.CommonClientConfigKey.MaxAutoRetries; import static com.netflix.client.config.CommonClientConfigKey.MaxAutoRetries;
import static com.netflix.client.config.CommonClientConfigKey.MaxAutoRetriesNextServer; import static com.netflix.client.config.CommonClientConfigKey.MaxAutoRetriesNextServer;
@@ -71,53 +72,47 @@ public class FeignLoadBalancerTests {
private FeignLoadBalancer feignLoadBalancer; private FeignLoadBalancer feignLoadBalancer;
private ServerIntrospector inspector = new DefaultServerIntrospector(); private final ServerIntrospector inspector = new DefaultServerIntrospector();
private Integer defaultConnectTimeout = 10000;
private Integer defaultReadTimeout = 10000;
@Before @Before
public void setup() { public void setup() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
when(this.config.get(MaxAutoRetries, DEFAULT_MAX_AUTO_RETRIES)).thenReturn(1); when(config.get(MaxAutoRetries, DEFAULT_MAX_AUTO_RETRIES)).thenReturn(1);
when(this.config.get(MaxAutoRetriesNextServer, when(config.get(MaxAutoRetriesNextServer, DEFAULT_MAX_AUTO_RETRIES_NEXT_SERVER))
DEFAULT_MAX_AUTO_RETRIES_NEXT_SERVER)).thenReturn(1); .thenReturn(1);
when(this.config.get(OkToRetryOnAllOperations, eq(anyBoolean()))) when(config.get(OkToRetryOnAllOperations, eq(anyBoolean()))).thenReturn(true);
.thenReturn(true); when(config.get(ConnectTimeout)).thenReturn(10000);
when(this.config.get(ConnectTimeout)).thenReturn(this.defaultConnectTimeout); when(config.get(ReadTimeout)).thenReturn(10000);
when(this.config.get(ReadTimeout)).thenReturn(this.defaultReadTimeout); when(config.get(eq(FollowRedirects), any())).thenReturn(true);
when(this.config.get(OkToRetryOnAllOperations, false)).thenReturn(true); when(config.get(OkToRetryOnAllOperations, false)).thenReturn(true);
} }
@Test @Test
public void testUriInsecure() throws Exception { public void testUriInsecure() throws Exception {
when(this.config.get(IsSecure)).thenReturn(false); when(config.get(IsSecure)).thenReturn(false);
this.feignLoadBalancer = new FeignLoadBalancer(this.lb, this.config, feignLoadBalancer = new FeignLoadBalancer(lb, config, inspector);
this.inspector);
Request request = new RequestTemplate().method(GET).target("https://foo/") Request request = new RequestTemplate().method(GET).target("https://foo/")
.resolve(new HashMap<>()).request(); .resolve(new HashMap<>()).request();
RibbonRequest ribbonRequest = new RibbonRequest(this.delegate, request, RibbonRequest ribbonRequest = new RibbonRequest(delegate, request,
new URI(request.url())); new URI(request.url()));
Response response = Response.builder().request(request).status(200).reason("Test") Response response = Response.builder().request(request).status(200).reason("Test")
.headers(Collections.emptyMap()).body(new byte[0]).build(); .headers(Collections.emptyMap()).body(new byte[0]).build();
when(this.delegate.execute(any(Request.class), any(Options.class))) when(delegate.execute(any(Request.class), any(Options.class)))
.thenReturn(response); .thenReturn(response);
RibbonResponse resp = this.feignLoadBalancer.execute(ribbonRequest, null); RibbonResponse resp = feignLoadBalancer.execute(ribbonRequest, null);
assertThat(resp.getRequestedURI()).isEqualTo(new URI("https://foo")); assertThat(resp.getRequestedURI()).isEqualTo(new URI("https://foo"));
} }
@Test @Test
public void testSecureUriFromClientConfig() throws Exception { public void testSecureUriFromClientConfig() throws Exception {
when(this.config.get(IsSecure)).thenReturn(true); when(config.get(IsSecure)).thenReturn(true);
this.feignLoadBalancer = new FeignLoadBalancer(this.lb, this.config, feignLoadBalancer = new FeignLoadBalancer(lb, config, inspector);
this.inspector);
Server server = new Server("foo", 7777); Server server = new Server("foo", 7777);
URI uri = this.feignLoadBalancer.reconstructURIWithServer(server, URI uri = feignLoadBalancer.reconstructURIWithServer(server,
new URI("https://foo/")); new URI("https://foo/"));
assertThat(uri).isEqualTo(new URI("https://foo:7777/")); assertThat(uri).isEqualTo(new URI("https://foo:7777/"));
} }
@@ -125,33 +120,31 @@ public class FeignLoadBalancerTests {
@Test @Test
public void testInsecureUriFromInsecureClientConfigToSecureServerIntrospector() public void testInsecureUriFromInsecureClientConfigToSecureServerIntrospector()
throws Exception { throws Exception {
when(this.config.get(IsSecure)).thenReturn(false); when(config.get(IsSecure)).thenReturn(false);
this.feignLoadBalancer = new FeignLoadBalancer(this.lb, this.config, feignLoadBalancer = new FeignLoadBalancer(lb, config, new ServerIntrospector() {
new ServerIntrospector() { @Override
@Override public boolean isSecure(Server server) {
public boolean isSecure(Server server) { return true;
return true; }
}
@Override @Override
public Map<String, String> getMetadata(Server server) { public Map<String, String> getMetadata(Server server) {
return null; return null;
} }
}); });
Server server = new Server("foo", 7777); Server server = new Server("foo", 7777);
URI uri = this.feignLoadBalancer.reconstructURIWithServer(server, URI uri = feignLoadBalancer.reconstructURIWithServer(server,
new URI("https://foo/")); new URI("https://foo/"));
assertThat(uri).isEqualTo(new URI("https://foo:7777/")); assertThat(uri).isEqualTo(new URI("https://foo:7777/"));
} }
@Test @Test
public void testSecureUriFromClientConfigOverride() throws Exception { public void testSecureUriFromClientConfigOverride() throws Exception {
this.feignLoadBalancer = new FeignLoadBalancer(this.lb, this.config, feignLoadBalancer = new FeignLoadBalancer(lb, config, inspector);
this.inspector);
Server server = Mockito.mock(Server.class); Server server = Mockito.mock(Server.class);
when(server.getPort()).thenReturn(443); when(server.getPort()).thenReturn(443);
when(server.getHost()).thenReturn("foo"); when(server.getHost()).thenReturn("foo");
URI uri = this.feignLoadBalancer.reconstructURIWithServer(server, URI uri = feignLoadBalancer.reconstructURIWithServer(server,
new URI("https://bar/")); new URI("https://bar/"));
assertThat(uri).isEqualTo(new URI("https://foo:443/")); assertThat(uri).isEqualTo(new URI("https://foo:443/"));
} }
@@ -163,7 +156,7 @@ public class FeignLoadBalancerTests {
assertThat(request.url()).isEqualTo(url); assertThat(request.url()).isEqualTo(url);
RibbonRequest ribbonRequest = new RibbonRequest(this.delegate, request, RibbonRequest ribbonRequest = new RibbonRequest(delegate, request,
new URI(request.url())); new URI(request.url()));
Request cloneRequest = ribbonRequest.toRequest(); Request cloneRequest = ribbonRequest.toRequest();
@@ -174,7 +167,7 @@ public class FeignLoadBalancerTests {
@Test @Test
public void testOverrideFeignLoadBalancer() throws Exception { public void testOverrideFeignLoadBalancer() throws Exception {
when(this.config.get(IsSecure)).thenReturn(false); when(config.get(IsSecure)).thenReturn(false);
Server server1 = new Server("foo", 6666); Server server1 = new Server("foo", 6666);
Server server2 = new Server("foo", 7777); Server server2 = new Server("foo", 7777);
BaseLoadBalancer baseLoadBalancer = new BaseLoadBalancer(); BaseLoadBalancer baseLoadBalancer = new BaseLoadBalancer();
@@ -185,8 +178,7 @@ public class FeignLoadBalancerTests {
} }
}); });
this.feignLoadBalancer = new FeignLoadBalancer(baseLoadBalancer, this.config, feignLoadBalancer = new FeignLoadBalancer(baseLoadBalancer, config, inspector) {
this.inspector) {
protected void customizeLoadBalancerCommandBuilder( protected void customizeLoadBalancerCommandBuilder(
final FeignLoadBalancer.RibbonRequest request, final FeignLoadBalancer.RibbonRequest request,
final IClientConfig config, final IClientConfig config,
@@ -196,13 +188,13 @@ public class FeignLoadBalancerTests {
}; };
Request request = new RequestTemplate().method(GET).resolve(new HashMap<>()) Request request = new RequestTemplate().method(GET).resolve(new HashMap<>())
.request(); .request();
RibbonResponse resp = this.feignLoadBalancer.executeWithLoadBalancer( RibbonResponse resp = feignLoadBalancer.executeWithLoadBalancer(
new RibbonRequest(this.delegate, request, new URI(request.url())), null); new RibbonRequest(delegate, request, new URI(request.url())), null);
assertThat(resp.getRequestedURI().getPort()).isEqualTo(7777); assertThat(resp.getRequestedURI().getPort()).isEqualTo(7777);
request = new RequestTemplate().method(GET).header("c_ip", "666") request = new RequestTemplate().method(GET).header("c_ip", "666")
.resolve(new HashMap<>()).request(); .resolve(new HashMap<>()).request();
resp = this.feignLoadBalancer.executeWithLoadBalancer( resp = feignLoadBalancer.executeWithLoadBalancer(
new RibbonRequest(this.delegate, request, new URI(request.url())), null); new RibbonRequest(delegate, request, new URI(request.url())), null);
assertThat(resp.getRequestedURI().getPort()).isEqualTo(6666); assertThat(resp.getRequestedURI().getPort()).isEqualTo(6666);
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -50,9 +50,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
webEnvironment = RANDOM_PORT, webEnvironment = RANDOM_PORT,
value = { "spring.application.name=feignribbonclientpathtest", value = { "spring.application.name=feignribbonclientpathtest",
"feign.okhttp.enabled=false", "feign.httpclient.enabled=false", "feign.okhttp.enabled=false", "feign.httpclient.enabled=false",
"feign.hystrix.enabled=false", "test.path.prefix=/base/path" // For "feign.hystrix.enabled=false", "feign.httpclient.hc5.enabled=false",
// pathWithPlaceholder "test.path.prefix=/base/path" // For pathWithPlaceholder test
// test
}) })
@DirtiesContext @DirtiesContext
public class FeignRibbonClientPathTests { public class FeignRibbonClientPathTests {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -56,7 +56,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
webEnvironment = RANDOM_PORT, webEnvironment = RANDOM_PORT,
value = { "spring.application.name=feignclientretrytest", value = { "spring.application.name=feignclientretrytest",
"feign.okhttp.enabled=false", "feign.httpclient.enabled=false", "feign.okhttp.enabled=false", "feign.httpclient.enabled=false",
"feign.hystrix.enabled=false", "localapp.ribbon.MaxAutoRetries=2", "feign.hystrix.enabled=false", "feign.httpclient.hc5.enabled=false",
"localapp.ribbon.MaxAutoRetries=2",
"localapp.ribbon.MaxAutoRetriesNextServer=3" }) "localapp.ribbon.MaxAutoRetriesNextServer=3" })
@DirtiesContext @DirtiesContext
public class FeignRibbonClientRetryTests { public class FeignRibbonClientRetryTests {
@@ -0,0 +1,112 @@
/*
* Copyright 2013-2021 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
*
* https://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.openfeign.ribbon;
import java.lang.reflect.Field;
import javax.net.ssl.SSLContextSpi;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import feign.Client;
import feign.hc5.ApacheHttp5Client;
import org.apache.hc.client5.http.impl.io.DefaultHttpClientConnectionOperator;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http.config.Lookup;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Nguyen Ky Thanh
*/
@SpringBootTest(
classes = FeignRibbonHttpClient5ConfigurationTests.FeignRibbonHttpClientConfigurationTestsApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = { "feign.httpclient.disableSslValidation=true",
"feign.httpclient.hc5.enabled=true", "feign.httpclient.enabled=false" })
@DirtiesContext
class FeignRibbonHttpClient5ConfigurationTests {
@Autowired
private HttpClientConnectionManager connectionManager;
@Autowired
private Client client;
@Test
void disableSslTest() throws Exception {
Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(
connectionManager);
assertThat(socketFactoryRegistry.lookup(URIScheme.HTTPS.id)).isNotNull();
assertThat(getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers())
.isNull();
}
@Test
void verifyHttpClient5IsPickedUp() {
assertThat(client).isInstanceOf(LoadBalancerFeignClient.class);
Client delegate = (Client) getField(client, "delegate");
assertThat(delegate).isInstanceOf(ApacheHttp5Client.class);
}
private Lookup<ConnectionSocketFactory> getConnectionSocketFactoryLookup(
HttpClientConnectionManager connectionManager) {
DefaultHttpClientConnectionOperator connectionOperator = (DefaultHttpClientConnectionOperator) this
.getField(connectionManager, "connectionOperator");
return (Lookup) getField(connectionOperator, "socketFactoryRegistry");
}
private X509TrustManager getX509TrustManager(
Lookup<ConnectionSocketFactory> socketFactoryRegistry) {
ConnectionSocketFactory connectionSocketFactory = (ConnectionSocketFactory) socketFactoryRegistry
.lookup(URIScheme.HTTPS.id);
SSLSocketFactory sslSocketFactory = (SSLSocketFactory) this
.getField(connectionSocketFactory, "socketFactory");
SSLContextSpi sslContext = (SSLContextSpi) getField(sslSocketFactory, "context");
return (X509TrustManager) getField(sslContext, "trustManager");
}
protected <T> Object getField(Object target, String name) {
Field field = ReflectionUtils.findField(target.getClass(), name);
ReflectionUtils.makeAccessible(field);
Object value = ReflectionUtils.getField(field, target);
return value;
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
static class FeignRibbonHttpClientConfigurationTestsApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(FeignRibbonClientRetryTests.Application.class)
.run(args);
}
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -59,6 +59,7 @@ import org.springframework.retry.backoff.BackOffInterruptedException;
import org.springframework.retry.backoff.BackOffPolicy; import org.springframework.retry.backoff.BackOffPolicy;
import static com.netflix.client.config.CommonClientConfigKey.ConnectTimeout; import static com.netflix.client.config.CommonClientConfigKey.ConnectTimeout;
import static com.netflix.client.config.CommonClientConfigKey.FollowRedirects;
import static com.netflix.client.config.CommonClientConfigKey.MaxAutoRetries; import static com.netflix.client.config.CommonClientConfigKey.MaxAutoRetries;
import static com.netflix.client.config.CommonClientConfigKey.MaxAutoRetriesNextServer; import static com.netflix.client.config.CommonClientConfigKey.MaxAutoRetriesNextServer;
import static com.netflix.client.config.CommonClientConfigKey.OkToRetryOnAllOperations; import static com.netflix.client.config.CommonClientConfigKey.OkToRetryOnAllOperations;
@@ -92,29 +93,28 @@ public class RetryableFeignLoadBalancerTests {
@Mock @Mock
private IClientConfig config; private IClientConfig config;
private ServerIntrospector inspector = new DefaultServerIntrospector(); private final ServerIntrospector inspector = new DefaultServerIntrospector();
private Integer defaultConnectTimeout = 10000; private final Integer defaultConnectTimeout = 10000;
private Integer defaultReadTimeout = 10000; private final Integer defaultReadTimeout = 10000;
@Before @Before
public void setup() { public void setup() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
when(this.config.get(MaxAutoRetries, DEFAULT_MAX_AUTO_RETRIES)).thenReturn(1); when(config.get(MaxAutoRetries, DEFAULT_MAX_AUTO_RETRIES)).thenReturn(1);
when(this.config.get(MaxAutoRetriesNextServer, when(config.get(MaxAutoRetriesNextServer, DEFAULT_MAX_AUTO_RETRIES_NEXT_SERVER))
DEFAULT_MAX_AUTO_RETRIES_NEXT_SERVER)).thenReturn(1); .thenReturn(1);
when(this.config.get(OkToRetryOnAllOperations, eq(anyBoolean()))) when(config.get(OkToRetryOnAllOperations, eq(anyBoolean()))).thenReturn(true);
.thenReturn(true); when(config.get(ConnectTimeout)).thenReturn(defaultConnectTimeout);
when(this.config.get(ConnectTimeout)).thenReturn(this.defaultConnectTimeout); when(config.get(ReadTimeout)).thenReturn(defaultReadTimeout);
when(this.config.get(ReadTimeout)).thenReturn(this.defaultReadTimeout); when(config.get(OkToRetryOnAllOperations, false)).thenReturn(true);
when(this.config.get(OkToRetryOnAllOperations, false)).thenReturn(true); when(config.get(eq(FollowRedirects), any())).thenReturn(true);
} }
@Test @Test
public void executeNoFailure() throws Exception { public void executeNoFailure() throws Exception {
RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(this.lb, RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(lb, config);
this.config);
SpringClientFactory clientFactory = mock(SpringClientFactory.class); SpringClientFactory clientFactory = mock(SpringClientFactory.class);
doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class)); doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class));
IClientConfig config = mock(IClientConfig.class); IClientConfig config = mock(IClientConfig.class);
@@ -123,9 +123,9 @@ public class RetryableFeignLoadBalancerTests {
anyInt()); anyInt());
doReturn(true).when(config) doReturn(true).when(config)
.get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false));
doReturn(this.defaultConnectTimeout).when(config) doReturn(defaultConnectTimeout).when(config)
.get(eq(CommonClientConfigKey.ConnectTimeout)); .get(eq(CommonClientConfigKey.ConnectTimeout));
doReturn(this.defaultReadTimeout).when(config) doReturn(defaultReadTimeout).when(config)
.get(eq(CommonClientConfigKey.ReadTimeout)); .get(eq(CommonClientConfigKey.ReadTimeout));
doReturn("404,502,foo, ,").when(config).getPropertyAsString( doReturn("404,502,foo, ,").when(config).getPropertyAsString(
eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq(""));
@@ -141,8 +141,9 @@ public class RetryableFeignLoadBalancerTests {
.headers(new HashMap<>()).build(); .headers(new HashMap<>()).build();
doReturn(response).when(client).execute(any(Request.class), doReturn(response).when(client).execute(any(Request.class),
any(Request.Options.class)); any(Request.Options.class));
RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(this.lb, when(config.get(eq(FollowRedirects), any())).thenReturn(true);
config, this.inspector, loadBalancedRetryFactory); RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(lb, config,
inspector, loadBalancedRetryFactory);
FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null); FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null);
assertThat(ribbonResponse.toResponse().status()).isEqualTo(200); assertThat(ribbonResponse.toResponse().status()).isEqualTo(200);
verify(client, times(1)).execute(any(Request.class), any(Request.Options.class)); verify(client, times(1)).execute(any(Request.class), any(Request.Options.class));
@@ -157,8 +158,8 @@ public class RetryableFeignLoadBalancerTests {
client, feignRequest, new URI("https://foo")); client, feignRequest, new URI("https://foo"));
doThrow(new IOException("boom")).when(client).execute(any(Request.class), doThrow(new IOException("boom")).when(client).execute(any(Request.class),
any(Request.Options.class)); any(Request.Options.class));
RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(this.lb, RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(lb, config,
this.config, this.inspector, new LoadBalancedRetryFactory() { inspector, new LoadBalancedRetryFactory() {
@Override @Override
public LoadBalancedRetryPolicy createRetryPolicy(String s, public LoadBalancedRetryPolicy createRetryPolicy(String s,
ServiceInstanceChooser serviceInstanceChooser) { ServiceInstanceChooser serviceInstanceChooser) {
@@ -189,8 +190,7 @@ public class RetryableFeignLoadBalancerTests {
@Test @Test
public void executeRetry() throws Exception { public void executeRetry() throws Exception {
RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(this.lb, RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(lb, config);
this.config);
SpringClientFactory clientFactory = mock(SpringClientFactory.class); SpringClientFactory clientFactory = mock(SpringClientFactory.class);
IClientConfig config = mock(IClientConfig.class); IClientConfig config = mock(IClientConfig.class);
doReturn(1).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); doReturn(1).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt());
@@ -198,14 +198,15 @@ public class RetryableFeignLoadBalancerTests {
anyInt()); anyInt());
doReturn(true).when(config) doReturn(true).when(config)
.get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false));
doReturn(this.defaultConnectTimeout).when(config) doReturn(defaultConnectTimeout).when(config)
.get(eq(CommonClientConfigKey.ConnectTimeout)); .get(eq(CommonClientConfigKey.ConnectTimeout));
doReturn(this.defaultReadTimeout).when(config) doReturn(defaultReadTimeout).when(config)
.get(eq(CommonClientConfigKey.ReadTimeout)); .get(eq(CommonClientConfigKey.ReadTimeout));
doReturn("").when(config).getPropertyAsString( doReturn("").when(config).getPropertyAsString(
eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq(""));
doReturn(config).when(clientFactory).getClientConfig(eq("default")); doReturn(config).when(clientFactory).getClientConfig(eq("default"));
doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class)); doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class));
when(config.get(eq(FollowRedirects), any())).thenReturn(true);
MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); MyBackOffPolicy backOffPolicy = new MyBackOffPolicy();
RibbonLoadBalancedRetryFactory loadBalancedRetryFactory = new RibbonLoadBalancedRetryFactory( RibbonLoadBalancedRetryFactory loadBalancedRetryFactory = new RibbonLoadBalancedRetryFactory(
clientFactory) { clientFactory) {
@@ -224,8 +225,8 @@ public class RetryableFeignLoadBalancerTests {
doThrow(new IOException("boom")).doReturn(response).when(client) doThrow(new IOException("boom")).doReturn(response).when(client)
.execute(any(Request.class), any(Request.Options.class)); .execute(any(Request.class), any(Request.Options.class));
RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(this.lb, RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(lb, config,
config, this.inspector, loadBalancedRetryFactory); inspector, loadBalancedRetryFactory);
FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null); FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null);
assertThat(ribbonResponse.toResponse().status()).isEqualTo(200); assertThat(ribbonResponse.toResponse().status()).isEqualTo(200);
verify(client, times(2)).execute(any(Request.class), any(Request.Options.class)); verify(client, times(2)).execute(any(Request.class), any(Request.Options.class));
@@ -234,8 +235,7 @@ public class RetryableFeignLoadBalancerTests {
@Test @Test
public void executeRetryOnStatusCode() throws Exception { public void executeRetryOnStatusCode() throws Exception {
RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(this.lb, RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(lb, config);
this.config);
SpringClientFactory clientFactory = mock(SpringClientFactory.class); SpringClientFactory clientFactory = mock(SpringClientFactory.class);
IClientConfig config = mock(IClientConfig.class); IClientConfig config = mock(IClientConfig.class);
doReturn(1).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); doReturn(1).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt());
@@ -243,9 +243,9 @@ public class RetryableFeignLoadBalancerTests {
anyInt()); anyInt());
doReturn(true).when(config) doReturn(true).when(config)
.get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false));
doReturn(this.defaultConnectTimeout).when(config) doReturn(defaultConnectTimeout).when(config)
.get(eq(CommonClientConfigKey.ConnectTimeout)); .get(eq(CommonClientConfigKey.ConnectTimeout));
doReturn(this.defaultReadTimeout).when(config) doReturn(defaultReadTimeout).when(config)
.get(eq(CommonClientConfigKey.ReadTimeout)); .get(eq(CommonClientConfigKey.ReadTimeout));
doReturn("404").when(config).getPropertyAsString( doReturn("404").when(config).getPropertyAsString(
eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq(""));
@@ -270,8 +270,9 @@ public class RetryableFeignLoadBalancerTests {
.headers(new HashMap<>()).build(); .headers(new HashMap<>()).build();
doReturn(fourOFourResponse).doReturn(response).when(client) doReturn(fourOFourResponse).doReturn(response).when(client)
.execute(any(Request.class), any(Request.Options.class)); .execute(any(Request.class), any(Request.Options.class));
RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(this.lb, when(config.get(eq(FollowRedirects), any())).thenReturn(true);
config, this.inspector, loadBalancedRetryFactory); RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(lb, config,
inspector, loadBalancedRetryFactory);
FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null); FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null);
assertThat(ribbonResponse.toResponse().status()).isEqualTo(200); assertThat(ribbonResponse.toResponse().status()).isEqualTo(200);
verify(client, times(2)).execute(any(Request.class), any(Request.Options.class)); verify(client, times(2)).execute(any(Request.class), any(Request.Options.class));
@@ -281,11 +282,10 @@ public class RetryableFeignLoadBalancerTests {
@Test @Test
public void executeRetryOnStatusCodeWithEmptyBody() throws Exception { public void executeRetryOnStatusCodeWithEmptyBody() throws Exception {
int retriesNextServer = 0; int retriesNextServer = 0;
when(this.config.get(MaxAutoRetriesNextServer, when(config.get(MaxAutoRetriesNextServer, DEFAULT_MAX_AUTO_RETRIES_NEXT_SERVER))
DEFAULT_MAX_AUTO_RETRIES_NEXT_SERVER)).thenReturn(retriesNextServer); .thenReturn(retriesNextServer);
doReturn(new Server("foo", 80)).when(this.lb).chooseServer(any()); doReturn(new Server("foo", 80)).when(lb).chooseServer(any());
RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(this.lb, RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(lb, config);
this.config);
SpringClientFactory clientFactory = mock(SpringClientFactory.class); SpringClientFactory clientFactory = mock(SpringClientFactory.class);
IClientConfig config = mock(IClientConfig.class); IClientConfig config = mock(IClientConfig.class);
doReturn(1).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); doReturn(1).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt());
@@ -293,9 +293,9 @@ public class RetryableFeignLoadBalancerTests {
.get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt()); .get(eq(CommonClientConfigKey.MaxAutoRetriesNextServer), anyInt());
doReturn(true).when(config) doReturn(true).when(config)
.get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false));
doReturn(this.defaultConnectTimeout).when(config) doReturn(defaultConnectTimeout).when(config)
.get(eq(CommonClientConfigKey.ConnectTimeout)); .get(eq(CommonClientConfigKey.ConnectTimeout));
doReturn(this.defaultReadTimeout).when(config) doReturn(defaultReadTimeout).when(config)
.get(eq(CommonClientConfigKey.ReadTimeout)); .get(eq(CommonClientConfigKey.ReadTimeout));
doReturn("404").when(config).getPropertyAsString( doReturn("404").when(config).getPropertyAsString(
eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq(""));
@@ -320,8 +320,9 @@ public class RetryableFeignLoadBalancerTests {
.headers(new HashMap<>()).build(); .headers(new HashMap<>()).build();
doReturn(fourOFourResponse).doReturn(response).when(client) doReturn(fourOFourResponse).doReturn(response).when(client)
.execute(any(Request.class), any(Request.Options.class)); .execute(any(Request.class), any(Request.Options.class));
RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(this.lb, when(config.get(eq(FollowRedirects), any())).thenReturn(true);
config, this.inspector, loadBalancedRetryFactory); RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(lb, config,
inspector, loadBalancedRetryFactory);
FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null); FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null);
assertThat(ribbonResponse.toResponse().status()).isEqualTo(404); assertThat(ribbonResponse.toResponse().status()).isEqualTo(404);
assertThat(ribbonResponse.toResponse().body().length()) assertThat(ribbonResponse.toResponse().body().length())
@@ -332,8 +333,7 @@ public class RetryableFeignLoadBalancerTests {
@Test @Test
public void getRequestSpecificRetryHandler() throws Exception { public void getRequestSpecificRetryHandler() throws Exception {
RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(this.lb, RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(lb, config);
this.config);
SpringClientFactory clientFactory = mock(SpringClientFactory.class); SpringClientFactory clientFactory = mock(SpringClientFactory.class);
doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class)); doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class));
RibbonLoadBalancedRetryFactory loadBalancedRetryFactory = new RibbonLoadBalancedRetryFactory( RibbonLoadBalancedRetryFactory loadBalancedRetryFactory = new RibbonLoadBalancedRetryFactory(
@@ -347,10 +347,10 @@ public class RetryableFeignLoadBalancerTests {
.headers(new HashMap<>()).build(); .headers(new HashMap<>()).build();
doReturn(response).when(client).execute(any(Request.class), doReturn(response).when(client).execute(any(Request.class),
any(Request.Options.class)); any(Request.Options.class));
RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(this.lb, RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(lb, config,
this.config, this.inspector, loadBalancedRetryFactory); inspector, loadBalancedRetryFactory);
RequestSpecificRetryHandler retryHandler = feignLb RequestSpecificRetryHandler retryHandler = feignLb
.getRequestSpecificRetryHandler(request, this.config); .getRequestSpecificRetryHandler(request, config);
assertThat(retryHandler.getMaxRetriesOnNextServer()).isEqualTo(1); assertThat(retryHandler.getMaxRetriesOnNextServer()).isEqualTo(1);
assertThat(retryHandler.getMaxRetriesOnSameServer()).isEqualTo(1); assertThat(retryHandler.getMaxRetriesOnSameServer()).isEqualTo(1);
@@ -358,8 +358,7 @@ public class RetryableFeignLoadBalancerTests {
@Test @Test
public void choose() throws Exception { public void choose() throws Exception {
RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(this.lb, RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(lb, config);
this.config);
SpringClientFactory clientFactory = mock(SpringClientFactory.class); SpringClientFactory clientFactory = mock(SpringClientFactory.class);
doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class)); doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class));
RibbonLoadBalancedRetryFactory loadBalancedRetryFactory = new RibbonLoadBalancedRetryFactory( RibbonLoadBalancedRetryFactory loadBalancedRetryFactory = new RibbonLoadBalancedRetryFactory(
@@ -367,8 +366,6 @@ public class RetryableFeignLoadBalancerTests {
Request feignRequest = Request.create(GET, "https://foo", new HashMap<>(), Request feignRequest = Request.create(GET, "https://foo", new HashMap<>(),
new byte[] {}, UTF_8, null); new byte[] {}, UTF_8, null);
Client client = mock(Client.class); Client client = mock(Client.class);
FeignLoadBalancer.RibbonRequest request = new FeignLoadBalancer.RibbonRequest(
client, feignRequest, new URI("https://foo"));
Response response = Response.builder().request(feignRequest).status(200) Response response = Response.builder().request(feignRequest).status(200)
.headers(new HashMap<>()).build(); .headers(new HashMap<>()).build();
doReturn(response).when(client).execute(any(Request.class), doReturn(response).when(client).execute(any(Request.class),
@@ -405,7 +402,7 @@ public class RetryableFeignLoadBalancerTests {
public List<Server> getAllServers() { public List<Server> getAllServers() {
return null; return null;
} }
}, this.config, this.inspector, loadBalancedRetryFactory); }, config, inspector, loadBalancedRetryFactory);
ServiceInstance serviceInstance = feignLb.choose("foo"); ServiceInstance serviceInstance = feignLb.choose("foo");
assertThat(serviceInstance.getHost()).isEqualTo("foo"); assertThat(serviceInstance.getHost()).isEqualTo("foo");
assertThat(serviceInstance.getPort()).isEqualTo(80); assertThat(serviceInstance.getPort()).isEqualTo(80);
@@ -414,8 +411,7 @@ public class RetryableFeignLoadBalancerTests {
@Test @Test
public void retryListenerTest() throws Exception { public void retryListenerTest() throws Exception {
RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(this.lb, RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(lb, config);
this.config);
SpringClientFactory clientFactory = mock(SpringClientFactory.class); SpringClientFactory clientFactory = mock(SpringClientFactory.class);
IClientConfig config = mock(IClientConfig.class); IClientConfig config = mock(IClientConfig.class);
doReturn(1).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); doReturn(1).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt());
@@ -423,14 +419,15 @@ public class RetryableFeignLoadBalancerTests {
anyInt()); anyInt());
doReturn(true).when(config) doReturn(true).when(config)
.get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false));
doReturn(this.defaultConnectTimeout).when(config) doReturn(defaultConnectTimeout).when(config)
.get(eq(CommonClientConfigKey.ConnectTimeout)); .get(eq(CommonClientConfigKey.ConnectTimeout));
doReturn(this.defaultReadTimeout).when(config) doReturn(defaultReadTimeout).when(config)
.get(eq(CommonClientConfigKey.ReadTimeout)); .get(eq(CommonClientConfigKey.ReadTimeout));
doReturn("").when(config).getPropertyAsString( doReturn("").when(config).getPropertyAsString(
eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq(""));
doReturn(config).when(clientFactory).getClientConfig(eq("default")); doReturn(config).when(clientFactory).getClientConfig(eq("default"));
doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class)); doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class));
when(config.get(eq(FollowRedirects), any())).thenReturn(true);
MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); MyBackOffPolicy backOffPolicy = new MyBackOffPolicy();
MyRetryListener myRetryListener = new MyRetryListener(); MyRetryListener myRetryListener = new MyRetryListener();
RibbonLoadBalancedRetryFactory loadBalancedRetryFactory = new RibbonLoadBalancedRetryFactory( RibbonLoadBalancedRetryFactory loadBalancedRetryFactory = new RibbonLoadBalancedRetryFactory(
@@ -455,8 +452,8 @@ public class RetryableFeignLoadBalancerTests {
doThrow(new IOException("boom")).doReturn(response).when(client) doThrow(new IOException("boom")).doReturn(response).when(client)
.execute(any(Request.class), any(Request.Options.class)); .execute(any(Request.class), any(Request.Options.class));
RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(this.lb, RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(lb, config,
config, this.inspector, loadBalancedRetryFactory); inspector, loadBalancedRetryFactory);
FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null); FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null);
assertThat(ribbonResponse.toResponse().status()).isEqualTo(200); assertThat(ribbonResponse.toResponse().status()).isEqualTo(200);
verify(client, times(2)).execute(any(Request.class), any(Request.Options.class)); verify(client, times(2)).execute(any(Request.class), any(Request.Options.class));
@@ -466,8 +463,7 @@ public class RetryableFeignLoadBalancerTests {
@Test(expected = TerminatedRetryException.class) @Test(expected = TerminatedRetryException.class)
public void retryListenerTestNoRetry() throws Exception { public void retryListenerTestNoRetry() throws Exception {
RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(this.lb, RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(lb, config);
this.config);
SpringClientFactory clientFactory = mock(SpringClientFactory.class); SpringClientFactory clientFactory = mock(SpringClientFactory.class);
IClientConfig config = mock(IClientConfig.class); IClientConfig config = mock(IClientConfig.class);
doReturn(1).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); doReturn(1).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt());
@@ -475,14 +471,15 @@ public class RetryableFeignLoadBalancerTests {
anyInt()); anyInt());
doReturn(true).when(config) doReturn(true).when(config)
.get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false));
doReturn(this.defaultConnectTimeout).when(config) doReturn(defaultConnectTimeout).when(config)
.get(eq(CommonClientConfigKey.ConnectTimeout)); .get(eq(CommonClientConfigKey.ConnectTimeout));
doReturn(this.defaultReadTimeout).when(config) doReturn(defaultReadTimeout).when(config)
.get(eq(CommonClientConfigKey.ReadTimeout)); .get(eq(CommonClientConfigKey.ReadTimeout));
doReturn("").when(config).getPropertyAsString( doReturn("").when(config).getPropertyAsString(
eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq(""));
doReturn(config).when(clientFactory).getClientConfig(eq("default")); doReturn(config).when(clientFactory).getClientConfig(eq("default"));
doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class)); doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class));
when(config.get(eq(FollowRedirects), any())).thenReturn(true);
MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); MyBackOffPolicy backOffPolicy = new MyBackOffPolicy();
MyRetryListenerNotRetry myRetryListenerNotRetry = new MyRetryListenerNotRetry(); MyRetryListenerNotRetry myRetryListenerNotRetry = new MyRetryListenerNotRetry();
RibbonLoadBalancedRetryFactory loadBalancedRetryFactory = new RibbonLoadBalancedRetryFactory( RibbonLoadBalancedRetryFactory loadBalancedRetryFactory = new RibbonLoadBalancedRetryFactory(
@@ -502,15 +499,14 @@ public class RetryableFeignLoadBalancerTests {
Client client = mock(Client.class); Client client = mock(Client.class);
FeignLoadBalancer.RibbonRequest request = new FeignLoadBalancer.RibbonRequest( FeignLoadBalancer.RibbonRequest request = new FeignLoadBalancer.RibbonRequest(
client, feignRequest, new URI("https://listener")); client, feignRequest, new URI("https://listener"));
RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(this.lb, RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(lb, config,
config, this.inspector, loadBalancedRetryFactory); inspector, loadBalancedRetryFactory);
FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null); feignLb.execute(request, null);
} }
@Test @Test
public void retryWithDefaultConstructorTest() throws Exception { public void retryWithDefaultConstructorTest() throws Exception {
RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(this.lb, RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(lb, config);
this.config);
SpringClientFactory clientFactory = mock(SpringClientFactory.class); SpringClientFactory clientFactory = mock(SpringClientFactory.class);
IClientConfig config = mock(IClientConfig.class); IClientConfig config = mock(IClientConfig.class);
doReturn(1).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt()); doReturn(1).when(config).get(eq(CommonClientConfigKey.MaxAutoRetries), anyInt());
@@ -518,14 +514,15 @@ public class RetryableFeignLoadBalancerTests {
anyInt()); anyInt());
doReturn(true).when(config) doReturn(true).when(config)
.get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false));
doReturn(this.defaultConnectTimeout).when(config) doReturn(defaultConnectTimeout).when(config)
.get(eq(CommonClientConfigKey.ConnectTimeout)); .get(eq(CommonClientConfigKey.ConnectTimeout));
doReturn(this.defaultReadTimeout).when(config) doReturn(defaultReadTimeout).when(config)
.get(eq(CommonClientConfigKey.ReadTimeout)); .get(eq(CommonClientConfigKey.ReadTimeout));
doReturn("").when(config).getPropertyAsString( doReturn("").when(config).getPropertyAsString(
eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq(""));
doReturn(config).when(clientFactory).getClientConfig(eq("default")); doReturn(config).when(clientFactory).getClientConfig(eq("default"));
doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class)); doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class));
when(config.get(eq(FollowRedirects), any())).thenReturn(true);
MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); MyBackOffPolicy backOffPolicy = new MyBackOffPolicy();
RibbonLoadBalancedRetryFactory loadBalancedRetryPolicyFactory = new RibbonLoadBalancedRetryFactory( RibbonLoadBalancedRetryFactory loadBalancedRetryPolicyFactory = new RibbonLoadBalancedRetryFactory(
clientFactory) { clientFactory) {
@@ -543,8 +540,8 @@ public class RetryableFeignLoadBalancerTests {
.headers(new HashMap<>()).build(); .headers(new HashMap<>()).build();
doThrow(new IOException("boom")).doReturn(response).when(client) doThrow(new IOException("boom")).doReturn(response).when(client)
.execute(any(Request.class), any(Request.Options.class)); .execute(any(Request.class), any(Request.Options.class));
RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(this.lb, RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(lb, config,
config, this.inspector, loadBalancedRetryPolicyFactory); inspector, loadBalancedRetryPolicyFactory);
FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null); FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null);
assertThat(ribbonResponse.toResponse().status()).isEqualTo(200); assertThat(ribbonResponse.toResponse().status()).isEqualTo(200);
verify(client, times(2)).execute(any(Request.class), any(Request.Options.class)); verify(client, times(2)).execute(any(Request.class), any(Request.Options.class));
@@ -553,8 +550,7 @@ public class RetryableFeignLoadBalancerTests {
@Test @Test
public void executeRetryFail() throws Exception { public void executeRetryFail() throws Exception {
RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(this.lb, RibbonLoadBalancerContext lbContext = new RibbonLoadBalancerContext(lb, config);
this.config);
lbContext.setRetryHandler(new DefaultLoadBalancerRetryHandler(1, 0, true)); lbContext.setRetryHandler(new DefaultLoadBalancerRetryHandler(1, 0, true));
SpringClientFactory clientFactory = mock(SpringClientFactory.class); SpringClientFactory clientFactory = mock(SpringClientFactory.class);
IClientConfig config = mock(IClientConfig.class); IClientConfig config = mock(IClientConfig.class);
@@ -563,14 +559,15 @@ public class RetryableFeignLoadBalancerTests {
anyInt()); anyInt());
doReturn(true).when(config) doReturn(true).when(config)
.get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false)); .get(eq(CommonClientConfigKey.OkToRetryOnAllOperations), eq(false));
doReturn(this.defaultConnectTimeout).when(config) doReturn(defaultConnectTimeout).when(config)
.get(eq(CommonClientConfigKey.ConnectTimeout)); .get(eq(CommonClientConfigKey.ConnectTimeout));
doReturn(this.defaultReadTimeout).when(config) doReturn(defaultReadTimeout).when(config)
.get(eq(CommonClientConfigKey.ReadTimeout)); .get(eq(CommonClientConfigKey.ReadTimeout));
doReturn("404").when(config).getPropertyAsString( doReturn("404").when(config).getPropertyAsString(
eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq("")); eq(RibbonLoadBalancedRetryPolicy.RETRYABLE_STATUS_CODES), eq(""));
doReturn(config).when(clientFactory).getClientConfig(eq("default")); doReturn(config).when(clientFactory).getClientConfig(eq("default"));
doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class)); doReturn(lbContext).when(clientFactory).getLoadBalancerContext(any(String.class));
when(config.get(eq(FollowRedirects), any())).thenReturn(true);
MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); MyBackOffPolicy backOffPolicy = new MyBackOffPolicy();
RibbonLoadBalancedRetryFactory loadBalancedRetryFactory = new RibbonLoadBalancedRetryFactory( RibbonLoadBalancedRetryFactory loadBalancedRetryFactory = new RibbonLoadBalancedRetryFactory(
clientFactory) { clientFactory) {
@@ -598,28 +595,28 @@ public class RetryableFeignLoadBalancerTests {
} }
@Override @Override
public InputStream asInputStream() throws IOException { public InputStream asInputStream() {
return new ByteArrayInputStream("test".getBytes()); return new ByteArrayInputStream("test".getBytes());
} }
@Override @Override
public Reader asReader() throws IOException { public Reader asReader() {
return new InputStreamReader(asInputStream(), UTF_8); return new InputStreamReader(asInputStream(), UTF_8);
} }
@Override @Override
public Reader asReader(Charset charset) throws IOException { public Reader asReader(Charset charset) {
return new InputStreamReader(asInputStream(), charset); return new InputStreamReader(asInputStream(), charset);
} }
@Override @Override
public void close() throws IOException { public void close() {
} }
}).build(); }).build();
doReturn(fourOFourResponse).when(client).execute(any(Request.class), doReturn(fourOFourResponse).when(client).execute(any(Request.class),
any(Request.Options.class)); any(Request.Options.class));
RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(this.lb, RetryableFeignLoadBalancer feignLb = new RetryableFeignLoadBalancer(lb, config,
config, this.inspector, loadBalancedRetryFactory); inspector, loadBalancedRetryFactory);
FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null); FeignLoadBalancer.RibbonResponse ribbonResponse = feignLb.execute(request, null);
verify(client, times(2)).execute(any(Request.class), any(Request.Options.class)); verify(client, times(2)).execute(any(Request.class), any(Request.Options.class));
assertThat(backOffPolicy.getCount()).isEqualTo(1); assertThat(backOffPolicy.getCount()).isEqualTo(1);
@@ -629,7 +626,7 @@ public class RetryableFeignLoadBalancerTests {
assertThat(new String(buf, 0, read)).isEqualTo("test"); assertThat(new String(buf, 0, read)).isEqualTo("test");
} }
class MyBackOffPolicy implements BackOffPolicy { static class MyBackOffPolicy implements BackOffPolicy {
private int count = 0; private int count = 0;
@@ -641,16 +638,16 @@ public class RetryableFeignLoadBalancerTests {
@Override @Override
public void backOff(BackOffContext backOffContext) public void backOff(BackOffContext backOffContext)
throws BackOffInterruptedException { throws BackOffInterruptedException {
this.count++; count++;
} }
public int getCount() { public int getCount() {
return this.count; return count;
} }
} }
class MyRetryListener implements RetryListener { static class MyRetryListener implements RetryListener {
private int onError = 0; private int onError = 0;
@@ -669,16 +666,16 @@ public class RetryableFeignLoadBalancerTests {
@Override @Override
public <T, E extends Throwable> void onError(RetryContext context, public <T, E extends Throwable> void onError(RetryContext context,
RetryCallback<T, E> callback, Throwable throwable) { RetryCallback<T, E> callback, Throwable throwable) {
this.onError++; onError++;
} }
public int getOnError() { public int getOnError() {
return this.onError; return onError;
} }
} }
class MyRetryListenerNotRetry implements RetryListener { static class MyRetryListenerNotRetry implements RetryListener {
@Override @Override
public <T, E extends Throwable> boolean open(RetryContext context, public <T, E extends Throwable> boolean open(RetryContext context,
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2021 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign.support; package org.springframework.cloud.openfeign.support;
import java.util.concurrent.TimeUnit;
import org.junit.After; import org.junit.After;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@@ -23,6 +25,8 @@ import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties.Hc5Properties.PoolConcurrencyPolicy;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties.Hc5Properties.PoolReusePolicy;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@@ -30,9 +34,12 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.cloud.openfeign.support.FeignHttpClientProperties.Hc5Properties.DEFAULT_SOCKET_TIMEOUT;
import static org.springframework.cloud.openfeign.support.FeignHttpClientProperties.Hc5Properties.DEFAULT_SOCKET_TIMEOUT_UNIT;
/** /**
* @author Ryan Baxter * @author Ryan Baxter
* @author Nguyen Ky Thanh
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@DirtiesContext @DirtiesContext
@@ -62,16 +69,32 @@ public class FeignHttpClientPropertiesTests {
.isEqualTo(FeignHttpClientProperties.DEFAULT_DISABLE_SSL_VALIDATION); .isEqualTo(FeignHttpClientProperties.DEFAULT_DISABLE_SSL_VALIDATION);
assertThat(getProperties().isFollowRedirects()) assertThat(getProperties().isFollowRedirects())
.isEqualTo(FeignHttpClientProperties.DEFAULT_FOLLOW_REDIRECTS); .isEqualTo(FeignHttpClientProperties.DEFAULT_FOLLOW_REDIRECTS);
assertThat(getProperties().getHc5().getPoolConcurrencyPolicy())
.isEqualTo(PoolConcurrencyPolicy.STRICT);
assertThat(getProperties().getHc5().getPoolReusePolicy())
.isEqualTo(PoolReusePolicy.FIFO);
assertThat(getProperties().getHc5().getSocketTimeout())
.isEqualTo(DEFAULT_SOCKET_TIMEOUT);
assertThat(getProperties().getHc5().getSocketTimeoutUnit())
.isEqualTo(DEFAULT_SOCKET_TIMEOUT_UNIT);
} }
@Test @Test
public void testCustomization() { public void testCustomization() {
TestPropertyValues.of("feign.httpclient.maxConnections=2", TestPropertyValues
"feign.httpclient.connectionTimeout=2", .of("feign.httpclient.maxConnections=2",
"feign.httpclient.maxConnectionsPerRoute=2", "feign.httpclient.connectionTimeout=2",
"feign.httpclient.timeToLive=2", "feign.httpclient.maxConnectionsPerRoute=2",
"feign.httpclient.disableSslValidation=true", "feign.httpclient.timeToLive=2",
"feign.httpclient.followRedirects=false").applyTo(this.context); "feign.httpclient.disableSslValidation=true",
"feign.httpclient.followRedirects=false",
"feign.httpclient.disableSslValidation=true",
"feign.httpclient.followRedirects=false",
"feign.httpclient.hc5.poolConcurrencyPolicy=lax",
"feign.httpclient.hc5.poolReusePolicy=lifo",
"feign.httpclient.hc5.socketTimeout=200",
"feign.httpclient.hc5.socketTimeoutUnit=milliseconds")
.applyTo(this.context);
setupContext(); setupContext();
assertThat(getProperties().getMaxConnections()).isEqualTo(2); assertThat(getProperties().getMaxConnections()).isEqualTo(2);
assertThat(getProperties().getConnectionTimeout()).isEqualTo(2); assertThat(getProperties().getConnectionTimeout()).isEqualTo(2);
@@ -79,6 +102,13 @@ public class FeignHttpClientPropertiesTests {
assertThat(getProperties().getTimeToLive()).isEqualTo(2L); assertThat(getProperties().getTimeToLive()).isEqualTo(2L);
assertThat(getProperties().isDisableSslValidation()).isTrue(); assertThat(getProperties().isDisableSslValidation()).isTrue();
assertThat(getProperties().isFollowRedirects()).isFalse(); assertThat(getProperties().isFollowRedirects()).isFalse();
assertThat(getProperties().getHc5().getPoolConcurrencyPolicy())
.isEqualTo(PoolConcurrencyPolicy.LAX);
assertThat(getProperties().getHc5().getPoolReusePolicy())
.isEqualTo(PoolReusePolicy.LIFO);
assertThat(getProperties().getHc5().getSocketTimeout()).isEqualTo(200);
assertThat(getProperties().getHc5().getSocketTimeoutUnit())
.isEqualTo(TimeUnit.MILLISECONDS);
} }
private void setupContext() { private void setupContext() {
@@ -19,14 +19,18 @@ package org.springframework.cloud.openfeign.support;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link PageJacksonModule}.
*
* @author Ruben Vervaeke * @author Ruben Vervaeke
* @author Olga Maciaszek-Sharma
*/ */
public class PageJacksonModuleTests { public class PageJacksonModuleTests {
@@ -38,10 +42,13 @@ public class PageJacksonModuleTests {
objectMapper.registerModule(new PageJacksonModule()); objectMapper.registerModule(new PageJacksonModule());
} }
@Test @ParameterizedTest
public void deserializePage() throws JsonProcessingException { @ValueSource(strings = { "totalElements", "total-elements", "total_elements",
"totalelements", "TotalElements" })
public void deserializePage(String totalElements) throws JsonProcessingException {
// Given // Given
String pageJson = "{\"content\":[\"A name\"], \"number\":1, \"size\":2, \"totalElements\": 3}"; String pageJson = "{\"content\":[\"A name\"], \"number\":1, \"size\":2, \""
+ totalElements + "\": 3}";
// When // When
Page<?> result = objectMapper.readValue(pageJson, Page.class); Page<?> result = objectMapper.readValue(pageJson, Page.class);
// Then // Then
@@ -36,9 +36,11 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.cloud.openfeign.FeignContext; import org.springframework.cloud.openfeign.FeignContext;
import org.springframework.cloud.openfeign.encoding.HttpEncoding; import org.springframework.cloud.openfeign.encoding.HttpEncoding;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage; import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@@ -47,6 +49,7 @@ import org.springframework.http.converter.GenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.mock.web.MockMultipartFile; import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -59,6 +62,7 @@ import static org.springframework.http.HttpHeaders.CONTENT_LENGTH;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE; import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE;
import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE;
import static org.springframework.http.MediaType.TEXT_PLAIN_VALUE;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
@@ -79,6 +83,9 @@ public class SpringEncoderTests {
@Qualifier("myHttpMessageConverter") @Qualifier("myHttpMessageConverter")
private HttpMessageConverter<?> myConverter; private HttpMessageConverter<?> myConverter;
@Autowired
private ApplicationContext applicationContext;
@Autowired @Autowired
@Qualifier("myGenericHttpMessageConverter") @Qualifier("myGenericHttpMessageConverter")
private GenericHttpMessageConverter<?> myGenericConverter; private GenericHttpMessageConverter<?> myGenericConverter;
@@ -185,6 +192,32 @@ public class SpringEncoderTests {
.as("Body content cannot be decoded").contains("hi"); .as("Body content cannot be decoded").contains("hi");
} }
@Test
public void testNoCharsetForBinaryFiles() {
Encoder encoder = context.getInstance("test", Encoder.class);
assertThat(encoder).isNotNull();
RequestTemplate request = new RequestTemplate();
request.header(CONTENT_TYPE, APPLICATION_OCTET_STREAM_VALUE);
Resource resource = applicationContext.getResource("classpath:dummy.pdf");
encoder.encode(resource, Resource.class, request);
assertThat(request.requestBody().getEncoding()).isEmpty();
}
@Test
public void testUTF8CharsetForTextFiles() {
Encoder encoder = context.getInstance("test", Encoder.class);
assertThat(encoder).isNotNull();
RequestTemplate request = new RequestTemplate();
request.header(CONTENT_TYPE, TEXT_PLAIN_VALUE);
String test = "test";
encoder.encode(test, String.class, request);
assertThat(request.requestBody().getEncoding().get().name()).isEqualTo("UTF-8");
}
protected interface TestClient { protected interface TestClient {
} }
@@ -213,6 +246,11 @@ public class SpringEncoderTests {
return new MyHttpMessageConverter(); return new MyHttpMessageConverter();
} }
@Bean
ResourceHttpMessageConverter resourceHttpMessageConverter() {
return new ResourceHttpMessageConverter();
}
@Bean @Bean
GenericHttpMessageConverter<?> myGenericHttpMessageConverter() { GenericHttpMessageConverter<?> myGenericHttpMessageConverter() {
return new MyGenericHttpMessageConverter(); return new MyGenericHttpMessageConverter();
@@ -22,3 +22,4 @@ feign.client.config.unwrap.readTimeout=1000
feign.client.config.unwrap.exceptionPropagationPolicy=unwrap feign.client.config.unwrap.exceptionPropagationPolicy=unwrap
feign.client.config.readTimeout.readTimeout=1000 feign.client.config.readTimeout.readTimeout=1000
feign.client.config.connectTimeout.connectTimeout=1000 feign.client.config.connectTimeout.connectTimeout=1000
feign.client.config.default.followRedirects=false
+6 -64
View File
@@ -6,16 +6,16 @@
<parent> <parent>
<artifactId>spring-cloud-dependencies-parent</artifactId> <artifactId>spring-cloud-dependencies-parent</artifactId>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<version>2.3.2.BUILD-SNAPSHOT</version> <version>2.3.4.RELEASE</version>
<relativePath/> <relativePath/>
</parent> </parent>
<artifactId>spring-cloud-openfeign-dependencies</artifactId> <artifactId>spring-cloud-openfeign-dependencies</artifactId>
<version>2.2.7.BUILD-SNAPSHOT</version> <version>2.2.8.RELEASE</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>spring-cloud-openfeign-dependencies</name> <name>spring-cloud-openfeign-dependencies</name>
<description>Spring Cloud OpenFeign Dependencies</description> <description>Spring Cloud OpenFeign Dependencies</description>
<properties> <properties>
<feign.version>10.10.1</feign.version> <feign.version>10.12</feign.version>
<feign-form.version>3.8.0</feign-form.version> <feign-form.version>3.8.0</feign-form.version>
</properties> </properties>
<dependencyManagement> <dependencyManagement>
@@ -32,74 +32,16 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.github.openfeign</groupId> <groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId> <artifactId>feign-bom</artifactId>
<version>${feign.version}</version> <version>${feign.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.github.openfeign.form</groupId> <groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId> <artifactId>feign-form-spring</artifactId>
<version>${feign-form.version}</version> <version>${feign-form.version}</version>
</dependency> </dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-hystrix</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jackson-jaxb</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jackson</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jaxb</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jaxrs</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-ribbon</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-sax</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-mock</artifactId>
<version>${feign.version}</version>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
<profiles> <profiles>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent> <parent>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId> <artifactId>spring-cloud-openfeign</artifactId>
<version>2.2.7.BUILD-SNAPSHOT</version> <version>2.2.8.RELEASE</version>
<relativePath>..</relativePath> <relativePath>..</relativePath>
</parent> </parent>
<artifactId>spring-cloud-starter-openfeign</artifactId> <artifactId>spring-cloud-starter-openfeign</artifactId>
+14 -11
View File
@@ -3,16 +3,19 @@
"-//Puppy Crawl//DTD Suppressions 1.1//EN" "-//Puppy Crawl//DTD Suppressions 1.1//EN"
"https://www.puppycrawl.com/dtds/suppressions_1_1.dtd"> "https://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions> <suppressions>
<suppress files=".*FeignClientTests.*" checks="LineLengthCheck" /> <suppress files=".*FeignClientTests.*" checks="LineLengthCheck"/>
<suppress files=".*FeignClientsRegistrarTests.*" checks="LineLengthCheck" /> <suppress files=".*FeignClientsRegistrarTests.*" checks="LineLengthCheck"/>
<suppress files=".*FeignRibbonHttpClientConfigurationTests.*" checks="LineLengthCheck" /> <suppress files=".*FeignRibbonHttpClientConfigurationTests.*"
<suppress files=".*FeignRibbonOkHttpClientConfigurationTests.*" checks="LineLengthCheck" /> checks="LineLengthCheck"/>
<suppress files=".*InvoiceClient.*" checks="LineLengthCheck" /> <suppress files=".*FeignRibbonOkHttpClientConfigurationTests.*"
<suppress files=".*InvoiceResource.*" checks="LineLengthCheck" /> checks="LineLengthCheck"/>
<suppress files=".*IterableParameterTests.*" checks="LineLengthCheck" /> <suppress files=".*InvoiceClient.*" checks="LineLengthCheck"/>
<suppress files=".*LoadBalancerFeignClientOverrideTests.*" checks="LineLengthCheck" /> <suppress files=".*InvoiceResource.*" checks="LineLengthCheck"/>
<suppress files=".*ProtobufSpringEncoderTest.*" checks="LineLengthCheck" /> <suppress files=".*IterableParameterTests.*" checks="LineLengthCheck"/>
<suppress files=".*ProtobufTest.*" checks="LineLengthCheck" /> <suppress files=".*LoadBalancerFeignClientOverrideTests.*" checks="LineLengthCheck"/>
<suppress files=".*ProtobufSpringEncoderTest.*" checks="LineLengthCheck"/>
<suppress files=".*ProtobufTest.*" checks="LineLengthCheck"/>
<suppress files=".*Hello.*" checks="RedundantModifier"/>
<!-- Important --> <!-- Important -->
<suppress files=".*HttpEncoding.*" checks="InterfaceIsTypeCheck" /> <suppress files=".*HttpEncoding.*" checks="InterfaceIsTypeCheck"/>
</suppressions> </suppressions>