Compare commits

...
96 Commits
Author SHA1 Message Date
Olga MaciaszekSharma 161789e33a Going back to snapshots. 2021-11-17 23:12:16 +01:00
buildmaster 650b14ac22 Bumping versions 2021-10-21 11:07:10 +00:00
Olga MaciaszekSharma 17d0161faf Reformat. 2021-10-21 12:40:20 +02:00
Olga MaciaszekSharma d6783a6f1e Block clas-level request mapping on Feign clients. 2021-10-21 12:14:19 +02:00
Olga MaciaszekSharma 1275875ddb Reformat. 2021-07-07 18:58:48 +02:00
Olga MaciaszekSharma c4b9492a9b Bumping versions to 2.2.10.BUILD-SNAPSHOT after release
This reverts commit f7e490c466.
2021-07-07 18:46:53 +02:00
Olga MaciaszekSharma 3acf5f9e92 Going back to snapshots
This reverts commit 6479db0a54.
2021-07-07 18:46:20 +02:00
buildmaster e9e38d0274 Bumping versions 2021-07-07 14:07:20 +00:00
Olga MaciaszekSharma 28b50401c5 Revert "Update SNAPSHOT to 2.2.9.RELEASE"
This reverts commit 1005749eb5.
2021-07-07 14:38:12 +02:00
Olga MaciaszekSharma 6479db0a54 Revert "Going back to snapshots"
This reverts commit 190f5a9083.
2021-07-07 14:37:39 +02:00
Olga MaciaszekSharma f7e490c466 Revert "Bumping versions to 2.2.10.BUILD-SNAPSHOT after release"
This reverts commit d60cda824d.
2021-07-07 14:37:03 +02:00
buildmaster d60cda824d Bumping versions to 2.2.10.BUILD-SNAPSHOT after release 2021-07-06 14:53:53 +00:00
buildmaster 190f5a9083 Going back to snapshots 2021-07-06 14:53:53 +00:00
buildmaster 1005749eb5 Update SNAPSHOT to 2.2.9.RELEASE 2021-07-06 14:52:01 +00:00
Michal Domagala df1f982046 Fix for RetryableFeignBlockingLoadBalancerClient closes stream (#569) 2021-07-05 13:03:06 +02:00
Michal Domagala baf7cf95f2 Simplify Log.info logic (#556) 2021-07-05 12:43:59 +02:00
Olga MaciaszekSharma 00ea88c67f Fix typo. Refactor. 2021-07-05 11:55:41 +02:00
Olga MaciaszekSharma d897b18e16 Add missing author tags. Refactor. 2021-07-05 11:26:06 +02:00
Can Bezmen 8c08204c78 Issue #549
* Fixed: Form URL Encoded bug fixed.

Fixes gh-549.
2021-07-05 11:19:29 +02:00
Olga MaciaszekSharma 2f43715f6f Change log level. Fixes gh-552. 2021-06-10 16:04:17 +02:00
Nick Smith 421df91a80 Filters out null matrix parameters 2021-05-24 15:58:27 +02:00
Olga MaciaszekSharma ec1f2ad5bb Refactor FeignHalConfiguration to use HalMediaTypeConfiguration under the hood. Fixes gh-541. 2021-05-12 13:51:43 +02:00
Olga MaciaszekSharma 5baa8c8ed5 Remove master references. 2021-04-26 19:24:36 +02:00
buildmaster 0684ee4bc2 Bumping versions to 2.2.9.BUILD-SNAPSHOT after release 2021-04-21 17:11:52 +00:00
buildmaster 0b34d89adc Going back to snapshots 2021-04-21 17:11:52 +00:00
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
Olga Maciaszek-Sharma 89fb98daf7 Upgrade protobuf-java. 2020-12-01 17:30:13 +01:00
Olga Maciaszek-Sharma 1a7917e2bb Add information about decodeSlash property to docs. 2020-12-01 17:08:43 +01:00
Olga Maciaszek-Sharma 49d3830276 Remove unnecessary keyword from recently modified class. 2020-12-01 17:02:09 +01:00
Ram Anaswara d419826ca0 Fix for Path variables with / are not url encoded
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractIntegrationTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java
2020-12-01 16:53:39 +01:00
Olga Maciaszek-Sharma 64d3f05e70 Allow overriding creating requests. Fixes gh-423. 2020-11-30 19:12:14 +01:00
Olga Maciaszek-Sharma 4d021fd3f8 Do not throw exceptions from @PreDestroy methods. Fixes gh-435. 2020-11-30 18:21:44 +01:00
matt62king a8bcda0b5b add customizer for feign builder (#289).
Fixes gh-436.

* add customizer for feign builder

* support @Order for customizers

* switch to annotation aware comparator for @Order support

* remove intermediate instances

* removed default feign builder customizer
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java
2020-11-30 17:56:48 +01:00
buildmaster 1b42820c3a Bumping versions to 2.2.7.BUILD-SNAPSHOT after release 2020-11-09 10:40:38 +00:00
buildmaster e31defb2dd Going back to snapshots 2020-11-09 10:40:37 +00:00
buildmaster f4ca971253 Update SNAPSHOT to 2.2.6.RELEASE 2020-11-09 10:38:56 +00:00
Michal Domagalaandmichal a8a2a0155f Fix for @EnableFeignClients(clients) scans classes in nested packages (#422)
* Test to verify sub level client error

Error is described in https://github.com/spring-cloud/spring-cloud-openfeign/issues/331

Application fails when one Feign client is `org.TopClient` and second is in subpackage:  `org.sub.SubClient`

The error reason is that `SubClient` is registered twice

* Fix for @EnableFeignClients(clients) scans classes in nested packages twice

https://github.com/spring-cloud/spring-cloud-openfeign/issues/331
(cherry picked from commit fe62b0db90)

# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsRegistrar.java

* delete unused code

(cherry picked from commit 4df865d1d6)

* add file header

* Apply review

Co-authored-by: michal <michal@michal-desktop>
2020-11-03 10:31:23 +01:00
Nikolas Charalambidis cf4fa54ac8 Fixes gh-391 timeout handling documentation (#421)
* Fixes gh-391

* Fixes gh-391 sentence reworded

* Fixes gh-391 fixed spelling

* Fixes gh-391 fixed code format

* Fixes gh-391 fixed sentence

* Fixes gh-391 fixed code

* Fixes gh-391 word deletion
2020-11-02 14:10:58 +01:00
Ilia Ilinykh 93327fcace Ability to configure client to send default headers #284 at 2.2.x (#420)
* Implemented ability to provide default query parameters and headers to feign clients.
Issue was mentioned in №284

* Removed wrong names of test data. Replaced with correct ones.

* Thread sleep was repalced with more verbose TimeUnit sleep

* Fixed more names of the clients.
2020-10-29 15:58:38 +01:00
Olga Maciaszek-Sharma bc6c3b7bf2 Sort request interceptors. (#419) 2020-10-28 18:36:46 +01:00
Olga Maciaszek-Sharma f410385237 Upgrade jackson to 2.11.3. 2020-10-28 17:46:44 +01:00
Olga Maciaszek-Sharma a5ab3383c9 Rename new class. 2020-10-02 15:25:18 +02:00
Olga Maciaszek-Sharma dd518a812b Add support for load-balanced retries. (#408) 2020-10-01 20:20:24 +02:00
Olga Maciaszek-Sharma c3dcb1f376 Remove maven compiler plugin version to use the one provided by Boot instead. 2020-09-17 14:49:03 +02:00
Olga Maciaszek-Sharma 27e2775c5f Upgrade protobuf-java. 2020-09-17 14:30:54 +02:00
Olga Maciaszek-Sharma 83ef242406 Upgrade vavr. 2020-09-17 14:20:29 +02:00
Olga Maciaszek-Sharma 6534950ed2 Upgrade jakson. 2020-09-17 12:57:47 +02:00
Olga Maciaszek-Sharma e83593651c Clean up test. 2020-09-16 12:50:57 +02:00
Olga Maciaszek-Sharma 4cbf6da17b Adjust test to changes in commons. 2020-09-16 12:38:22 +02:00
liuzeyanga 5fea4f3b35 change "Sprig Cloud" to  "Spring Cloud" 2020-09-16 11:53:59 +02:00
buildmaster 36c06c97a6 Bumping versions to 2.2.6.BUILD-SNAPSHOT after release 2020-08-28 20:04:40 +00:00
buildmaster d6b021eaa4 Going back to snapshots 2020-08-28 20:04:40 +00:00
103 changed files with 5669 additions and 1079 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
+4 -4
View File
@@ -3,7 +3,7 @@
Spring Cloud is released under the non-restrictive Apache 2.0 license, Spring Cloud is released under the non-restrictive Apache 2.0 license,
and follows a very standard Github development process, using Github and follows a very standard Github development process, using Github
tracker for issues and merging pull requests into master. If you want tracker for issues and merging pull requests into main. If you want
to contribute even something trivial please do not hesitate, but to contribute even something trivial please do not hesitate, but
follow the guidelines below. follow the guidelines below.
@@ -17,7 +17,7 @@ given the ability to merge pull requests.
## Code of Conduct ## Code of Conduct
This project adheres to the Contributor Covenant [code of This project adheres to the Contributor Covenant [code of
conduct](https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report conduct](https://github.com/spring-cloud/spring-cloud-build/blob/main/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report
unacceptable behavior to spring-code-of-conduct@pivotal.io. unacceptable behavior to spring-code-of-conduct@pivotal.io.
## Code Conventions and Housekeeping ## Code Conventions and Housekeeping
@@ -27,7 +27,7 @@ added after the original pull request but before a merge.
* Use the Spring Framework code format conventions. If you use Eclipse * Use the Spring Framework code format conventions. If you use Eclipse
you can import formatter settings using the you can import formatter settings using the
`eclipse-code-formatter.xml` file from the `eclipse-code-formatter.xml` file from the
[Spring Cloud Build](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml) project. If using IntelliJ, you can use the [Spring Cloud Build](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/spring-cloud-dependencies-parent/eclipse-code-formatter.xml) project. If using IntelliJ, you can use the
[Eclipse Code Formatter Plugin](https://plugins.jetbrains.com/plugin/6546) to import the same file. [Eclipse Code Formatter Plugin](https://plugins.jetbrains.com/plugin/6546) to import the same file.
* Make sure all new `.java` files to have a simple Javadoc class comment with at least an * Make sure all new `.java` files to have a simple Javadoc class comment with at least an
`@author` tag identifying you, and preferably at least a paragraph on what the class is `@author` tag identifying you, and preferably at least a paragraph on what the class is
@@ -38,7 +38,7 @@ added after the original pull request but before a merge.
than cosmetic changes). than cosmetic changes).
* Add some Javadocs and, if you change the namespace, some XSD doc elements. * Add some Javadocs and, if you change the namespace, some XSD doc elements.
* A few unit tests would help a lot as well -- someone has to do it. * A few unit tests would help a lot as well -- someone has to do it.
* If no-one else is using your branch, please rebase it against the current master (or * If no-one else is using your branch, please rebase it against the current main (or
other target branch in the main project). other target branch in the main project).
* When writing a commit message please follow [these conventions](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html), * When writing a commit message please follow [these conventions](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html),
if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit
+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
+10 -18
View File
@@ -5,9 +5,9 @@ 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/main/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
image:https://api.codacy.com/project/badge/Grade/97b04c4e609c4b4f86b415e4437a6484["Codacy code quality", link="https://www.codacy.com/app/Spring-Cloud/spring-cloud-openfeign?utm_source=github.com&utm_medium=referral&utm_content=spring-cloud/spring-cloud-openfeign&utm_campaign=Badge_Grade"] image:https://api.codacy.com/project/badge/Grade/97b04c4e609c4b4f86b415e4437a6484["Codacy code quality", link="https://www.codacy.com/app/Spring-Cloud/spring-cloud-openfeign?utm_source=github.com&utm_medium=referral&utm_content=spring-cloud/spring-cloud-openfeign&utm_campaign=Badge_Grade"]
@@ -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.
@@ -64,23 +66,9 @@ the `.mvn` configuration, so if you find you have to do it to make a
build succeed, please raise a ticket to get the settings added to build succeed, please raise a ticket to get the settings added to
source control. source control.
For hints on how to build the project look in `.travis.yml` if there The projects that require middleware (i.e. Redis) for testing generally
is one. There should be a "script" and maybe "install" command. Also require that a local instance of [Docker](https://www.docker.com/get-started) is installed and running.
look at the "services" section to see if any services need to be
running locally (e.g. mongo or rabbit). Ignore the git-related bits
that you might find in "before_install" since they're related to setting git
credentials and you already have those.
The projects that require middleware generally include a
`docker-compose.yml`, so consider using
https://docs.docker.com/compose/[Docker Compose] to run the middeware servers
in Docker containers. See the README in the
https://github.com/spring-cloud-samples/scripts[scripts demo
repository] for specific instructions about the common cases of mongo,
rabbit and redis.
NOTE: If all else fails, build with the command from `.travis.yml` (usually
`./mvnw install`).
=== Documentation === Documentation
@@ -314,3 +302,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/main/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.5.RELEASE</version> <version>2.2.11.BUILD-SNAPSHOT</version>
</parent> </parent>
<artifactId>spring-cloud-openfeign-docs</artifactId> <artifactId>spring-cloud-openfeign-docs</artifactId>
<packaging>pom</packaging> <packaging>pom</packaging>
+8 -4
View File
@@ -1,6 +1,6 @@
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/main/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
image:https://api.codacy.com/project/badge/Grade/97b04c4e609c4b4f86b415e4437a6484["Codacy code quality", link="https://www.codacy.com/app/Spring-Cloud/spring-cloud-openfeign?utm_source=github.com&utm_medium=referral&utm_content=spring-cloud/spring-cloud-openfeign&utm_campaign=Badge_Grade"] image:https://api.codacy.com/project/badge/Grade/97b04c4e609c4b4f86b415e4437a6484["Codacy code quality", link="https://www.codacy.com/app/Spring-Cloud/spring-cloud-openfeign?utm_source=github.com&utm_medium=referral&utm_content=spring-cloud/spring-cloud-openfeign&utm_campaign=Badge_Grade"]
@@ -14,8 +14,12 @@ include::intro.adoc[]
== Building == Building
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/building-jdk8.adoc[] include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/docs/src/main/asciidoc/building-jdk8.adoc[]
== 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/main/docs/src/main/asciidoc/contributing.adoc[]
== License
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/main/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 -17
View File
@@ -1,24 +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.default-config | default | |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-to-properties | true | |feign.client.default-config | `default` |
|feign.compression.request.enabled | false | Enables the request sent by Feign to be compressed. |feign.client.default-to-properties | `true` |
|feign.compression.request.mime-types | [text/xml, application/xml, application/json] | The list of supported mime types. |feign.compression.request.enabled | `false` | Enables the request sent by Feign to be compressed.
|feign.compression.request.min-request-size | 2048 | The minimum threshold content size. |feign.compression.request.mime-types | `[text/xml, application/xml, application/json]` | The list of supported mime types.
|feign.compression.response.enabled | false | Enables the response from Feign to be compressed. |feign.compression.request.min-request-size | `2048` | The minimum threshold content size.
|feign.compression.response.useGzipDecoder | false | Enables the default gzip decoder to be used. |feign.compression.response.enabled | `false` | Enables the response from Feign to be compressed.
|feign.httpclient.connection-timeout | 2000 | |feign.compression.response.useGzipDecoder | `false` | Enables the default gzip decoder to be used.
|feign.httpclient.connection-timer-repeat | 3000 | |feign.encoder.charset-from-content-type | `false` | Indicates whether the charset should be derived from the {@code Content-Type} header.
|feign.httpclient.disable-ssl-validation | false | |feign.httpclient.connection-timeout | `2000` |
|feign.httpclient.enabled | true | Enables the use of the Apache HTTP Client by Feign. |feign.httpclient.connection-timer-repeat | `3000` |
|feign.httpclient.follow-redirects | true | |feign.httpclient.disable-ssl-validation | `false` |
|feign.httpclient.max-connections | 200 | |feign.httpclient.enabled | `true` | Enables the use of the Apache HTTP Client by Feign.
|feign.httpclient.max-connections-per-route | 50 | |feign.httpclient.follow-redirects | `true` |
|feign.httpclient.time-to-live | 900 | |feign.httpclient.hc5.enabled | `false` | Enables the use of the Apache HTTP Client 5 by Feign.
|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.
|=== |===
+6 -6
View File
@@ -39,7 +39,7 @@ function check_if_anything_to_sync() {
} }
function retrieve_current_branch() { function retrieve_current_branch() {
# Code getting the name of the current branch. For master we want to publish as we did until now # Code getting the name of the current branch. For main we want to publish as we did until now
# https://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch # https://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch
# If there is a branch already passed will reuse it - otherwise will try to find it # If there is a branch already passed will reuse it - otherwise will try to find it
CURRENT_BRANCH=${BRANCH} CURRENT_BRANCH=${BRANCH}
@@ -134,8 +134,8 @@ function add_docs_from_target() {
# Copies the docs by using the retrieved properties from Maven build # Copies the docs by using the retrieved properties from Maven build
function copy_docs_for_current_version() { function copy_docs_for_current_version() {
if [[ "${CURRENT_BRANCH}" == "master" ]] ; then if [[ "${CURRENT_BRANCH}" == "main" ]] ; then
echo -e "Current branch is master - will copy the current docs only to the root folder" echo -e "Current branch is main - will copy the current docs only to the root folder"
for f in docs/target/generated-docs/*; do for f in docs/target/generated-docs/*; do
file=${f#docs/target/generated-docs/*} file=${f#docs/target/generated-docs/*}
if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then
@@ -216,7 +216,7 @@ function commit_changes_if_applicable() {
git commit -a -m "Sync docs from ${CURRENT_BRANCH} to gh-pages" && COMMIT_SUCCESSFUL="yes" || echo "Failed to commit changes" git commit -a -m "Sync docs from ${CURRENT_BRANCH} to gh-pages" && COMMIT_SUCCESSFUL="yes" || echo "Failed to commit changes"
# Uncomment the following push if you want to auto push to # Uncomment the following push if you want to auto push to
# the gh-pages branch whenever you commit to master locally. # the gh-pages branch whenever you commit to main locally.
# This is a little extreme. Use with care! # This is a little extreme. Use with care!
################################################################### ###################################################################
if [[ "${COMMIT_SUCCESSFUL}" == "yes" ]] ; then if [[ "${COMMIT_SUCCESSFUL}" == "yes" ]] ; then
@@ -249,7 +249,7 @@ The idea of this script is to update gh-pages branch with the generated docs. Wi
the script will work in the following manner: the script will work in the following manner:
- if there's no gh-pages / target for docs module then the script ends - if there's no gh-pages / target for docs module then the script ends
- for master branch the generated docs are copied to the root of gh-pages branch - for main branch the generated docs are copied to the root of gh-pages branch
- for any other branch (if that branch is whitelisted) a subfolder with branch name is created - for any other branch (if that branch is whitelisted) a subfolder with branch name is created
and docs are copied there and docs are copied there
- if the version switch is passed (-v) then a tag with (v) prefix will be retrieved and a folder - if the version switch is passed (-v) then a tag with (v) prefix will be retrieved and a folder
@@ -327,4 +327,4 @@ build_docs_if_applicable
retrieve_doc_properties retrieve_doc_properties
stash_changes stash_changes
add_docs_from_target add_docs_from_target
checkout_previous_branch checkout_previous_branch
+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/main/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/main/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:
@@ -175,6 +176,10 @@ feign:
loggerLevel: full loggerLevel: full
errorDecoder: com.example.SimpleErrorDecoder errorDecoder: com.example.SimpleErrorDecoder
retryer: com.example.SimpleRetryer retryer: com.example.SimpleRetryer
defaultQueryParameters:
query: queryValue
defaultRequestHeaders:
header: headerValue
requestInterceptors: requestInterceptors:
- com.example.FooRequestInterceptor - com.example.FooRequestInterceptor
- com.example.BarRequestInterceptor - com.example.BarRequestInterceptor
@@ -188,6 +193,8 @@ Default configurations can be specified in the `@EnableFeignClients` attribute `
If you prefer using configuration properties to configured all `@FeignClient`, you can create configuration properties with `default` feign name. If you prefer using configuration properties to configured all `@FeignClient`, you can create configuration properties with `default` feign name.
You can use `feign.client.config.feignName.defaultQueryParameters` and `feign.client.config.feignName.defaultRequestHeaders` to specify query parameters and headers that will be sent with every request of the client named `feignName`.
application.yml application.yml
[source,yaml] [source,yaml]
---- ----
@@ -268,6 +275,50 @@ 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`.
==== `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
We can configure timeouts on both the default and the named client. OpenFeign works with two timeout parameters:
- `connectTimeout` prevents blocking the caller due to the long server processing time.
- `readTimeout` is applied from the time of connection establishment and is triggered when returning the response takes too long.
NOTE: In case the server is not running or available a packet results in _connection refused_. The communication ends either with an error message or in a fallback. This can happen _before_ the `connectTimeout` if it is set very low. The time taken to perform a lookup and to receive such a packet causes a significant part of this delay. It is subject to change based on the remote host that involves a DNS lookup.
When Hystrix <<spring-cloud-openfeign#spring-cloud-feign-hystrix,is enabled>>, its timeout configuration link:https://github.com/Netflix/Hystrix/wiki/Configuration#execution.isolation.thread.timeoutInMilliseconds[defaults] to 1000 milliseconds. Hence, it might occur before the client timeout that we configured earlier. Increasing this timeout prevents it from happening.
[source,yaml]
----
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
hystrix:
enabled: true
hystrix:
command:
default:
execution:
timeout:
enabled: true
isolation:
thread:
timeoutInMilliseconds: 60000
----
NOTE: When the Hystrix timeout is enabled and its timeout is set longer than that of a feign client, `HystrixTimeoutException` wraps a feign exception. Otherwise, the only difference is the cause of the exception. The purpose of `HystrixTimeoutException` is to wrap any runtime exception that occurs first and throw an instance of itself.
=== Creating Feign Clients Manually === Creating Feign Clients Manually
In some cases it might be necessary to customize your Feign Clients in a way that is not In some cases it might be necessary to customize your Feign Clients in a way that is not
@@ -342,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]
---- ----
@@ -386,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.
@@ -434,10 +523,7 @@ public interface UserClient extends UserService {
} }
---- ----
NOTE: It is generally not advisable to share an interface between a WARNING: `@FeignClient` interfaces should not be shared between server and client and annotating `@FeignClient` interfaces with `@RequestMapping` on class level is no longer supported.
server and a client. It introduces tight coupling, and also actually
doesn't work with Spring MVC in its current form (method parameter
mapping is not inherited).
=== Feign request/response compression === Feign request/response compression
@@ -565,7 +651,7 @@ If a map is passed as the method argument, the `@MatrixVariable` path segment is
If a different object is passed, either the `name` provided in the `@MatrixVariable` annotation (if defined) or the annotated variable name is If a different object is passed, either the `name` provided in the `@MatrixVariable` annotation (if defined) or the annotated variable name is
joined with the provided method argument using `=`. joined with the provided method argument using `=`.
IMPORTANT:: Even though, on the server side, Spring does not require the users to name the path segment placeholder same as the matrix variable name, since it would be too ambiguous on the client side, Sprig Cloud OpenFeign requires that you add a path segment placeholder with a name matching either the `name` provided in the `@MatrixVariable` annotation (if defined) or the annotated variable name. IMPORTANT:: Even though, on the server side, Spring does not require the users to name the path segment placeholder same as the matrix variable name, since it would be too ambiguous on the client side, Spring Cloud OpenFeign requires that you add a path segment placeholder with a name matching either the `name` provided in the `@MatrixVariable` annotation (if defined) or the annotated variable name.
For example: For example:
@@ -621,6 +707,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].
+5 -7
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.5.RELEASE</version> <version>2.2.11.BUILD-SNAPSHOT</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.6.BUILD-SNAPSHOT</version>
<relativePath/> <relativePath/>
</parent> </parent>
<scm> <scm>
@@ -25,12 +25,11 @@
</scm> </scm>
<properties> <properties>
<main.basedir>${basedir}</main.basedir> <main.basedir>${basedir}</main.basedir>
<jackson.version>2.7.3</jackson.version> <jackson.version>2.11.3</jackson.version>
<spring-cloud-commons.version>2.2.5.RELEASE</spring-cloud-commons.version> <spring-cloud-commons.version>2.2.9.RELEASE</spring-cloud-commons.version>
<spring-cloud-netflix.version>2.2.5.RELEASE</spring-cloud-netflix.version> <spring-cloud-netflix.version>2.2.9.RELEASE</spring-cloud-netflix.version>
<!-- Plugin versions --> <!-- Plugin versions -->
<maven-compiler-plugin.version>3.6.1</maven-compiler-plugin.version>
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version> <maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
<!-- Sonar --> <!-- Sonar -->
<surefire.plugin.version>2.19.1</surefire.plugin.version> <surefire.plugin.version>2.19.1</surefire.plugin.version>
@@ -68,7 +67,6 @@
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration> <configuration>
<source>1.8</source> <source>1.8</source>
<target>1.8</target> <target>1.8</target>
+8 -3
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.5.RELEASE</version> <version>2.2.11.BUILD-SNAPSHOT</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>
@@ -217,13 +222,13 @@
<dependency> <dependency>
<groupId>com.google.protobuf</groupId> <groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId> <artifactId>protobuf-java</artifactId>
<version>3.4.0</version> <version>3.14.0</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.vavr</groupId> <groupId>io.vavr</groupId>
<artifactId>vavr</artifactId> <artifactId>vavr</artifactId>
<version>0.10.0</version> <version>0.10.3</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@@ -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.
@@ -16,6 +16,7 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Timer; import java.util.Timer;
@@ -24,11 +25,15 @@ 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;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.RegistryBuilder; import org.apache.http.config.RegistryBuilder;
@@ -36,33 +41,50 @@ 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 {
private static final Log LOG = LogFactory.getLog(FeignAutoConfiguration.class);
@Autowired(required = false) @Autowired(required = false)
private List<FeignClientSpecification> configurations = new ArrayList<>(); private List<FeignClientSpecification> configurations = new ArrayList<>();
@@ -79,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
@@ -91,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);
} }
} }
@@ -111,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(
@@ -163,10 +224,17 @@ public class FeignAutoConfiguration {
} }
@PreDestroy @PreDestroy
public void destroy() throws Exception { public void destroy() {
this.connectionManagerTimer.cancel(); this.connectionManagerTimer.cancel();
if (this.httpClient != null) { if (this.httpClient != null) {
this.httpClient.close(); try {
this.httpClient.close();
}
catch (IOException e) {
if (LOG.isErrorEnabled()) {
LOG.error("Could not correctly close httpClient.");
}
}
} }
} }
@@ -222,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,31 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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;
/**
* Allows application to customize the Feign builder.
*
* @author Matt King
*/
@FunctionalInterface
public interface FeignBuilderCustomizer {
void customize(Feign.Builder builder);
}
@@ -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.
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@@ -33,17 +35,23 @@ 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;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@@ -54,15 +62,20 @@ import org.springframework.util.StringUtils;
* @author Gregor Zurowski * @author Gregor Zurowski
* @author Matt King * @author Matt King
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @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;
@@ -79,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;
@@ -87,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");
@@ -107,13 +126,28 @@ class FeignClientFactoryBean
// @formatter:on // @formatter:on
configureFeign(context, builder); configureFeign(context, builder);
applyBuildCustomizers(context, builder);
return builder; return builder;
} }
private void applyBuildCustomizers(FeignContext context, Feign.Builder builder) {
Map<String, FeignBuilderCustomizer> customizerMap = context
.getInstances(contextId, FeignBuilderCustomizer.class);
if (customizerMap != null) {
customizerMap.values().stream()
.sorted(AnnotationAwareOrderComparator.INSTANCE)
.forEach(feignBuilderCustomizer -> feignBuilderCustomizer
.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);
@@ -169,11 +203,15 @@ 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);
if (requestInterceptors != null) { if (requestInterceptors != null) {
builder.requestInterceptors(requestInterceptors.values()); List<RequestInterceptor> interceptors = new ArrayList<>(
requestInterceptors.values());
AnnotationAwareOrderComparator.sort(interceptors);
builder.requestInterceptors(interceptors);
} }
QueryMapEncoder queryMapEncoder = getInheritedAwareOptional(context, QueryMapEncoder queryMapEncoder = getInheritedAwareOptional(context,
QueryMapEncoder.class); QueryMapEncoder.class);
@@ -205,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());
@@ -238,6 +278,16 @@ class FeignClientFactoryBean
builder.encoder(getOrInstantiate(config.getEncoder())); builder.encoder(getOrInstantiate(config.getEncoder()));
} }
if (Objects.nonNull(config.getDefaultRequestHeaders())) {
builder.requestInterceptor(requestTemplate -> requestTemplate
.headers(config.getDefaultRequestHeaders()));
}
if (Objects.nonNull(config.getDefaultQueryParameters())) {
builder.requestInterceptor(requestTemplate -> requestTemplate
.queries(config.getDefaultQueryParameters()));
}
if (Objects.nonNull(config.getDecoder())) { if (Objects.nonNull(config.getDecoder())) {
builder.decoder(getOrInstantiate(config.getDecoder())); builder.decoder(getOrInstantiate(config.getDecoder()));
} }
@@ -253,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);
@@ -302,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();
} }
@@ -316,10 +367,17 @@ 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 (LOG.isInfoEnabled()) {
LOG.info("For '" + name
+ "' URL not provided. Will try picking an instance via load-balancing.");
}
if (!name.startsWith("http")) { if (!name.startsWith("http")) {
url = "http://" + name; url = "http://" + name;
} }
@@ -346,6 +404,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);
@@ -432,13 +496,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() {
@@ -467,18 +536,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
@@ -489,9 +563,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.
@@ -16,6 +16,7 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -34,6 +35,9 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
/** /**
* @author Eko Kurniawan Khannedy * @author Eko Kurniawan Khannedy
* @author Ilia Ilinykh
* @author Ram Anaswara
* @author Olga Maciaszek-Sharma
*/ */
@ConfigurationProperties("feign.client") @ConfigurationProperties("feign.client")
public class FeignClientProperties { public class FeignClientProperties {
@@ -44,8 +48,14 @@ public class FeignClientProperties {
private Map<String, FeignClientConfiguration> config = new HashMap<>(); private Map<String, FeignClientConfiguration> config = new HashMap<>();
/**
* Feign clients do not encode slash `/` characters by default. To change this
* behavior, set the `decodeSlash` to `false`.
*/
private boolean decodeSlash = true;
public boolean isDefaultToProperties() { public boolean isDefaultToProperties() {
return this.defaultToProperties; return defaultToProperties;
} }
public void setDefaultToProperties(boolean defaultToProperties) { public void setDefaultToProperties(boolean defaultToProperties) {
@@ -53,7 +63,7 @@ public class FeignClientProperties {
} }
public String getDefaultConfig() { public String getDefaultConfig() {
return this.defaultConfig; return defaultConfig;
} }
public void setDefaultConfig(String defaultConfig) { public void setDefaultConfig(String defaultConfig) {
@@ -61,13 +71,21 @@ public class FeignClientProperties {
} }
public Map<String, FeignClientConfiguration> getConfig() { public Map<String, FeignClientConfiguration> getConfig() {
return this.config; return config;
} }
public void setConfig(Map<String, FeignClientConfiguration> config) { public void setConfig(Map<String, FeignClientConfiguration> config) {
this.config = config; this.config = config;
} }
public boolean isDecodeSlash() {
return decodeSlash;
}
public void setDecodeSlash(boolean decodeSlash) {
this.decodeSlash = decodeSlash;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o) {
@@ -77,14 +95,15 @@ public class FeignClientProperties {
return false; return false;
} }
FeignClientProperties that = (FeignClientProperties) o; FeignClientProperties that = (FeignClientProperties) o;
return this.defaultToProperties == that.defaultToProperties return defaultToProperties == that.defaultToProperties
&& Objects.equals(this.defaultConfig, that.defaultConfig) && Objects.equals(defaultConfig, that.defaultConfig)
&& Objects.equals(this.config, that.config); && Objects.equals(config, that.config)
&& Objects.equals(decodeSlash, that.decodeSlash);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(this.defaultToProperties, this.defaultConfig, this.config); return Objects.hash(defaultToProperties, defaultConfig, config, decodeSlash);
} }
/** /**
@@ -104,6 +123,10 @@ public class FeignClientProperties {
private List<Class<RequestInterceptor>> requestInterceptors; private List<Class<RequestInterceptor>> requestInterceptors;
private Map<String, Collection<String>> defaultRequestHeaders;
private Map<String, Collection<String>> defaultQueryParameters;
private Boolean decode404; private Boolean decode404;
private Class<Decoder> decoder; private Class<Decoder> decoder;
@@ -114,8 +137,10 @@ public class FeignClientProperties {
private ExceptionPropagationPolicy exceptionPropagationPolicy; private ExceptionPropagationPolicy exceptionPropagationPolicy;
private Boolean followRedirects;
public Logger.Level getLoggerLevel() { public Logger.Level getLoggerLevel() {
return this.loggerLevel; return loggerLevel;
} }
public void setLoggerLevel(Logger.Level loggerLevel) { public void setLoggerLevel(Logger.Level loggerLevel) {
@@ -123,7 +148,7 @@ public class FeignClientProperties {
} }
public Integer getConnectTimeout() { public Integer getConnectTimeout() {
return this.connectTimeout; return connectTimeout;
} }
public void setConnectTimeout(Integer connectTimeout) { public void setConnectTimeout(Integer connectTimeout) {
@@ -131,7 +156,7 @@ public class FeignClientProperties {
} }
public Integer getReadTimeout() { public Integer getReadTimeout() {
return this.readTimeout; return readTimeout;
} }
public void setReadTimeout(Integer readTimeout) { public void setReadTimeout(Integer readTimeout) {
@@ -139,7 +164,7 @@ public class FeignClientProperties {
} }
public Class<Retryer> getRetryer() { public Class<Retryer> getRetryer() {
return this.retryer; return retryer;
} }
public void setRetryer(Class<Retryer> retryer) { public void setRetryer(Class<Retryer> retryer) {
@@ -147,7 +172,7 @@ public class FeignClientProperties {
} }
public Class<ErrorDecoder> getErrorDecoder() { public Class<ErrorDecoder> getErrorDecoder() {
return this.errorDecoder; return errorDecoder;
} }
public void setErrorDecoder(Class<ErrorDecoder> errorDecoder) { public void setErrorDecoder(Class<ErrorDecoder> errorDecoder) {
@@ -155,7 +180,7 @@ public class FeignClientProperties {
} }
public List<Class<RequestInterceptor>> getRequestInterceptors() { public List<Class<RequestInterceptor>> getRequestInterceptors() {
return this.requestInterceptors; return requestInterceptors;
} }
public void setRequestInterceptors( public void setRequestInterceptors(
@@ -163,8 +188,26 @@ public class FeignClientProperties {
this.requestInterceptors = requestInterceptors; this.requestInterceptors = requestInterceptors;
} }
public Map<String, Collection<String>> getDefaultRequestHeaders() {
return defaultRequestHeaders;
}
public void setDefaultRequestHeaders(
Map<String, Collection<String>> defaultRequestHeaders) {
this.defaultRequestHeaders = defaultRequestHeaders;
}
public Map<String, Collection<String>> getDefaultQueryParameters() {
return defaultQueryParameters;
}
public void setDefaultQueryParameters(
Map<String, Collection<String>> defaultQueryParameters) {
this.defaultQueryParameters = defaultQueryParameters;
}
public Boolean getDecode404() { public Boolean getDecode404() {
return this.decode404; return decode404;
} }
public void setDecode404(Boolean decode404) { public void setDecode404(Boolean decode404) {
@@ -172,7 +215,7 @@ public class FeignClientProperties {
} }
public Class<Decoder> getDecoder() { public Class<Decoder> getDecoder() {
return this.decoder; return decoder;
} }
public void setDecoder(Class<Decoder> decoder) { public void setDecoder(Class<Decoder> decoder) {
@@ -180,7 +223,7 @@ public class FeignClientProperties {
} }
public Class<Encoder> getEncoder() { public Class<Encoder> getEncoder() {
return this.encoder; return encoder;
} }
public void setEncoder(Class<Encoder> encoder) { public void setEncoder(Class<Encoder> encoder) {
@@ -188,7 +231,7 @@ public class FeignClientProperties {
} }
public Class<Contract> getContract() { public Class<Contract> getContract() {
return this.contract; return contract;
} }
public void setContract(Class<Contract> contract) { public void setContract(Class<Contract> contract) {
@@ -204,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) {
@@ -213,26 +264,29 @@ public class FeignClientProperties {
return false; return false;
} }
FeignClientConfiguration that = (FeignClientConfiguration) o; FeignClientConfiguration that = (FeignClientConfiguration) o;
return this.loggerLevel == that.loggerLevel return loggerLevel == that.loggerLevel
&& Objects.equals(this.connectTimeout, that.connectTimeout) && Objects.equals(connectTimeout, that.connectTimeout)
&& Objects.equals(this.readTimeout, that.readTimeout) && Objects.equals(readTimeout, that.readTimeout)
&& Objects.equals(this.retryer, that.retryer) && Objects.equals(retryer, that.retryer)
&& Objects.equals(this.errorDecoder, that.errorDecoder) && Objects.equals(errorDecoder, that.errorDecoder)
&& Objects.equals(this.requestInterceptors, that.requestInterceptors) && Objects.equals(requestInterceptors, that.requestInterceptors)
&& Objects.equals(this.decode404, that.decode404) && Objects.equals(decode404, that.decode404)
&& Objects.equals(this.encoder, that.encoder) && Objects.equals(encoder, that.encoder)
&& Objects.equals(this.decoder, that.decoder) && Objects.equals(decoder, that.decoder)
&& Objects.equals(this.contract, that.contract) && Objects.equals(contract, that.contract)
&& Objects.equals(this.exceptionPropagationPolicy, && Objects.equals(exceptionPropagationPolicy,
that.exceptionPropagationPolicy); that.exceptionPropagationPolicy)
&& Objects.equals(defaultRequestHeaders, that.defaultRequestHeaders)
&& Objects.equals(defaultQueryParameters, that.defaultQueryParameters)
&& Objects.equals(followRedirects, that.followRedirects);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(this.loggerLevel, this.connectTimeout, this.readTimeout, return Objects.hash(loggerLevel, connectTimeout, readTimeout, retryer,
this.retryer, this.errorDecoder, this.requestInterceptors, errorDecoder, requestInterceptors, decode404, encoder, decoder,
this.decode404, this.encoder, this.decoder, this.contract, contract, exceptionPropagationPolicy, defaultQueryParameters,
this.exceptionPropagationPolicy); 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 {
@@ -82,6 +87,12 @@ public class FeignClientsConfiguration {
@Autowired(required = false) @Autowired(required = false)
private SpringDataWebProperties springDataWebProperties; private SpringDataWebProperties springDataWebProperties;
@Autowired(required = false)
private FeignClientProperties feignClientProperties;
@Autowired(required = false)
private FeignEncoderProperties encoderProperties;
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public Decoder feignDecoder() { public Decoder feignDecoder() {
@@ -93,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
@@ -102,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(
@@ -115,10 +126,20 @@ 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) {
return new SpringMvcContract(this.parameterProcessors, feignConversionService); boolean decodeSlash = feignClientProperties == null
|| feignClientProperties.isDecodeSlash();
return new SpringMvcContract(this.parameterProcessors, feignConversionService,
decodeSlash);
} }
@Bean @Bean
@@ -149,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() {
@@ -168,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);
} }
} }
@@ -206,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.
@@ -16,21 +16,27 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import java.io.IOException;
import java.net.MalformedURLException; 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.Arrays;
import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
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;
@@ -43,14 +49,10 @@ import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AbstractClassTestingTypeFilter;
import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
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;
/** /**
@@ -58,6 +60,9 @@ import org.springframework.util.StringUtils;
* @author Jakub Narloch * @author Jakub Narloch
* @author Venil Noronha * @author Venil Noronha
* @author Gang Li * @author Gang Li
* @author Michal Domagala
* @author Marcin Grzejszczak
* @author Olga Maciaszek-Sharma
*/ */
class FeignClientsRegistrar class FeignClientsRegistrar
implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware { implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
@@ -165,60 +170,43 @@ class FeignClientsRegistrar
public void registerFeignClients(AnnotationMetadata metadata, public void registerFeignClients(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) { BeanDefinitionRegistry registry) {
ClassPathScanningCandidateComponentProvider scanner = getScanner();
scanner.setResourceLoader(this.resourceLoader);
Set<String> basePackages;
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) {
scanner.addIncludeFilter(annotationTypeFilter); ClassPathScanningCandidateComponentProvider scanner = getScanner();
basePackages = getBasePackages(metadata); scanner.setResourceLoader(this.resourceLoader);
scanner.addIncludeFilter(new AnnotationTypeFilter(FeignClient.class));
Set<String> basePackages = getBasePackages(metadata);
for (String basePackage : basePackages) {
candidateComponents.addAll(scanner.findCandidateComponents(basePackage));
}
} }
else { else {
final Set<String> clientClasses = new HashSet<>();
basePackages = new HashSet<>();
for (Class<?> clazz : clients) { for (Class<?> clazz : clients) {
basePackages.add(ClassUtils.getPackageName(clazz)); candidateComponents.add(new AnnotatedGenericBeanDefinition(clazz));
clientClasses.add(clazz.getCanonicalName());
} }
AbstractClassTestingTypeFilter filter = new AbstractClassTestingTypeFilter() {
@Override
protected boolean match(ClassMetadata metadata) {
String cleaned = metadata.getClassName().replaceAll("\\$", ".");
return clientClasses.contains(cleaned);
}
};
scanner.addIncludeFilter(
new AllTypeFilter(Arrays.asList(filter, annotationTypeFilter)));
} }
for (String basePackage : basePackages) { for (BeanDefinition candidateComponent : candidateComponents) {
Set<BeanDefinition> candidateComponents = scanner if (candidateComponent instanceof AnnotatedBeanDefinition) {
.findCandidateComponents(basePackage); // verify annotated class is an interface
for (BeanDefinition candidateComponent : candidateComponents) { AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
if (candidateComponent instanceof AnnotatedBeanDefinition) { AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
// verify annotated class is an interface Assert.isTrue(annotationMetadata.isInterface(),
AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent; "@FeignClient can only be specified on an interface");
AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
Assert.isTrue(annotationMetadata.isInterface(),
"@FeignClient can only be specified on an interface");
Map<String, Object> attributes = annotationMetadata Map<String, Object> attributes = annotationMetadata
.getAnnotationAttributes( .getAnnotationAttributes(FeignClient.class.getCanonicalName());
FeignClient.class.getCanonicalName());
String name = getClientName(attributes); String name = getClientName(attributes);
registerClientConfiguration(registry, name, registerClientConfiguration(registry, name,
attributes.get("configuration")); attributes.get("configuration"));
registerFeignClient(registry, annotationMetadata, attributes); registerFeignClient(registry, annotationMetadata, attributes);
}
} }
} }
} }
@@ -226,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);
} }
@@ -269,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");
@@ -276,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);
} }
@@ -360,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;
@@ -398,38 +435,4 @@ class FeignClientsRegistrar
this.environment = environment; this.environment = environment;
} }
/**
* Helper class to create a {@link TypeFilter} that matches if all the delegates
* match.
*
* @author Oliver Gierke
*/
private static class AllTypeFilter implements TypeFilter {
private final List<TypeFilter> delegates;
/**
* Creates a new {@link AllTypeFilter} to match if all the given delegates match.
* @param delegates must not be {@literal null}.
*/
AllTypeFilter(List<TypeFilter> delegates) {
Assert.notNull(delegates, "This argument is required, it must not be null");
this.delegates = delegates;
}
@Override
public boolean match(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
for (TypeFilter filter : this.delegates) {
if (!filter.match(metadataReader, metadataReaderFactory)) {
return false;
}
}
return true;
}
}
} }
@@ -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 {
}
}
@@ -75,7 +75,7 @@ public class MatrixVariableParameterProcessor implements AnnotatedParameterProce
private String expandMap(Object object) { private String expandMap(Object object) {
Map<String, Object> paramMap = (Map) object; Map<String, Object> paramMap = (Map) object;
return paramMap.keySet().stream() return paramMap.keySet().stream().filter(key -> paramMap.get(key) != null)
.map(key -> ";" + key + "=" + paramMap.get(key).toString()) .map(key -> ";" + key + "=" + paramMap.get(key).toString())
.collect(Collectors.joining()); .collect(Collectors.joining());
} }
@@ -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;
}
}
}
@@ -16,11 +16,14 @@
package org.springframework.cloud.openfeign.clientconfig; package org.springframework.cloud.openfeign.clientconfig;
import java.io.IOException;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import javax.annotation.PreDestroy; import javax.annotation.PreDestroy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.RegistryBuilder; import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.HttpClientConnectionManager;
@@ -48,6 +51,8 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnMissingBean(CloseableHttpClient.class) @ConditionalOnMissingBean(CloseableHttpClient.class)
public class HttpClientFeignConfiguration { public class HttpClientFeignConfiguration {
private static final Log LOG = LogFactory.getLog(HttpClientFeignConfiguration.class);
private final Timer connectionManagerTimer = new Timer( private final Timer connectionManagerTimer = new Timer(
"FeignApacheHttpClientConfiguration.connectionManagerTimer", true); "FeignApacheHttpClientConfiguration.connectionManagerTimer", true);
@@ -113,10 +118,17 @@ public class HttpClientFeignConfiguration {
} }
@PreDestroy @PreDestroy
public void destroy() throws Exception { public void destroy() {
this.connectionManagerTimer.cancel(); this.connectionManagerTimer.cancel();
if (this.httpClient != null) { if (this.httpClient != null) {
this.httpClient.close(); try {
this.httpClient.close();
}
catch (IOException e) {
if (LOG.isErrorEnabled()) {
LOG.error("Could not correctly close httpClient.");
}
}
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2016-2020 the original author or authors. * Copyright 2016-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,37 +16,30 @@
package org.springframework.cloud.openfeign.hateoas; package org.springframework.cloud.openfeign.hateoas;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore; 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.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration; import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration;
import org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration;
import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
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.hateoas.RepresentationModel; import org.springframework.hateoas.RepresentationModel;
import org.springframework.hateoas.mediatype.MessageResolver; import org.springframework.hateoas.mediatype.hal.HalMediaTypeConfiguration;
import org.springframework.hateoas.mediatype.hal.CurieProvider;
import org.springframework.hateoas.mediatype.hal.DefaultCurieProvider;
import org.springframework.hateoas.mediatype.hal.HalConfiguration;
import org.springframework.hateoas.mediatype.hal.Jackson2HalModule;
import org.springframework.hateoas.server.LinkRelationProvider;
import org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter; import org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter;
import static org.springframework.hateoas.MediaTypes.HAL_JSON; import static org.springframework.hateoas.MediaTypes.HAL_JSON;
/** /**
* @author Hector Espert * @author Hector Espert
* @author Olga Maciaszek-Sharma
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication @ConditionalOnWebApplication
@@ -54,41 +47,19 @@ import static org.springframework.hateoas.MediaTypes.HAL_JSON;
@AutoConfigureAfter({ JacksonAutoConfiguration.class, @AutoConfigureAfter({ JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
RepositoryRestMvcAutoConfiguration.class }) RepositoryRestMvcAutoConfiguration.class })
@AutoConfigureBefore(HypermediaAutoConfiguration.class)
public class FeignHalAutoConfiguration { public class FeignHalAutoConfiguration {
@Bean @Bean
@ConditionalOnBean(HalMediaTypeConfiguration.class)
@ConditionalOnMissingBean @ConditionalOnMissingBean
public TypeConstrainedMappingJackson2HttpMessageConverter halJacksonHttpMessageConverter( public TypeConstrainedMappingJackson2HttpMessageConverter halJacksonHttpMessageConverter(
ObjectProvider<ObjectMapper> objectMapper, ObjectProvider<ObjectMapper> objectMapper,
ObjectProvider<HalConfiguration> halConfiguration, HalMediaTypeConfiguration halConfiguration) {
ObjectProvider<MessageResolver> messageResolver,
ObjectProvider<CurieProvider> curieProvider,
ObjectProvider<LinkRelationProvider> linkRelationProvider) {
ObjectMapper mapper = objectMapper.getIfAvailable(ObjectMapper::new).copy(); ObjectMapper mapper = objectMapper.getIfAvailable(ObjectMapper::new).copy();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); halConfiguration.configureObjectMapper(mapper);
HalConfiguration configuration = halConfiguration
.getIfAvailable(HalConfiguration::new);
CurieProvider curieProviderInstance = curieProvider
.getIfAvailable(() -> new DefaultCurieProvider(Collections.emptyMap()));
Jackson2HalModule.HalHandlerInstantiator halHandlerInstantiator = new Jackson2HalModule.HalHandlerInstantiator(
linkRelationProvider.getIfAvailable(), curieProviderInstance,
messageResolver.getIfAvailable(), configuration);
mapper.setHandlerInstantiator(halHandlerInstantiator);
if (!Jackson2HalModule.isAlreadyRegisteredIn(mapper)) {
Jackson2HalModule halModule = new Jackson2HalModule();
mapper.registerModule(halModule);
}
TypeConstrainedMappingJackson2HttpMessageConverter converter = new TypeConstrainedMappingJackson2HttpMessageConverter( TypeConstrainedMappingJackson2HttpMessageConverter converter = new TypeConstrainedMappingJackson2HttpMessageConverter(
RepresentationModel.class); RepresentationModel.class);
converter.setSupportedMediaTypes(Arrays.asList(HAL_JSON)); converter.setSupportedMediaTypes(Collections.singletonList(HAL_JSON));
converter.setObjectMapper(mapper); converter.setObjectMapper(mapper);
return converter; return converter;
} }
@@ -16,12 +16,20 @@
package org.springframework.cloud.openfeign.loadbalancer; package org.springframework.cloud.openfeign.loadbalancer;
import java.util.List;
import feign.Client; import feign.Client;
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.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.loadbalancer.blocking.client.BlockingLoadBalancerClient;
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.core.annotation.AnnotationAwareOrderComparator;
/** /**
* Configuration instantiating a {@link BlockingLoadBalancerClient}-based {@link Client} * Configuration instantiating a {@link BlockingLoadBalancerClient}-based {@link Client}
@@ -35,9 +43,24 @@ class DefaultFeignLoadBalancerConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(BlockingLoadBalancerClient loadBalancerClient) { public Client feignClient(BlockingLoadBalancerClient loadBalancerClient) {
return new FeignBlockingLoadBalancerClient(new Client.Default(null, null), return new FeignBlockingLoadBalancerClient(new Client.Default(null, null),
loadBalancerClient); 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,
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) {
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories);
return new RetryableFeignBlockingLoadBalancerClient(
new Client.Default(null, null), loadBalancerClient,
loadBalancedRetryFactories.get(0));
}
} }
@@ -72,12 +72,15 @@ public class FeignBlockingLoadBalancerClient implements Client {
} }
String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri) String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri)
.toString(); .toString();
Request newRequest = Request.create(request.httpMethod(), reconstructedUrl, Request newRequest = buildRequest(request, reconstructedUrl);
request.headers(), request.body(), request.charset(),
request.requestTemplate());
return delegate.execute(newRequest, options); return delegate.execute(newRequest, options);
} }
protected Request buildRequest(Request request, String reconstructedUrl) {
return Request.create(request.httpMethod(), reconstructedUrl, request.headers(),
request.body(), request.charset(), request.requestTemplate());
}
// Visible for Sleuth instrumentation // Visible for Sleuth instrumentation
public Client getDelegate() { public Client getDelegate() {
return delegate; return delegate;
@@ -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.
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign.loadbalancer; package org.springframework.cloud.openfeign.loadbalancer;
import java.util.List;
import feign.Client; import feign.Client;
import feign.httpclient.ApacheHttpClient; import feign.httpclient.ApacheHttpClient;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
@@ -24,32 +26,54 @@ 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.ConditionalOnProperty; 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.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.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
/** /**
* Configuration instantiating a {@link BlockingLoadBalancerClient}-based {@link Client} * Configuration instantiating a {@link BlockingLoadBalancerClient}-based {@link Client}
* 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 {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(BlockingLoadBalancerClient loadBalancerClient, public Client feignClient(BlockingLoadBalancerClient loadBalancerClient,
HttpClient httpClient) { HttpClient httpClient) {
ApacheHttpClient delegate = new ApacheHttpClient(httpClient); ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient); 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 httpClient,
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) {
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories);
ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient,
loadBalancedRetryFactories.get(0));
}
} }
@@ -0,0 +1,50 @@
/*
* 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.loadbalancer;
import java.io.ByteArrayInputStream;
import java.net.URI;
import feign.Response;
import org.springframework.cloud.client.loadbalancer.RetryableStatusCodeException;
/**
* A {@link RetryableStatusCodeException} for {@link Response}s.
*
* @author Ryan Baxter
*/
public class LoadBalancerResponseStatusCodeException
extends RetryableStatusCodeException {
private final Response response;
public LoadBalancerResponseStatusCodeException(String serviceId, Response response,
byte[] body, URI uri) {
super(serviceId, response.status(), response, uri);
this.response = Response.builder()
.body(new ByteArrayInputStream(body), body.length)
.headers(response.headers()).reason(response.reason())
.status(response.status()).request(response.request()).build();
}
@Override
public Response getResponse() {
return this.response;
}
}
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign.loadbalancer; package org.springframework.cloud.openfeign.loadbalancer;
import java.util.List;
import feign.Client; import feign.Client;
import feign.okhttp.OkHttpClient; import feign.okhttp.OkHttpClient;
@@ -23,11 +25,14 @@ 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.ConditionalOnProperty; 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.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.cloud.openfeign.clientconfig.OkHttpFeignConfiguration; import org.springframework.cloud.openfeign.clientconfig.OkHttpFeignConfiguration;
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.core.annotation.AnnotationAwareOrderComparator;
/** /**
* Configuration instantiating a {@link BlockingLoadBalancerClient}-based {@link Client} * Configuration instantiating a {@link BlockingLoadBalancerClient}-based {@link Client}
@@ -45,10 +50,26 @@ class OkHttpFeignLoadBalancerConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(okhttp3.OkHttpClient okHttpClient, public Client feignClient(okhttp3.OkHttpClient okHttpClient,
BlockingLoadBalancerClient loadBalancerClient) { BlockingLoadBalancerClient loadBalancerClient) {
OkHttpClient delegate = new OkHttpClient(okHttpClient); OkHttpClient delegate = new OkHttpClient(okHttpClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient); 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,
okhttp3.OkHttpClient okHttpClient,
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) {
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories);
OkHttpClient delegate = new OkHttpClient(okHttpClient);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient,
loadBalancedRetryFactories.get(0));
}
} }
@@ -0,0 +1,56 @@
/*
* 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.loadbalancer;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.retry.support.RetryTemplate;
/**
* A condition that verifies that {@link RetryTemplate} is on the classpath, a
* {@link LoadBalancedRetryFactory} bean is present and
* <code>spring.cloud.loadbalancer.retry.enabled</code> is not set to <code>false</code>.
*
* @author Olga Maciaszek-Sharma
* @since 2.2.6
*/
public class OnRetryNotEnabledCondition extends AnyNestedCondition {
public OnRetryNotEnabledCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnMissingClass("org.springframework.retry.support.RetryTemplate")
static class OnNoRetryTemplateCondition {
}
@ConditionalOnMissingBean(LoadBalancedRetryFactory.class)
static class OnRetryFactoryCondition {
}
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled",
havingValue = "false")
static class OnLoadBalancerRetryEnabledCondition {
}
}
@@ -0,0 +1,190 @@
/*
* 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.loadbalancer;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import feign.Client;
import feign.Request;
import feign.Response;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRecoveryCallback;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.retry.RetryListener;
import org.springframework.retry.backoff.BackOffPolicy;
import org.springframework.retry.backoff.NoBackOffPolicy;
import org.springframework.retry.policy.NeverRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.util.StreamUtils;
/**
* A {@link Client} implementation that provides Spring Retry support for requests
* load-balanced with Spring Cloud LoadBalancer.
*
* @author Olga Maciaszek-Sharma
* @since 2.2.6
*/
public class RetryableFeignBlockingLoadBalancerClient implements Client {
private static final Log LOG = LogFactory
.getLog(FeignBlockingLoadBalancerClient.class);
private final Client delegate;
private final BlockingLoadBalancerClient loadBalancerClient;
private final LoadBalancedRetryFactory loadBalancedRetryFactory;
public RetryableFeignBlockingLoadBalancerClient(Client delegate,
BlockingLoadBalancerClient loadBalancerClient,
LoadBalancedRetryFactory loadBalancedRetryFactory) {
this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient;
this.loadBalancedRetryFactory = loadBalancedRetryFactory;
}
@Override
public Response execute(Request request, Request.Options options) throws IOException {
final URI originalUri = URI.create(request.url());
String serviceId = originalUri.getHost();
final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory
.createRetryPolicy(serviceId, loadBalancerClient);
RetryTemplate retryTemplate = buildRetryTemplate(serviceId, request, retryPolicy);
return retryTemplate.execute(context -> {
Request feignRequest = null;
// On retries the policy will choose the server and set it in the context
// and extract the server and update the request being made
if (context instanceof LoadBalancedRetryContext) {
ServiceInstance serviceInstance = ((LoadBalancedRetryContext) context)
.getServiceInstance();
if (serviceInstance != null) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format(
"Using service instance from LoadBalancedRetryContext: %s",
serviceInstance));
}
String reconstructedUrl = loadBalancerClient
.reconstructURI(serviceInstance, originalUri).toString();
feignRequest = buildRequest(request, reconstructedUrl);
}
}
if (feignRequest == null) {
if (LOG.isWarnEnabled()) {
LOG.warn(
"Service instance was not resolved, executing the original request");
}
feignRequest = request;
}
Response response = delegate.execute(feignRequest, options);
int responseStatus = response.status();
if (retryPolicy != null && retryPolicy.retryableStatusCode(responseStatus)) {
if (LOG.isDebugEnabled()) {
LOG.debug(
String.format("Retrying on status code: %d", responseStatus));
}
byte[] byteArray = response.body() == null ? new byte[] {}
: StreamUtils.copyToByteArray(response.body().asInputStream());
response.close();
throw new LoadBalancerResponseStatusCodeException(serviceId, response,
byteArray, URI.create(request.url()));
}
return response;
}, new LoadBalancedRecoveryCallback<Response, Response>() {
@Override
protected Response createResponse(Response response, URI uri) {
return response;
}
});
}
protected Request buildRequest(Request request, String reconstructedUrl) {
return Request.create(request.httpMethod(), reconstructedUrl, request.headers(),
request.body(), request.charset(), request.requestTemplate());
}
private RetryTemplate buildRetryTemplate(String serviceId, Request request,
LoadBalancedRetryPolicy retryPolicy) {
RetryTemplate retryTemplate = new RetryTemplate();
BackOffPolicy backOffPolicy = this.loadBalancedRetryFactory
.createBackOffPolicy(serviceId);
retryTemplate.setBackOffPolicy(
backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
RetryListener[] retryListeners = this.loadBalancedRetryFactory
.createRetryListeners(serviceId);
if (retryListeners != null && retryListeners.length != 0) {
retryTemplate.setListeners(retryListeners);
}
retryTemplate.setRetryPolicy(retryPolicy == null ? new NeverRetryPolicy()
: new InterceptorRetryPolicy(toHttpRequest(request), retryPolicy,
loadBalancerClient, serviceId));
return retryTemplate;
}
// Visible for Sleuth instrumentation
public Client getDelegate() {
return delegate;
}
private HttpRequest toHttpRequest(Request request) {
return new HttpRequest() {
@Override
public HttpMethod getMethod() {
return HttpMethod.resolve(request.httpMethod().name());
}
@Override
public String getMethodValue() {
return getMethod().name();
}
@Override
public URI getURI() {
return URI.create(request.url());
}
@Override
public HttpHeaders getHeaders() {
Map<String, List<String>> headers = new HashMap<>();
Map<String, Collection<String>> feignHeaders = request.headers();
for (String key : feignHeaders.keySet()) {
headers.put(key, new ArrayList<>(feignHeaders.get(key)));
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(headers);
return httpHeaders;
}
};
}
}
@@ -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,9 +24,9 @@ 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.ClientException;
import com.netflix.client.ClientRequest; import com.netflix.client.ClientRequest;
import com.netflix.client.IResponse; import com.netflix.client.IResponse;
import com.netflix.client.RequestSpecificRetryHandler; import com.netflix.client.RequestSpecificRetryHandler;
@@ -66,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
@@ -84,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);
@@ -97,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);
} }
@@ -138,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() {
@@ -169,7 +174,7 @@ public class FeignLoadBalancer extends
Map<String, Collection<String>> feignHeaders = RibbonRequest.this Map<String, Collection<String>> feignHeaders = RibbonRequest.this
.toRequest().headers(); .toRequest().headers();
for (String key : feignHeaders.keySet()) { for (String key : feignHeaders.keySet()) {
headers.put(key, new ArrayList<String>(feignHeaders.get(key))); headers.put(key, new ArrayList<>(feignHeaders.get(key)));
} }
HttpHeaders httpHeaders = new HttpHeaders(); HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(headers); httpHeaders.putAll(headers);
@@ -180,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,38 +211,38 @@ public class FeignLoadBalancer extends
} }
@Override @Override
public Object getPayload() throws ClientException { 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
@@ -36,8 +36,6 @@ import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient; import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.RibbonProperties; import org.springframework.cloud.netflix.ribbon.RibbonProperties;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector; import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.RetryListener; import org.springframework.retry.RetryListener;
import org.springframework.retry.backoff.BackOffPolicy; import org.springframework.retry.backoff.BackOffPolicy;
import org.springframework.retry.backoff.NoBackOffPolicy; import org.springframework.retry.backoff.NoBackOffPolicy;
@@ -91,39 +89,34 @@ public class RetryableFeignLoadBalancer extends FeignLoadBalancer
retryTemplate.setRetryPolicy(retryPolicy == null ? new NeverRetryPolicy() retryTemplate.setRetryPolicy(retryPolicy == null ? new NeverRetryPolicy()
: new FeignRetryPolicy(request.toHttpRequest(), retryPolicy, this, : new FeignRetryPolicy(request.toHttpRequest(), retryPolicy, this,
this.getClientName())); this.getClientName()));
return retryTemplate.execute(new RetryCallback<RibbonResponse, IOException>() { return retryTemplate.execute(retryContext -> {
@Override Request feignRequest = null;
public RibbonResponse doWithRetry(RetryContext retryContext) // on retries the policy will choose the server and set it in the context
throws IOException { // extract the server and update the request being made
Request feignRequest = null; if (retryContext instanceof LoadBalancedRetryContext) {
// on retries the policy will choose the server and set it in the context ServiceInstance service = ((LoadBalancedRetryContext) retryContext)
// extract the server and update the request being made .getServiceInstance();
if (retryContext instanceof LoadBalancedRetryContext) { if (service != null) {
ServiceInstance service = ((LoadBalancedRetryContext) retryContext) feignRequest = ((RibbonRequest) request
.getServiceInstance(); .replaceUri(reconstructURIWithServer(
if (service != null) { new Server(service.getHost(), service.getPort()),
feignRequest = ((RibbonRequest) request request.getUri()))).toRequest();
.replaceUri(reconstructURIWithServer(
new Server(service.getHost(), service.getPort()),
request.getUri()))).toRequest();
}
} }
if (feignRequest == null) {
feignRequest = request.toRequest();
}
Response response = request.client().execute(feignRequest, options);
if (retryPolicy != null
&& retryPolicy.retryableStatusCode(response.status())) {
byte[] byteArray = response.body() == null ? new byte[] {}
: StreamUtils
.copyToByteArray(response.body().asInputStream());
response.close();
throw new RibbonResponseStatusCodeException(
RetryableFeignLoadBalancer.this.clientName, response,
byteArray, request.getUri());
}
return new RibbonResponse(request.getUri(), response);
} }
if (feignRequest == null) {
feignRequest = request.toRequest();
}
Response response = request.client().execute(feignRequest, options);
if (retryPolicy != null
&& retryPolicy.retryableStatusCode(response.status())) {
byte[] byteArray = response.body() == null ? new byte[] {}
: StreamUtils.copyToByteArray(response.body().asInputStream());
response.close();
throw new RibbonResponseStatusCodeException(
RetryableFeignLoadBalancer.this.clientName, response, byteArray,
request.getUri());
}
return new RibbonResponse(request.getUri(), response);
}, new LoadBalancedRecoveryCallback<RibbonResponse, Response>() { }, new LoadBalancedRecoveryCallback<RibbonResponse, Response>() {
@Override @Override
protected RibbonResponse createResponse(Response response, URI uri) { protected RibbonResponse createResponse(Response response, URI uri) {
@@ -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,11 @@ 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.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;
@@ -48,6 +49,10 @@ import org.springframework.web.multipart.MultipartFile;
import static org.springframework.cloud.openfeign.support.FeignUtils.getHeaders; import static org.springframework.cloud.openfeign.support.FeignUtils.getHeaders;
import static org.springframework.cloud.openfeign.support.FeignUtils.getHttpHeaders; import static org.springframework.cloud.openfeign.support.FeignUtils.getHttpHeaders;
import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED;
import static org.springframework.http.MediaType.MULTIPART_FORM_DATA;
import static org.springframework.http.MediaType.MULTIPART_MIXED;
import static org.springframework.http.MediaType.MULTIPART_RELATED;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
@@ -55,7 +60,10 @@ 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
* @author Can Bezmen
*/ */
@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 +72,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,8 +105,8 @@ public class SpringEncoder implements Encoder {
requestContentType = MediaType.valueOf(type); requestContentType = MediaType.valueOf(type);
} }
if (Objects.equals(requestContentType, MediaType.MULTIPART_FORM_DATA)) { if (isFormRelatedContentType(requestContentType)) {
this.springFormEncoder.encode(requestBody, bodyType, request); springFormEncoder.encode(requestBody, bodyType, request);
return; return;
} }
else { else {
@@ -100,58 +116,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 : 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 +229,29 @@ public class SpringEncoder implements Encoder {
} }
} }
private boolean isFormRelatedContentType(MediaType requestContentType) {
return isMultipartType(requestContentType)
|| isFormUrlEncoded(requestContentType);
}
private boolean isMultipartType(MediaType requestContentType) {
return Arrays.asList(MULTIPART_FORM_DATA, MULTIPART_MIXED, MULTIPART_RELATED)
.contains(requestContentType);
}
private boolean isFormUrlEncoded(MediaType requestContentType) {
return Objects.equals(APPLICATION_FORM_URLENCODED, 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();
@@ -202,21 +259,21 @@ public class SpringEncoder implements Encoder {
private final HttpHeaders httpHeaders; private final HttpHeaders httpHeaders;
private FeignOutputMessage(RequestTemplate request) { private FeignOutputMessage(RequestTemplate request) {
this.httpHeaders = getHttpHeaders(request.headers()); httpHeaders = getHttpHeaders(request.headers());
} }
@Override @Override
public OutputStream getBody() throws IOException { public OutputStream getBody() throws IOException {
return this.outputStream; return outputStream;
} }
@Override @Override
public HttpHeaders getHeaders() { public HttpHeaders getHeaders() {
return this.httpHeaders; return httpHeaders;
} }
public ByteArrayOutputStream getOutputStream() { public ByteArrayOutputStream getOutputStream() {
return this.outputStream; return outputStream;
} }
} }
@@ -35,6 +35,8 @@ import feign.Feign;
import feign.MethodMetadata; import feign.MethodMetadata;
import feign.Param; import feign.Param;
import feign.Request; import feign.Request;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor; import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.cloud.openfeign.CollectionFormat; import org.springframework.cloud.openfeign.CollectionFormat;
@@ -78,10 +80,13 @@ import static org.springframework.core.annotation.AnnotatedElementUtils.findMerg
* @author Aaron Whiteside * @author Aaron Whiteside
* @author Artyom Romanenko * @author Artyom Romanenko
* @author Darren Foong * @author Darren Foong
* @author Ram Anaswara
*/ */
public class SpringMvcContract extends Contract.BaseContract public class SpringMvcContract extends Contract.BaseContract
implements ResourceLoaderAware { implements ResourceLoaderAware {
private static final Log LOG = LogFactory.getLog(SpringMvcContract.class);
private static final String ACCEPT = "Accept"; private static final String ACCEPT = "Accept";
private static final String CONTENT_TYPE = "Content-Type"; private static final String CONTENT_TYPE = "Content-Type";
@@ -104,6 +109,8 @@ public class SpringMvcContract extends Contract.BaseContract
private ResourceLoader resourceLoader = new DefaultResourceLoader(); private ResourceLoader resourceLoader = new DefaultResourceLoader();
private boolean decodeSlash;
public SpringMvcContract() { public SpringMvcContract() {
this(Collections.emptyList()); this(Collections.emptyList());
} }
@@ -116,6 +123,12 @@ public class SpringMvcContract extends Contract.BaseContract
public SpringMvcContract( public SpringMvcContract(
List<AnnotatedParameterProcessor> annotatedParameterProcessors, List<AnnotatedParameterProcessor> annotatedParameterProcessors,
ConversionService conversionService) { ConversionService conversionService) {
this(annotatedParameterProcessors, conversionService, true);
}
public SpringMvcContract(
List<AnnotatedParameterProcessor> annotatedParameterProcessors,
ConversionService conversionService, boolean decodeSlash) {
Assert.notNull(annotatedParameterProcessors, Assert.notNull(annotatedParameterProcessors,
"Parameter processors can not be null."); "Parameter processors can not be null.");
Assert.notNull(conversionService, "ConversionService can not be null."); Assert.notNull(conversionService, "ConversionService can not be null.");
@@ -126,6 +139,7 @@ public class SpringMvcContract extends Contract.BaseContract
annotatedArgumentProcessors = toAnnotatedArgumentProcessorMap(processors); annotatedArgumentProcessors = toAnnotatedArgumentProcessorMap(processors);
this.conversionService = conversionService; this.conversionService = conversionService;
convertingExpanderFactory = new ConvertingExpanderFactory(conversionService); convertingExpanderFactory = new ConvertingExpanderFactory(conversionService);
this.decodeSlash = decodeSlash;
} }
private static TypeDescriptor createTypeDescriptor(Method method, int paramIndex) { private static TypeDescriptor createTypeDescriptor(Method method, int paramIndex) {
@@ -171,46 +185,19 @@ public class SpringMvcContract extends Contract.BaseContract
@Override @Override
protected void processAnnotationOnClass(MethodMetadata data, Class<?> clz) { protected void processAnnotationOnClass(MethodMetadata data, Class<?> clz) {
if (clz.getInterfaces().length == 0) { RequestMapping classAnnotation = findMergedAnnotation(clz, RequestMapping.class);
RequestMapping classAnnotation = findMergedAnnotation(clz, if (classAnnotation != null) {
RequestMapping.class); LOG.error("Cannot process class: " + clz.getName()
if (classAnnotation != null) { + ". @RequestMapping annotation is not allowed on @FeignClient interfaces.");
// Prepend path from class annotation if specified throw new IllegalArgumentException(
if (classAnnotation.value().length > 0) { "@RequestMapping annotation not allowed on @FeignClient interfaces");
String pathValue = emptyToNull(classAnnotation.value()[0]);
pathValue = resolve(pathValue);
if (!pathValue.startsWith("/")) {
pathValue = "/" + pathValue;
}
data.template().uri(pathValue);
}
}
} }
} }
@Override @Override
public MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method method) { public MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method method) {
processedMethods.put(Feign.configKey(targetType, method), method); processedMethods.put(Feign.configKey(targetType, method), method);
MethodMetadata md = super.parseAndValidateMetadata(targetType, method); return super.parseAndValidateMetadata(targetType, method);
RequestMapping classAnnotation = findMergedAnnotation(targetType,
RequestMapping.class);
if (classAnnotation != null) {
// produces - use from class annotation only if method has not specified this
if (!md.template().headers().containsKey(ACCEPT)) {
parseProduces(md, method, classAnnotation);
}
// consumes -- use from class annotation only if method has not specified this
if (!md.template().headers().containsKey(CONTENT_TYPE)) {
parseConsumes(md, method, classAnnotation);
}
// headers -- class annotation is inherited to methods, always write these if
// present
parseHeaders(md, method, classAnnotation);
}
return md;
} }
@Override @Override
@@ -247,6 +234,9 @@ public class SpringMvcContract extends Contract.BaseContract
pathValue = "/" + pathValue; pathValue = "/" + pathValue;
} }
data.template().uri(pathValue, true); data.template().uri(pathValue, true);
if (data.template().decodeSlash() != decodeSlash) {
data.template().decodeSlash(decodeSlash);
}
} }
} }
@@ -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)));
}
}
@@ -0,0 +1,180 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 feign.Feign;
import feign.Logger;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.Order;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Matt King
* @author Sam Kruglov
*/
public class FeignBuilderCustomizerTests {
@Test
public void testBuilderCustomizer() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
FeignBuilderCustomizerTests.SampleConfiguration2.class);
FeignClientFactoryBean clientFactoryBean = context
.getBean(FeignClientFactoryBean.class);
FeignContext feignContext = context.getBean(FeignContext.class);
Feign.Builder builder = clientFactoryBean.feign(feignContext);
assertFeignBuilderField(builder, "logLevel", Logger.Level.HEADERS);
assertFeignBuilderField(builder, "decode404", true);
context.close();
}
private void assertFeignBuilderField(Feign.Builder builder, String fieldName,
Object expectedValue) {
Field builderField = ReflectionUtils.findField(Feign.Builder.class, fieldName);
ReflectionUtils.makeAccessible(builderField);
Object value = ReflectionUtils.getField(builderField, builder);
assertThat(value).as("Expected value for the field '" + fieldName + "':")
.isEqualTo(expectedValue);
}
@Test
public void testBuildCustomizerOrdered() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
FeignBuilderCustomizerTests.SampleConfiguration3.class);
FeignClientFactoryBean clientFactoryBean = context
.getBean(FeignClientFactoryBean.class);
FeignContext feignContext = context.getBean(FeignContext.class);
Feign.Builder builder = clientFactoryBean.feign(feignContext);
assertFeignBuilderField(builder, "logLevel", Logger.Level.FULL);
assertFeignBuilderField(builder, "decode404", true);
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() {
FeignClientFactoryBean feignClientFactoryBean = new FeignClientFactoryBean();
feignClientFactoryBean.setContextId("test");
feignClientFactoryBean.setName("test");
feignClientFactoryBean.setType(FeignClientFactoryTests.TestType.class);
feignClientFactoryBean.setPath("");
feignClientFactoryBean.setUrl("http://some.absolute.url");
return feignClientFactoryBean;
}
@Configuration(proxyBeanMethods = false)
@Import(FeignClientsConfiguration.class)
protected static class SampleConfiguration2 {
@Bean
FeignContext feignContext() {
return new FeignContext();
}
@Bean
FeignClientProperties feignClientProperties() {
return new FeignClientProperties();
}
@Bean
FeignBuilderCustomizer feignBuilderCustomizer() {
return builder -> builder.logLevel(Logger.Level.HEADERS);
}
@Bean
FeignBuilderCustomizer feignBuilderCustomizer2() {
return Feign.Builder::decode404;
}
@Bean
FeignClientFactoryBean feignClientFactoryBean() {
return defaultFeignClientFactoryBean();
}
}
@Configuration(proxyBeanMethods = false)
@Import(FeignClientsConfiguration.class)
protected static class SampleConfiguration3 {
@Bean
FeignContext feignContext() {
return new FeignContext();
}
@Bean
FeignClientProperties feignClientProperties() {
return new FeignClientProperties();
}
@Bean
@Order(1)
FeignBuilderCustomizer feignBuilderCustomizer() {
return builder -> builder.logLevel(Logger.Level.HEADERS);
}
@Bean
@Order(2)
FeignBuilderCustomizer feignBuilderCustomizer1() {
return builder -> builder.logLevel(Logger.Level.FULL);
}
@Bean
FeignBuilderCustomizer feignBuilderCustomizer2() {
return Feign.Builder::decode404;
}
@Bean
FeignClientFactoryBean feignClientFactoryBean() {
return defaultFeignClientFactoryBean();
}
}
}
@@ -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;
@@ -24,7 +26,6 @@ import feign.QueryMapEncoder;
import feign.Request; import feign.Request;
import feign.RequestInterceptor; import feign.RequestInterceptor;
import feign.RequestLine; import feign.RequestLine;
import feign.RequestTemplate;
import feign.Retryer; import feign.Retryer;
import feign.auth.BasicAuthRequestInterceptor; import feign.auth.BasicAuthRequestInterceptor;
import feign.codec.Decoder; import feign.codec.Decoder;
@@ -34,8 +35,7 @@ import feign.hystrix.HystrixFeign;
import feign.optionals.OptionalDecoder; import feign.optionals.OptionalDecoder;
import feign.querymap.BeanQueryMapEncoder; import feign.querymap.BeanQueryMapEncoder;
import feign.slf4j.Slf4jLogger; import feign.slf4j.Slf4jLogger;
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.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
@@ -47,19 +47,17 @@ 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.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
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
*/ */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = FeignClientOverrideDefaultsTests.TestConfiguration.class) @SpringBootTest(classes = FeignClientOverrideDefaultsTests.TestConfiguration.class)
@DirtiesContext @DirtiesContext
public class FeignClientOverrideDefaultsTests { class FeignClientOverrideDefaultsTests {
@Autowired @Autowired
private FeignContext context; private FeignContext context;
@@ -71,92 +69,90 @@ public class FeignClientOverrideDefaultsTests {
private BarClient bar; private BarClient bar;
@Test @Test
public void clientsAvailable() { void clientsAvailable() {
assertThat(this.foo).isNotNull(); assertThat(foo).isNotNull();
assertThat(this.bar).isNotNull(); assertThat(bar).isNotNull();
} }
@Test @Test
public void overrideDecoder() { void overrideDecoder() {
Decoder.Default.class.cast(this.context.getInstance("foo", Decoder.class)); Decoder.Default.class.cast(context.getInstance("foo", Decoder.class));
OptionalDecoder.class.cast(this.context.getInstance("bar", Decoder.class)); OptionalDecoder.class.cast(context.getInstance("bar", Decoder.class));
} }
@Test @Test
public void overrideEncoder() { void overrideEncoder() {
Encoder.Default.class.cast(this.context.getInstance("foo", Encoder.class)); Encoder.Default.class.cast(context.getInstance("foo", Encoder.class));
PageableSpringEncoder.class.cast(this.context.getInstance("bar", Encoder.class)); PageableSpringEncoder.class.cast(context.getInstance("bar", Encoder.class));
} }
@Test @Test
public void overrideLogger() { void overrideLogger() {
Logger.JavaLogger.class.cast(this.context.getInstance("foo", Logger.class)); Logger.JavaLogger.class.cast(context.getInstance("foo", Logger.class));
Slf4jLogger.class.cast(this.context.getInstance("bar", Logger.class)); Slf4jLogger.class.cast(context.getInstance("bar", Logger.class));
} }
@Test @Test
public void overrideContract() { void overrideContract() {
Contract.Default.class.cast(this.context.getInstance("foo", Contract.class)); Contract.Default.class.cast(context.getInstance("foo", Contract.class));
SpringMvcContract.class.cast(this.context.getInstance("bar", Contract.class)); SpringMvcContract.class.cast(context.getInstance("bar", Contract.class));
} }
@Test @Test
public void overrideLoggerLevel() { void overrideLoggerLevel() {
assertThat(this.context.getInstance("foo", Logger.Level.class)).isNull(); assertThat(context.getInstance("foo", Logger.Level.class)).isNull();
assertThat(this.context.getInstance("bar", Logger.Level.class)) assertThat(context.getInstance("bar", Logger.Level.class))
.isEqualTo(Logger.Level.HEADERS); .isEqualTo(Logger.Level.HEADERS);
} }
@Test @Test
public void overrideRetryer() { void overrideRetryer() {
assertThat(this.context.getInstance("foo", Retryer.class)) assertThat(context.getInstance("foo", Retryer.class))
.isEqualTo(Retryer.NEVER_RETRY); .isEqualTo(Retryer.NEVER_RETRY);
Retryer.Default.class.cast(this.context.getInstance("bar", Retryer.class)); Retryer.Default.class.cast(context.getInstance("bar", Retryer.class));
} }
@Test @Test
public void overrideErrorDecoder() { void overrideErrorDecoder() {
assertThat(this.context.getInstance("foo", ErrorDecoder.class)).isNull(); assertThat(context.getInstance("foo", ErrorDecoder.class)).isNull();
ErrorDecoder.Default.class ErrorDecoder.Default.class.cast(context.getInstance("bar", ErrorDecoder.class));
.cast(this.context.getInstance("bar", ErrorDecoder.class));
} }
@Test @Test
public void overrideBuilder() { void overrideBuilder() {
HystrixFeign.Builder.class HystrixFeign.Builder.class.cast(context.getInstance("foo", Feign.Builder.class));
.cast(this.context.getInstance("foo", Feign.Builder.class)); Feign.Builder.class.cast(context.getInstance("bar", Feign.Builder.class));
Feign.Builder.class.cast(this.context.getInstance("bar", Feign.Builder.class));
} }
@Test @Test
public void overrideRequestOptions() { void overrideRequestOptions() {
assertThat(this.context.getInstance("foo", Request.Options.class)).isNull(); assertThat(context.getInstance("foo", Request.Options.class)).isNull();
Request.Options options = this.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
public void overrideQueryMapEncoder() { void overrideQueryMapEncoder() {
QueryMapEncoder.Default.class QueryMapEncoder.Default.class
.cast(this.context.getInstance("foo", QueryMapEncoder.class)); .cast(context.getInstance("foo", QueryMapEncoder.class));
BeanQueryMapEncoder.class BeanQueryMapEncoder.class.cast(context.getInstance("bar", QueryMapEncoder.class));
.cast(this.context.getInstance("bar", QueryMapEncoder.class));
} }
@Test @Test
public void addRequestInterceptor() { void addRequestInterceptor() {
assertThat(this.context.getInstances("foo", RequestInterceptor.class).size()) assertThat(context.getInstances("foo", RequestInterceptor.class).size())
.isEqualTo(1); .isEqualTo(1);
assertThat(this.context.getInstances("bar", RequestInterceptor.class).size()) assertThat(context.getInstances("bar", RequestInterceptor.class).size())
.isEqualTo(2); .isEqualTo(2);
} }
@Test @Test
public void exceptionPropagationPolicy() { void exceptionPropagationPolicy() {
assertThat(this.context.getInstances("foo", ExceptionPropagationPolicy.class)) assertThat(context.getInstances("foo", ExceptionPropagationPolicy.class))
.isNull(); .isEmpty();
assertThat(this.context.getInstances("bar", ExceptionPropagationPolicy.class)) assertThat(context.getInstances("bar", ExceptionPropagationPolicy.class))
.containsValues(ExceptionPropagationPolicy.UNWRAP); .containsValues(ExceptionPropagationPolicy.UNWRAP);
} }
@@ -173,7 +169,7 @@ public class FeignClientOverrideDefaultsTests {
configuration = BarConfiguration.class) configuration = BarConfiguration.class)
interface BarClient { interface BarClient {
@RequestMapping(value = "/", method = RequestMethod.GET) @GetMapping("/")
String get(); String get();
} }
@@ -186,10 +182,7 @@ public class FeignClientOverrideDefaultsTests {
@Bean @Bean
RequestInterceptor defaultRequestInterceptor() { RequestInterceptor defaultRequestInterceptor() {
return new RequestInterceptor() { return template -> {
@Override
public void apply(RequestTemplate template) {
}
}; };
} }
@@ -248,7 +241,8 @@ public 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.
@@ -22,9 +22,15 @@ import java.lang.reflect.Proxy;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.net.SocketTimeoutException; import java.net.SocketTimeoutException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@@ -55,8 +61,11 @@ import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
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;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@@ -66,6 +75,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
/** /**
* @author Eko Kurniawan Khannedy * @author Eko Kurniawan Khannedy
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Ilia Ilinykh
*/ */
@SuppressWarnings("FieldMayBeFinal") @SuppressWarnings("FieldMayBeFinal")
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@@ -92,6 +102,10 @@ public class FeignClientUsingPropertiesTests {
private FeignClientFactoryBean formFactoryBean; private FeignClientFactoryBean formFactoryBean;
private FeignClientFactoryBean defaultHeadersAndQuerySingleParamsFeignClientFactoryBean;
private FeignClientFactoryBean defaultHeadersAndQueryMultipleParamsFeignClientFactoryBean;
public FeignClientUsingPropertiesTests() { public FeignClientUsingPropertiesTests() {
fooFactoryBean = new FeignClientFactoryBean(); fooFactoryBean = new FeignClientFactoryBean();
fooFactoryBean.setContextId("foo"); fooFactoryBean.setContextId("foo");
@@ -108,6 +122,18 @@ public class FeignClientUsingPropertiesTests {
formFactoryBean = new FeignClientFactoryBean(); formFactoryBean = new FeignClientFactoryBean();
formFactoryBean.setContextId("form"); formFactoryBean.setContextId("form");
formFactoryBean.setType(FeignClientFactoryBean.class); formFactoryBean.setType(FeignClientFactoryBean.class);
this.defaultHeadersAndQuerySingleParamsFeignClientFactoryBean = new FeignClientFactoryBean();
this.defaultHeadersAndQuerySingleParamsFeignClientFactoryBean
.setContextId("singleValue");
this.defaultHeadersAndQuerySingleParamsFeignClientFactoryBean
.setType(FeignClientFactoryBean.class);
this.defaultHeadersAndQueryMultipleParamsFeignClientFactoryBean = new FeignClientFactoryBean();
this.defaultHeadersAndQueryMultipleParamsFeignClientFactoryBean
.setContextId("multipleValue");
this.defaultHeadersAndQueryMultipleParamsFeignClientFactoryBean
.setType(FeignClientFactoryBean.class);
} }
public FooClient fooClient() { public FooClient fooClient() {
@@ -159,6 +185,35 @@ public class FeignClientUsingPropertiesTests {
assertThat(response).isEqualTo("Data"); assertThat(response).isEqualTo("Data");
} }
@Test
public void testSingleValue() {
List<String> response = singleValueClient().singleValue();
assertThat(response).isEqualTo(Arrays.asList("header", "parameter"));
}
@Test
public void testMultipleValue() {
List<String> response = multipleValueClient().multipleValue();
assertThat(response).isEqualTo(
Arrays.asList("header1", "header2", "parameter1", "parameter2"));
}
public SingleValueClient singleValueClient() {
this.defaultHeadersAndQuerySingleParamsFeignClientFactoryBean
.setApplicationContext(this.applicationContext);
return this.defaultHeadersAndQuerySingleParamsFeignClientFactoryBean
.feign(this.context)
.target(SingleValueClient.class, "http://localhost:" + this.port);
}
public MultipleValueClient multipleValueClient() {
this.defaultHeadersAndQueryMultipleParamsFeignClientFactoryBean
.setApplicationContext(this.applicationContext);
return this.defaultHeadersAndQueryMultipleParamsFeignClientFactoryBean
.feign(this.context)
.target(MultipleValueClient.class, "http://localhost:" + this.port);
}
@Test @Test
public void readTimeoutShouldWorkWhenConnectTimeoutNotSet() { public void readTimeoutShouldWorkWhenConnectTimeoutNotSet() {
FeignClientFactoryBean readTimeoutFactoryBean = new FeignClientFactoryBean(); FeignClientFactoryBean readTimeoutFactoryBean = new FeignClientFactoryBean();
@@ -191,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
@@ -202,21 +272,21 @@ public class FeignClientUsingPropertiesTests {
protected interface FooClient { protected interface FooClient {
@RequestMapping(method = RequestMethod.GET, value = "/foo") @GetMapping(path = "/foo")
String foo(); String foo();
} }
protected interface BarClient { protected interface BarClient {
@RequestMapping(method = RequestMethod.GET, value = "/bar") @GetMapping(path = "/bar")
String bar(); String bar();
} }
protected interface UnwrapClient { protected interface UnwrapClient {
@RequestMapping(method = RequestMethod.GET, value = "/bar") // intentionally /bar @GetMapping(path = "/bar") // intentionally /bar
String unwrap() throws IOException; String unwrap() throws IOException;
} }
@@ -229,6 +299,20 @@ public class FeignClientUsingPropertiesTests {
} }
protected interface SingleValueClient {
@GetMapping(path = "/singleValue")
List<String> singleValue();
}
protected interface MultipleValueClient {
@GetMapping(path = "/multipleValue")
List<String> multipleValue();
}
protected interface TimeoutClient { protected interface TimeoutClient {
@GetMapping("/timeouts") @GetMapping("/timeouts")
@@ -253,18 +337,33 @@ public class FeignClientUsingPropertiesTests {
} }
} }
@RequestMapping(method = RequestMethod.GET, value = "/bar") @GetMapping(path = "/bar")
public String bar() throws InterruptedException { public String bar() throws InterruptedException {
Thread.sleep(2000L); TimeUnit.SECONDS.sleep(2);
return "OK"; return "OK";
} }
@RequestMapping(value = "/form", method = RequestMethod.POST, @PostMapping(path = "/form",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String form(HttpServletRequest request) { public String form(HttpServletRequest request) {
return request.getParameter("form"); return request.getParameter("form");
} }
@GetMapping(path = "/singleValue")
public List<String> singleValue(@RequestHeader List<String> singleValueHeaders,
@RequestParam List<String> singleValueParameters) {
return Stream.of(singleValueHeaders, singleValueParameters)
.flatMap(Collection::stream).collect(Collectors.toList());
}
@GetMapping(path = "/multipleValue")
public List<String> multipleValue(
@RequestHeader List<String> multipleValueHeaders,
@RequestParam List<String> multipleValueParameters) {
return Stream.of(multipleValueHeaders, multipleValueParameters)
.flatMap(Collection::stream).collect(Collectors.toList());
}
} }
public static class FooRequestInterceptor implements RequestInterceptor { public static class FooRequestInterceptor implements RequestInterceptor {
@@ -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.
@@ -20,7 +20,9 @@ import java.util.Collections;
import org.junit.Test; import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.openfeign.test.TestAutoConfiguration;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.env.MockEnvironment;
@@ -28,10 +30,12 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
* @author Gang Li * @author Gang Li
* @author Michal Domagala
*/ */
public class FeignClientsRegistrarTests { public class FeignClientsRegistrarTests {
@@ -76,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)
@@ -89,6 +93,17 @@ public class FeignClientsRegistrarTests {
new AnnotationConfigApplicationContext(FallbackFactoryTestConfig.class); new AnnotationConfigApplicationContext(FallbackFactoryTestConfig.class);
} }
@Test
public void shouldPassSubLevelFeignClient() {
AnnotationConfigApplicationContext config = new AnnotationConfigApplicationContext();
((DefaultListableBeanFactory) config.getBeanFactory())
.setAllowBeanDefinitionOverriding(false);
config.register(TopLevelSubLevelTestConfig.class);
assertThatCode(() -> config.refresh()).as(
"Case https://github.com/spring-cloud/spring-cloud-openfeign/issues/331 should be solved")
.doesNotThrowAnyException();
}
@FeignClient(name = "fallbackTestClient", url = "http://localhost:8080/", @FeignClient(name = "fallbackTestClient", url = "http://localhost:8080/",
fallback = FallbackClient.class) fallback = FallbackClient.class)
protected interface FallbackClient { protected interface FallbackClient {
@@ -122,4 +137,12 @@ public class FeignClientsRegistrarTests {
} }
@EnableFeignClients(clients = {
org.springframework.cloud.openfeign.feignclientsregistrar.TopLevelClient.class,
org.springframework.cloud.openfeign.feignclientsregistrar.sub.SubLevelClient.class })
@EnableAutoConfiguration(exclude = TestAutoConfiguration.class)
protected static class TopLevelSubLevelTestConfig {
}
} }
@@ -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(),
@@ -0,0 +1,28 @@
/*
* 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.feignclientsregistrar;
import org.springframework.cloud.openfeign.FeignClient;
/**
* @author Michal Domagala
*/
@FeignClient("top-level")
public interface TopLevelClient {
}
@@ -0,0 +1,28 @@
/*
* 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.feignclientsregistrar.sub;
import org.springframework.cloud.openfeign.FeignClient;
/**
* @author Michal Domagala
*/
@FeignClient("sub-level")
public interface SubLevelClient {
}
@@ -16,7 +16,7 @@
package org.springframework.cloud.openfeign.hateoas; package org.springframework.cloud.openfeign.hateoas;
import java.util.Arrays; import java.util.Collections;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test; import org.junit.Test;
@@ -26,9 +26,11 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.hateoas.mediatype.MessageResolver; import org.springframework.hateoas.mediatype.MessageResolver;
import org.springframework.hateoas.mediatype.hal.CurieProvider; import org.springframework.hateoas.mediatype.hal.CurieProvider;
import org.springframework.hateoas.mediatype.hal.HalConfiguration; import org.springframework.hateoas.mediatype.hal.HalConfiguration;
import org.springframework.hateoas.mediatype.hal.HalMediaTypeConfiguration;
import org.springframework.hateoas.mediatype.hal.Jackson2HalModule; import org.springframework.hateoas.mediatype.hal.Jackson2HalModule;
import org.springframework.hateoas.server.LinkRelationProvider; import org.springframework.hateoas.server.LinkRelationProvider;
import org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter; import org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter;
@@ -45,20 +47,20 @@ import static org.springframework.hateoas.MediaTypes.HAL_JSON;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class FeignHalAutoConfigurationTests { public class FeignHalAutoConfigurationTests {
@Mock
private ObjectProvider<ObjectMapper> objectMapper;
@Mock @Mock
private ObjectProvider<HalConfiguration> halConfiguration; private ObjectProvider<HalConfiguration> halConfiguration;
@Mock @Mock
private ObjectProvider<LinkRelationProvider> relProvider; private ObjectProvider<ObjectMapper> objectMapper;
@Mock
private LinkRelationProvider relProvider;
@Mock @Mock
private ObjectProvider<CurieProvider> curieProvider; private ObjectProvider<CurieProvider> curieProvider;
@Mock @Mock
private ObjectProvider<MessageResolver> messageResolver; private MessageResolver messageResolver;
@InjectMocks @InjectMocks
private FeignHalAutoConfiguration feignHalAutoConfiguration; private FeignHalAutoConfiguration feignHalAutoConfiguration;
@@ -70,17 +72,19 @@ public class FeignHalAutoConfigurationTests {
when(halConfiguration.getIfAvailable(any())) when(halConfiguration.getIfAvailable(any()))
.thenReturn(mock(HalConfiguration.class)); .thenReturn(mock(HalConfiguration.class));
when(relProvider.getIfAvailable()).thenReturn(mock(LinkRelationProvider.class));
when(curieProvider.getIfAvailable(any())).thenReturn(mock(CurieProvider.class)); when(curieProvider.getIfAvailable(any())).thenReturn(mock(CurieProvider.class));
when(messageResolver.getIfAvailable()).thenReturn(mock(MessageResolver.class));
HalMediaTypeConfiguration halMediaTypeConfiguration = new HalMediaTypeConfiguration(
relProvider, curieProvider, halConfiguration, messageResolver,
new DefaultListableBeanFactory());
TypeConstrainedMappingJackson2HttpMessageConverter converter = feignHalAutoConfiguration TypeConstrainedMappingJackson2HttpMessageConverter converter = feignHalAutoConfiguration
.halJacksonHttpMessageConverter(objectMapper, halConfiguration, .halJacksonHttpMessageConverter(objectMapper, halMediaTypeConfiguration);
messageResolver, curieProvider, relProvider);
assertThat(converter).isNotNull(); assertThat(converter).isNotNull();
assertThat(converter.getObjectMapper()).isNotNull(); assertThat(converter.getObjectMapper()).isNotNull();
assertThat(converter.getSupportedMediaTypes()).isEqualTo(Arrays.asList(HAL_JSON)); assertThat(converter.getSupportedMediaTypes())
.isEqualTo(Collections.singletonList(HAL_JSON));
assertThat(Jackson2HalModule.isAlreadyRegisteredIn(converter.getObjectMapper())) assertThat(Jackson2HalModule.isAlreadyRegisteredIn(converter.getObjectMapper()))
.isTrue(); .isTrue();
@@ -54,7 +54,7 @@ import static org.mockito.Mockito.when;
* {@link FeignBlockingLoadBalancerClient} and its delegates. * {@link FeignBlockingLoadBalancerClient} and its delegates.
* *
* @see <a href= * @see <a href=
* "https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/blocking/client/BlockingLoadBalancerClientTests.java">BlockingLoadBalancerClientTests</a> * "https://github.com/spring-cloud/spring-cloud-commons/blob/main/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/blocking/client/BlockingLoadBalancerClientTests.java">BlockingLoadBalancerClientTests</a>
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
@@ -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 {
@@ -45,7 +47,8 @@ class FeignLoadBalancerAutoConfigurationTests {
void shouldInstantiateDefaultFeignBlockingLoadBalancerClientWhenHttpClientDisabled() { void shouldInstantiateDefaultFeignBlockingLoadBalancerClientWhenHttpClientDisabled() {
ConfigurableApplicationContext context = initContext( ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false", "spring.cloud.loadbalancer.ribbon.enabled=false",
"feign.httpclient.enabled=false"); "feign.httpclient.enabled=false",
"spring.cloud.loadbalancer.retry.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class); assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalanced(context, Client.Default.class); assertLoadBalanced(context, Client.Default.class);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class); assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
@@ -54,7 +57,8 @@ class FeignLoadBalancerAutoConfigurationTests {
@Test @Test
void shouldInstantiateHttpFeignClientWhenEnabled() { void shouldInstantiateHttpFeignClientWhenEnabled() {
ConfigurableApplicationContext context = initContext( ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false"); "spring.cloud.loadbalancer.ribbon.enabled=false",
"spring.cloud.loadbalancer.retry.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class); assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalanced(context, ApacheHttpClient.class); assertLoadBalanced(context, ApacheHttpClient.class);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class); assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
@@ -64,16 +68,93 @@ class FeignLoadBalancerAutoConfigurationTests {
void shouldInstantiateOkHttpFeignClientWhenEnabled() { void shouldInstantiateOkHttpFeignClientWhenEnabled() {
ConfigurableApplicationContext context = initContext( ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false", "spring.cloud.loadbalancer.ribbon.enabled=false",
"feign.httpclient.enabled=false", "feign.okhttp.enabled=true"); "feign.httpclient.enabled=false", "feign.okhttp.enabled=true",
"spring.cloud.loadbalancer.retry.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class); assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalanced(context, OkHttpClient.class); assertLoadBalanced(context, OkHttpClient.class);
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
void shouldInstantiateRetryableDefaultFeignBlockingLoadBalancerClientWhenHttpClientDisabled() {
ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false",
"feign.httpclient.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalancedWithRetries(context, Client.Default.class);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
}
@Test
void shouldInstantiateRetryableHttpFeignClientWhenEnabled() {
ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalancedWithRetries(context, ApacheHttpClient.class);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
}
@Test
void shouldInstantiateRetryableOkHttpFeignClientWhenEnabled() {
ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false",
"feign.httpclient.enabled=false", "feign.okhttp.enabled=true");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalancedWithRetries(context, OkHttpClient.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(
"spring.cloud.loadbalancer.ribbon.enabled=true"); "spring.cloud.loadbalancer.ribbon.enabled=true",
"spring.cloud.loadbalancer.retry.enabled=false");
assertThatOneBeanPresent(context, LoadBalancerFeignClient.class); assertThatOneBeanPresent(context, LoadBalancerFeignClient.class);
assertThatBeanNotPresent(context, BlockingLoadBalancerClient.class); assertThatBeanNotPresent(context, BlockingLoadBalancerClient.class);
assertThatBeanNotPresent(context, FeignBlockingLoadBalancerClient.class); assertThatBeanNotPresent(context, FeignBlockingLoadBalancerClient.class);
@@ -104,6 +185,18 @@ class FeignLoadBalancerAutoConfigurationTests {
assertThat(beans.get("feignClient").getDelegate()).isInstanceOf(delegateClass); assertThat(beans.get("feignClient").getDelegate()).isInstanceOf(delegateClass);
} }
private void assertLoadBalancedWithRetries(ConfigurableApplicationContext context,
Class delegateClass) {
Map<String, RetryableFeignBlockingLoadBalancerClient> retryableBeans = context
.getBeansOfType(RetryableFeignBlockingLoadBalancerClient.class);
assertThat(retryableBeans).hasSize(1);
Map<String, FeignBlockingLoadBalancerClient> beans = context
.getBeansOfType(FeignBlockingLoadBalancerClient.class);
assertThat(beans).isEmpty();
assertThat(retryableBeans.get("feignRetryClient").getDelegate())
.isInstanceOf(delegateClass);
}
private void assertThatBeanNotPresent(ConfigurableApplicationContext context, private void assertThatBeanNotPresent(ConfigurableApplicationContext context,
Class<?> beanClass) { Class<?> beanClass) {
Map<String, ?> beans = context.getBeansOfType(beanClass); Map<String, ?> beans = context.getBeansOfType(beanClass);
@@ -0,0 +1,231 @@
/*
* 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.loadbalancer;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import feign.Client;
import feign.Request;
import feign.Response;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerRetryProperties;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.cloud.loadbalancer.blocking.retry.BlockingLoadBalancedRetryPolicy;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link RetryableFeignBlockingLoadBalancerClient}. Note: the underlying
* {@link BlockingLoadBalancerClient} is already extensively tested in the Spring Cloud
* Commons project, so here we are only testing the interactions between
* {@link RetryableFeignBlockingLoadBalancerClient} and its delegates.
*
* @see <a href=
* "https://github.com/spring-cloud/spring-cloud-commons/blob/main/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/blocking/client/BlockingLoadBalancerClientTests.java">BlockingLoadBalancerClientTests</a>
* @author Olga Maciaszek-Sharma
*/
@ExtendWith(MockitoExtension.class)
class RetryableFeignBlockingLoadBalancerClientTests {
private Client delegate = mock(Client.class);
private LoadBalancedRetryFactory retryFactory = mock(LoadBalancedRetryFactory.class);
private BlockingLoadBalancerClient loadBalancerClient = mock(
BlockingLoadBalancerClient.class);
private LoadBalancerRetryProperties properties = new LoadBalancerRetryProperties();
private RetryableFeignBlockingLoadBalancerClient feignBlockingLoadBalancerClient = new RetryableFeignBlockingLoadBalancerClient(
delegate, loadBalancerClient, retryFactory);
private ServiceInstance serviceInstance = new DefaultServiceInstance("test-a", "test",
"testhost", 80, false);
@BeforeEach
void setUp() {
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
.thenReturn(new BlockingLoadBalancedRetryPolicy("test",
loadBalancerClient, properties));
when(loadBalancerClient.choose("test")).thenReturn(serviceInstance);
}
@Test
void shouldExtractServiceIdFromRequestUrl() throws IOException {
Request request = testRequest();
Response response = testResponse(200);
when(delegate.execute(any(), any())).thenReturn(response);
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
.thenReturn(new BlockingLoadBalancedRetryPolicy("test",
loadBalancerClient, properties));
when(loadBalancerClient.reconstructURI(serviceInstance,
URI.create("http://test/path")))
.thenReturn(URI.create("http://testhost:80/path"));
feignBlockingLoadBalancerClient.execute(request, new Request.Options());
verify(loadBalancerClient).choose("test");
verify(loadBalancerClient).reconstructURI(serviceInstance,
URI.create("http://test/path"));
verify(delegate).execute(argThat((Request actualRequest) -> actualRequest.url()
.equals("http://testhost:80/path")), any());
}
private Response testResponse(int status) {
return Response.builder().request(testRequest()).status(status).build();
}
private Response testResponse(int status, String body) {
// ByteArrayInputStream ignores close() and must be wrapped
InputStream reallyCloseable = new BufferedInputStream(
new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
return Response.builder().request(testRequest()).status(status)
.body(reallyCloseable, null).build();
}
@Test
void shouldExecuteOriginalRequestIfInstanceNotFound() throws IOException {
Request request = testRequest();
Response response = testResponse(503);
when(loadBalancerClient.choose("test")).thenReturn(null);
when(delegate.execute(any(), any())).thenReturn(response);
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
.thenReturn(new BlockingLoadBalancedRetryPolicy("test",
loadBalancerClient, properties));
feignBlockingLoadBalancerClient.execute(request, new Request.Options());
verify(delegate).execute(eq(request), any());
}
@Test
void shouldRetryOnRepeatableStatusCode() throws IOException {
properties.getRetryableStatusCodes().add(503);
Request request = testRequest();
Response response = testResponse(503);
when(delegate.execute(any(), any())).thenReturn(response);
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
.thenReturn(new BlockingLoadBalancedRetryPolicy("test",
loadBalancerClient, properties));
when(loadBalancerClient.reconstructURI(serviceInstance,
URI.create("http://test/path")))
.thenReturn(URI.create("http://testhost:80/path"));
feignBlockingLoadBalancerClient.execute(request, new Request.Options());
verify(loadBalancerClient, times(2)).reconstructURI(serviceInstance,
URI.create("http://test/path"));
verify(delegate, times(2)).execute(any(), any());
}
@Test
void shouldExposeResponseBodyOnRetry() throws IOException {
properties.getRetryableStatusCodes().add(503);
Request request = testRequest();
when(delegate.execute(any(), any())).thenReturn(testResponse(503, "foo"),
testResponse(503, "foo"));
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
.thenReturn(new BlockingLoadBalancedRetryPolicy("test",
loadBalancerClient, properties));
when(loadBalancerClient.reconstructURI(serviceInstance,
URI.create("http://test/path")))
.thenReturn(URI.create("http://testhost:80/path"));
Response response = feignBlockingLoadBalancerClient.execute(request,
new Request.Options());
String bodyContent = IOUtils
.toString(response.body().asReader(StandardCharsets.UTF_8));
assertThat(bodyContent).isEqualTo("foo");
}
@Test
void shouldPassCorrectRequestToDelegate() throws IOException {
Request request = testRequest();
Request.Options options = new Request.Options();
String url = "http://127.0.0.1/path";
ServiceInstance serviceInstance = new DefaultServiceInstance("test-1", "test",
"test-host", 8888, false);
when(loadBalancerClient.choose("test")).thenReturn(serviceInstance);
when(loadBalancerClient.reconstructURI(serviceInstance,
URI.create("http://test/path"))).thenReturn(URI.create(url));
Response response = testResponse(200);
when(delegate.execute(any(), any())).thenReturn(response);
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
.thenReturn(new BlockingLoadBalancedRetryPolicy("test",
loadBalancerClient, properties));
feignBlockingLoadBalancerClient.execute(request, options);
ArgumentCaptor<Request> captor = ArgumentCaptor.forClass(Request.class);
verify(delegate, times(1)).execute(captor.capture(), eq(options));
Request actualRequest = captor.getValue();
assertThat(actualRequest.httpMethod()).isEqualTo(Request.HttpMethod.GET);
assertThat(actualRequest.url()).isEqualTo(url);
assertThat(actualRequest.headers()).hasSize(1);
assertThat(actualRequest.headers()).containsEntry(HttpHeaders.CONTENT_TYPE,
Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
assertThat(new String(actualRequest.body())).isEqualTo("hello");
}
private Request testRequest() {
return testRequest("test");
}
private Request testRequest(String host) {
return Request.create(Request.HttpMethod.GET, "http://" + host + "/path",
testHeaders(), "hello".getBytes(), StandardCharsets.UTF_8, null);
}
private Map<String, Collection<String>> testHeaders() {
Map<String, Collection<String>> feignHeaders = new HashMap<>();
feignHeaders.put(HttpHeaders.CONTENT_TYPE,
Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
return feignHeaders;
}
}
@@ -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,
@@ -0,0 +1,116 @@
/*
* 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.support;
import java.nio.charset.Charset;
import feign.Response;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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.http.HttpHeaders;
import org.springframework.util.SocketUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Abstract class for the integration tests for {@link SpringMvcContract}.
*
* @author Ram Anaswara
*/
public class AbstractSpringMvcContractIntegrationTests {
@BeforeAll
public static void beforeClass() {
System.setProperty("server.port",
String.valueOf(SocketUtils.findAvailableTcpPort()));
}
@AfterAll
public static void afterClass() {
System.clearProperty("server.port");
}
protected String getUrlQueryParam(Response response) {
return response.request().requestTemplate().queries().get("url").stream()
.findFirst().orElseThrow(IllegalStateException::new);
}
@FeignClient(name = "test", url = "http://localhost:${server.port}/",
configuration = NoCodecsFeignConfiguration.class)
interface TestClient {
@PostMapping("/test")
Object sendMessage(@RequestBody String message,
@RequestHeader(HttpHeaders.CONTENT_TYPE) String acceptHeader);
@GetMapping("/get")
Object getMessage(@RequestParam String url);
}
@Configuration(proxyBeanMethods = false)
@EnableFeignClients(clients = TestClient.class)
@EnableAutoConfiguration
@RestController
@Import(NoSecurityConfiguration.class)
protected static class Config {
@PostMapping("/test")
Object sendMessage(@RequestBody String message,
@RequestHeader(HttpHeaders.CONTENT_TYPE) String acceptHeader) {
return message;
}
@GetMapping("/get")
Object getMessage(@RequestParam String url) {
return url;
}
}
// Avoid feign.codec.EncodeException - this feature works for users that override
// Encoder
protected static class NoCodecsFeignConfiguration {
@Bean
public Decoder decoder() {
return (response, type) -> response;
}
@Bean
public Encoder encoder() {
return (object, bodyType, request) -> request
.body(object.toString().getBytes(), Charset.defaultCharset());
}
}
}
@@ -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;
@@ -57,13 +60,16 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.http.HttpHeaders.ACCEPT; import static org.springframework.http.HttpHeaders.ACCEPT;
import static org.springframework.http.HttpHeaders.CONTENT_LENGTH; 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_FORM_URLENCODED_VALUE;
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
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Ahmad Mozafarnia * @author Ahmad Mozafarnia
* @author Can Bezmen
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringEncoderTests.Application.class, @SpringBootTest(classes = SpringEncoderTests.Application.class,
@@ -79,6 +85,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 +194,44 @@ public class SpringEncoderTests {
.as("Body content cannot be decoded").contains("hi"); .as("Body content cannot be decoded").contains("hi");
} }
@Test
public void testFromURLEncodedValue() {
Encoder encoder = context.getInstance("formUrlEncoded", Encoder.class);
assertThat(encoder).isNotNull();
RequestTemplate request = new RequestTemplate();
request.header(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE);
String body = "test";
encoder.encode(body, String.class, request);
assertThat(new String(request.requestBody().asBytes()))
.as("Body content cannot be decoded").contains(body);
}
@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 +260,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();
@@ -16,101 +16,41 @@
package org.springframework.cloud.openfeign.support; package org.springframework.cloud.openfeign.support;
import java.nio.charset.Charset; import feign.Response;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; 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;
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.http.HttpHeaders;
import org.springframework.util.SocketUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatCode;
/** /**
* Integration tests for {@link SpringMvcContract} * Integration tests for {@link SpringMvcContract}.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Ram Anaswara
*/ */
@SpringBootTest(classes = SpringMvcContractIntegrationTests.Config.class, @SpringBootTest(classes = AbstractSpringMvcContractIntegrationTests.Config.class,
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SpringMvcContractIntegrationTests { public class SpringMvcContractIntegrationTests
extends AbstractSpringMvcContractIntegrationTests {
@Autowired @Autowired
private TestClient client; private TestClient client;
@BeforeAll
public static void beforeClass() {
System.setProperty("server.port",
String.valueOf(SocketUtils.findAvailableTcpPort()));
}
@AfterAll
public static void afterClass() {
System.clearProperty("server.port");
}
@Test @Test
public void shouldNotThrowInvalidMediaTypeExceptionWhenContentTypeTemplateUsed() { public void shouldNotThrowInvalidMediaTypeExceptionWhenContentTypeTemplateUsed() {
assertThatCode(() -> client.sendMessage("test", "text/markdown")) assertThatCode(() -> client.sendMessage("test", "text/markdown"))
.doesNotThrowAnyException(); .doesNotThrowAnyException();
} }
@FeignClient(name = "test", url = "http://localhost:${server.port}/", @Test
configuration = NoCodecsFeignConfiguration.class) public void feignClientShouldPreserveSlash() {
interface TestClient { Response response = (Response) client.getMessage("https://www.google.com");
@PostMapping("/test")
Object sendMessage(@RequestBody String message,
@RequestHeader(HttpHeaders.CONTENT_TYPE) String acceptHeader);
}
@Configuration(proxyBeanMethods = false)
@EnableFeignClients(clients = TestClient.class)
@EnableAutoConfiguration
@RestController
@Import(NoSecurityConfiguration.class)
protected static class Config {
@PostMapping("/test")
Object sendMessage(@RequestBody String message,
@RequestHeader(HttpHeaders.CONTENT_TYPE) String acceptHeader) {
return message;
}
}
// avoid feign.codec.EncodeException - this feature works for users that override
// Encoder
protected static class NoCodecsFeignConfiguration {
@Bean
public Decoder decoder() {
return (response, type) -> response;
}
@Bean
public Encoder encoder() {
return (object, bodyType, request) -> request
.body(object.toString().getBytes(), Charset.defaultCharset());
}
String urlQueryParam = getUrlQueryParam(response);
assertThat(urlQueryParam).isEqualTo("https%3A//www.google.com");
} }
} }
@@ -0,0 +1,49 @@
/*
* 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.support;
import feign.Response;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link SpringMvcContract}.
*
* @author Ram Anaswara
*/
@SpringBootTest(classes = SpringMvcContractSlashEncodingIntegrationTests.Config.class,
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
properties = { "feign.client.decodeSlash=false" })
public class SpringMvcContractSlashEncodingIntegrationTests
extends AbstractSpringMvcContractIntegrationTests {
@Autowired
private TestClient client;
@Test
public void feignClientShouldNotDecodeEncodedSlash() {
Response response = (Response) client.getMessage("https://www.google.com");
String urlQueryParam = getUrlQueryParam(response);
assertThat(urlQueryParam).isEqualTo("https%3A%2F%2Fwww.google.com");
}
}
@@ -62,6 +62,7 @@ import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import static feign.CollectionFormat.SSV; import static feign.CollectionFormat.SSV;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeTrue;
/** /**
@@ -118,11 +119,7 @@ public class SpringMvcContractTests {
@Before @Before
public void setup() { public void setup() {
FormattingConversionServiceFactoryBean conversionServiceFactoryBean = new FormattingConversionServiceFactoryBean(); contract = new SpringMvcContract(Collections.emptyList(), getConversionService());
conversionServiceFactoryBean.afterPropertiesSet();
ConversionService conversionService = conversionServiceFactoryBean.getObject();
contract = new SpringMvcContract(Collections.emptyList(), conversionService);
} }
@Test @Test
@@ -136,6 +133,23 @@ public class SpringMvcContractTests {
assertThat(data.template().method()).isEqualTo("GET"); assertThat(data.template().method()).isEqualTo("GET");
assertThat(data.template().headers().get("Accept").iterator().next()) assertThat(data.template().headers().get("Accept").iterator().next())
.isEqualTo(MediaType.APPLICATION_JSON_VALUE); .isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(data.template().decodeSlash()).isTrue();
}
@Test
public void testProcessAnnotationOnMethod_Simple_SlashEncoded() throws Exception {
contract = new SpringMvcContract(Collections.emptyList(), getConversionService(),
false);
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest",
String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test/{id}");
assertThat(data.template().decodeSlash()).isFalse();
} }
@Test @Test
@@ -169,18 +183,12 @@ public class SpringMvcContractTests {
} }
@Test @Test
public void testProcessAnnotations_Class_AnnotationsGetSpecificTest() public void testProcessAnnotations_Class_Annotations_RequestMapping() {
throws Exception { assertThatIllegalArgumentException().isThrownBy(() -> {
Method method = TestTemplate_Class_Annotations.class Method method = TestTemplate_Class_RequestMapping.class
.getDeclaredMethod("getSpecificTest", String.class, String.class); .getDeclaredMethod("getSpecificTest", String.class, String.class);
MethodMetadata data = contract contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
.parseAndValidateMetadata(method.getDeclaringClass(), method); });
assertThat(data.template().url()).isEqualTo("/prepend/{classId}/test/{testId}");
assertThat(data.template().method()).isEqualTo("GET");
assertThat(data.indexToName().get(0).iterator().next()).isEqualTo("classId");
assertThat(data.indexToName().get(1).iterator().next()).isEqualTo("testId");
} }
@Test @Test
@@ -190,10 +198,12 @@ public class SpringMvcContractTests {
MethodMetadata data = contract MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method); .parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/prepend/{classId}"); assertThat(data.template().url()).isEqualTo("/");
assertThat(data.template().method()).isEqualTo("GET"); assertThat(data.template().method()).isEqualTo("GET");
assertThat(data.indexToName().get(0).iterator().next()).isEqualTo("classId"); assertThat(data.indexToName().get(0).iterator().next()).isEqualTo("classId");
assertThat(data.template().decodeSlash()).isTrue();
} }
@Test @Test
@@ -213,6 +223,9 @@ public class SpringMvcContractTests {
assertThat(data.indexToName().get(0).iterator().next()) assertThat(data.indexToName().get(0).iterator().next())
.isEqualTo(data.indexToName().get(0).iterator().next()); .isEqualTo(data.indexToName().get(0).iterator().next());
assertThat(data.indexToName().get(0).iterator().next())
.isEqualTo(data.indexToName().get(0).iterator().next());
assertThat(data.template().decodeSlash()).isTrue();
} }
@Test @Test
@@ -250,8 +263,7 @@ public class SpringMvcContractTests {
MethodMetadata data = contract MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method); .parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()) assertThat(data.template().url()).isEqualTo("/test/{id}?amount=" + "{amount}");
.isEqualTo("/advanced/test/{id}?amount=" + "{amount}");
assertThat(data.template().method()).isEqualTo("PUT"); assertThat(data.template().method()).isEqualTo("PUT");
assertThat(data.template().headers().get("Accept").iterator().next()) assertThat(data.template().headers().get("Accept").iterator().next())
.isEqualTo(MediaType.APPLICATION_JSON_VALUE); .isEqualTo(MediaType.APPLICATION_JSON_VALUE);
@@ -286,8 +298,7 @@ public class SpringMvcContractTests {
MethodMetadata data = contract MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method); .parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()) assertThat(data.template().url()).isEqualTo("/test/{id}?amount=" + "{amount}");
.isEqualTo("/advanced/test/{id}?amount=" + "{amount}");
assertThat(data.template().method()).isEqualTo("PUT"); assertThat(data.template().method()).isEqualTo("PUT");
assertThat(data.template().headers().get("Accept").iterator().next()) assertThat(data.template().headers().get("Accept").iterator().next())
.isEqualTo(MediaType.APPLICATION_JSON_VALUE); .isEqualTo(MediaType.APPLICATION_JSON_VALUE);
@@ -311,8 +322,7 @@ public class SpringMvcContractTests {
MethodMetadata data = contract MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method); .parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()) assertThat(data.template().url()).isEqualTo("/test2?amount=" + "{amount}");
.isEqualTo("/advanced/test2?amount=" + "{amount}");
assertThat(data.template().method()).isEqualTo("PUT"); assertThat(data.template().method()).isEqualTo("PUT");
assertThat(data.template().headers().get("Accept").iterator().next()) assertThat(data.template().headers().get("Accept").iterator().next())
.isEqualTo(MediaType.APPLICATION_JSON_VALUE); .isEqualTo(MediaType.APPLICATION_JSON_VALUE);
@@ -374,7 +384,7 @@ public class SpringMvcContractTests {
MethodMetadata data = contract MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method); .parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/advanced"); assertThat(data.template().url()).isEqualTo("/");
assertThat(data.template().method()).isEqualTo("GET"); assertThat(data.template().method()).isEqualTo("GET");
assertThat(data.template().headers().get("Accept").iterator().next()) assertThat(data.template().headers().get("Accept").iterator().next())
.isEqualTo(MediaType.APPLICATION_JSON_VALUE); .isEqualTo(MediaType.APPLICATION_JSON_VALUE);
@@ -390,6 +400,22 @@ public class SpringMvcContractTests {
assertThat(data.template().method()).isEqualTo("GET"); assertThat(data.template().method()).isEqualTo("GET");
assertThat(data.template().headers().get("Accept").iterator().next()) assertThat(data.template().headers().get("Accept").iterator().next())
.isEqualTo(MediaType.APPLICATION_JSON_VALUE); .isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(data.template().decodeSlash()).isTrue();
}
@Test
public void testProcessAnnotations_Advanced3_DecodeSlashFlagNotModified()
throws Exception {
contract = new SpringMvcContract(Collections.emptyList(), getConversionService(),
false);
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest");
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/");
assertThat(data.template().decodeSlash()).isTrue();
} }
@Test @Test
@@ -468,7 +494,7 @@ public class SpringMvcContractTests {
.parseAndValidateMetadata(method.getDeclaringClass(), method); .parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()) assertThat(data.template().url())
.isEqualTo("/advanced/testfallback/{id}?amount=" + "{amount}"); .isEqualTo("/testfallback/{id}?amount=" + "{amount}");
assertThat(data.template().method()).isEqualTo("PUT"); assertThat(data.template().method()).isEqualTo("PUT");
assertThat(data.template().headers().get("Accept").iterator().next()) assertThat(data.template().headers().get("Accept").iterator().next())
.isEqualTo(MediaType.APPLICATION_JSON_VALUE); .isEqualTo(MediaType.APPLICATION_JSON_VALUE);
@@ -608,6 +634,12 @@ public class SpringMvcContractTests {
assertThat(data.formParams()).contains("file", "id"); assertThat(data.formParams()).contains("file", "id");
} }
private ConversionService getConversionService() {
FormattingConversionServiceFactoryBean conversionServiceFactoryBean = new FormattingConversionServiceFactoryBean();
conversionServiceFactoryBean.afterPropertiesSet();
return conversionServiceFactoryBean.getObject();
}
public interface TestTemplate_Simple { public interface TestTemplate_Simple {
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET, @RequestMapping(value = "/test/{id}", method = RequestMethod.GET,
@@ -631,6 +663,14 @@ public class SpringMvcContractTests {
} }
@RequestMapping("/prepend/{classId}") @RequestMapping("/prepend/{classId}")
public interface TestTemplate_Class_RequestMapping {
@RequestMapping(value = "/test/{testId}", method = RequestMethod.GET)
TestObject getSpecificTest(@PathVariable("classId") String classId,
@PathVariable("testId") String testId);
}
public interface TestTemplate_Class_Annotations { public interface TestTemplate_Class_Annotations {
@RequestMapping(value = "/test/{testId}", method = RequestMethod.GET) @RequestMapping(value = "/test/{testId}", method = RequestMethod.GET)
@@ -735,7 +775,6 @@ public class SpringMvcContractTests {
} }
@JsonAutoDetect @JsonAutoDetect
@RequestMapping("/advanced")
public interface TestTemplate_Advanced { public interface TestTemplate_Advanced {
@CollectionFormat(SSV) @CollectionFormat(SSV)
@@ -17,7 +17,6 @@
package org.springframework.cloud.openfeign.valid; package org.springframework.cloud.openfeign.valid;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; import java.lang.reflect.Proxy;
import java.text.ParseException; import java.text.ParseException;
import java.time.LocalDate; import java.time.LocalDate;
@@ -49,7 +48,6 @@ import feign.Feign;
import feign.Logger; import feign.Logger;
import feign.RequestInterceptor; import feign.RequestInterceptor;
import feign.RequestTemplate; import feign.RequestTemplate;
import feign.Target;
import feign.codec.EncodeException; import feign.codec.EncodeException;
import feign.hystrix.FallbackFactory; import feign.hystrix.FallbackFactory;
import feign.hystrix.SetterFactory; import feign.hystrix.SetterFactory;
@@ -91,6 +89,7 @@ import org.springframework.http.ResponseEntity;
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;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
@@ -102,6 +101,7 @@ import org.springframework.web.multipart.MultipartFile;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
@@ -110,6 +110,7 @@ import static org.hamcrest.core.IsInstanceOf.instanceOf;
* @author Halvdan Hoem Grelland * @author Halvdan Hoem Grelland
* @author Aaron Whiteside * @author Aaron Whiteside
* @author Darren Foong * @author Darren Foong
* @author Can Bezmen
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = FeignClientTests.Application.class, @SpringBootTest(classes = FeignClientTests.Application.class,
@@ -178,23 +179,23 @@ public class FeignClientTests {
@Test @Test
public void testClient() { public void testClient() {
assertThat(this.testClient).as("testClient was null").isNotNull(); assertThat(testClient).as("testClient was null").isNotNull();
assertThat(Proxy.isProxyClass(this.testClient.getClass())) assertThat(Proxy.isProxyClass(testClient.getClass()))
.as("testClient is not a java Proxy").isTrue(); .as("testClient is not a java Proxy").isTrue();
InvocationHandler invocationHandler = Proxy.getInvocationHandler(this.testClient); InvocationHandler invocationHandler = Proxy.getInvocationHandler(testClient);
assertThat(invocationHandler).as("invocationHandler was null").isNotNull(); assertThat(invocationHandler).as("invocationHandler was null").isNotNull();
} }
@Test @Test
public void testRequestMappingClassLevelPropertyReplacement() { public void testRequestMappingClassLevelPropertyReplacement() {
Hello hello = this.testClient.getHelloUsingPropertyPlaceHolder(); Hello hello = testClient.getHelloUsingPropertyPlaceHolder();
assertThat(hello).as("hello was null").isNotNull(); assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello(OI_TERRA_2)); assertThat(hello).as("first hello didn't match").isEqualTo(new Hello(OI_TERRA_2));
} }
@Test @Test
public void testSimpleType() { public void testSimpleType() {
Hello hello = this.testClient.getHello(); Hello hello = testClient.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));
@@ -202,20 +203,20 @@ public class FeignClientTests {
@Test @Test
public void testOptional() { public void testOptional() {
Optional<Hello> hello = this.testClient.getOptionalHello(); Optional<Hello> hello = testClient.getOptionalHello();
assertThat(hello).isNotNull().isPresent().contains(new Hello(HELLO_WORLD_1)); assertThat(hello).isNotNull().isPresent().contains(new Hello(HELLO_WORLD_1));
} }
@Test @Test
public void testGenericType() { public void testGenericType() {
List<Hello> hellos = this.testClient.getHellos(); List<Hello> hellos = testClient.getHellos();
assertThat(hellos).as("hellos was null").isNotNull(); assertThat(hellos).as("hellos was null").isNotNull();
assertThat(getHelloList()).as("hellos didn't match").isEqualTo(hellos); assertThat(getHelloList()).as("hellos didn't match").isEqualTo(hellos);
} }
@Test @Test
public void testRequestInterceptors() { public void testRequestInterceptors() {
List<String> headers = this.testClient.getHelloHeaders(); List<String> headers = testClient.getHelloHeaders();
assertThat(headers).as("headers was null").isNotNull(); assertThat(headers).as("headers was null").isNotNull();
assertThat(headers.contains("myheader1value")) assertThat(headers.contains("myheader1value"))
.as("headers didn't contain myheader1value").isTrue(); .as("headers didn't contain myheader1value").isTrue();
@@ -225,24 +226,23 @@ public class FeignClientTests {
@Test @Test
public void testHeaderPlaceholders() { public void testHeaderPlaceholders() {
String header = this.testClient.getHelloHeadersPlaceholders(); String header = testClient.getHelloHeadersPlaceholders();
assertThat(header).as("header was null").isNotNull(); assertThat(header).as("header was null").isNotNull();
assertThat(header).as("header was wrong").isEqualTo("myPlaceholderHeaderValue"); assertThat(header).as("header was wrong").isEqualTo("myPlaceholderHeaderValue");
} }
@Test @Test
public void testFeignClientType() throws IllegalAccessException { public void testFeignClientType() {
assertThat(this.feignClient).isInstanceOf(LoadBalancerFeignClient.class); assertThat(feignClient).isInstanceOf(LoadBalancerFeignClient.class);
LoadBalancerFeignClient client = (LoadBalancerFeignClient) this.feignClient; LoadBalancerFeignClient client = (LoadBalancerFeignClient) feignClient;
Client delegate = client.getDelegate(); Client delegate = client.getDelegate();
assertThat(delegate).isInstanceOf(Client.Default.class); assertThat(delegate).isInstanceOf(Client.Default.class);
} }
@Test @Test
public void testServiceId() { public void testServiceId() {
assertThat(this.testClientServiceId).as("testClientServiceId was null") assertThat(testClientServiceId).as("testClientServiceId was null").isNotNull();
.isNotNull(); final Hello hello = testClientServiceId.getHello();
final Hello hello = this.testClientServiceId.getHello();
assertThat(hello).as("The hello response was null").isNotNull(); assertThat(hello).as("The hello response 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));
@@ -251,7 +251,7 @@ public class FeignClientTests {
@Test @Test
public void testParams() { public void testParams() {
List<String> list = Arrays.asList("a", "1", "test"); List<String> list = Arrays.asList("a", "1", "test");
List<String> params = this.testClient.getParams(list); List<String> params = testClient.getParams(list);
assertThat(params).as("params was null").isNotNull(); assertThat(params).as("params was null").isNotNull();
assertThat(params.size()).as("params size was wrong").isEqualTo(list.size()); assertThat(params.size()).as("params size was wrong").isEqualTo(list.size());
} }
@@ -260,14 +260,14 @@ public class FeignClientTests {
public void testFormattedParams() { public void testFormattedParams() {
List<LocalDate> list = Arrays.asList(LocalDate.of(2001, 1, 1), List<LocalDate> list = Arrays.asList(LocalDate.of(2001, 1, 1),
LocalDate.of(2018, 6, 10)); LocalDate.of(2018, 6, 10));
List<LocalDate> params = this.testClient.getFormattedParams(list); List<LocalDate> params = testClient.getFormattedParams(list);
assertThat(params).as("params was null").isNotNull(); assertThat(params).as("params was null").isNotNull();
assertThat(params).as("params not converted correctly").isEqualTo(list); assertThat(params).as("params not converted correctly").isEqualTo(list);
} }
@Test @Test
public void testHystrixCommand() throws NoSuchMethodException { public void testHystrixCommand() throws NoSuchMethodException {
HystrixCommand<List<Hello>> command = this.testClient.getHellosHystrix(); HystrixCommand<List<Hello>> command = testClient.getHellosHystrix();
assertThat(command).as("command was null").isNotNull(); assertThat(command).as("command was null").isNotNull();
assertThat(command.getCommandGroup().name()).as( assertThat(command.getCommandGroup().name()).as(
"Hystrix command group name should match the name of the feign client") "Hystrix command group name should match the name of the feign client")
@@ -284,7 +284,7 @@ public class FeignClientTests {
@Test @Test
public void testSingle() { public void testSingle() {
Single<Hello> single = this.testClient.getHelloSingle(); Single<Hello> single = testClient.getHelloSingle();
assertThat(single).as("single was null").isNotNull(); assertThat(single).as("single was null").isNotNull();
Hello hello = single.toBlocking().value(); Hello hello = single.toBlocking().value();
assertThat(hello).as("hello was null").isNotNull(); assertThat(hello).as("hello was null").isNotNull();
@@ -294,7 +294,7 @@ public class FeignClientTests {
@Test @Test
public void testNoContentResponse() { public void testNoContentResponse() {
ResponseEntity<Void> response = this.testClient.noContent(); ResponseEntity<Void> response = testClient.noContent();
assertThat(response).as("response was null").isNotNull(); assertThat(response).as("response was null").isNotNull();
assertThat(response.getStatusCode()).as("status code was wrong") assertThat(response.getStatusCode()).as("status code was wrong")
.isEqualTo(HttpStatus.NO_CONTENT); .isEqualTo(HttpStatus.NO_CONTENT);
@@ -302,7 +302,7 @@ public class FeignClientTests {
@Test @Test
public void testHeadResponse() { public void testHeadResponse() {
ResponseEntity<Void> response = this.testClient.head(); ResponseEntity<Void> response = testClient.head();
assertThat(response).as("response was null").isNotNull(); assertThat(response).as("response was null").isNotNull();
assertThat(response.getStatusCode()).as("status code was wrong") assertThat(response.getStatusCode()).as("status code was wrong")
.isEqualTo(HttpStatus.OK); .isEqualTo(HttpStatus.OK);
@@ -310,7 +310,7 @@ public class FeignClientTests {
@Test @Test
public void testHttpEntity() { public void testHttpEntity() {
HttpEntity<Hello> entity = this.testClient.getHelloEntity(); HttpEntity<Hello> entity = testClient.getHelloEntity();
assertThat(entity).as("entity was null").isNotNull(); assertThat(entity).as("entity was null").isNotNull();
Hello hello = entity.getBody(); Hello hello = entity.getBody();
assertThat(hello).as("hello was null").isNotNull(); assertThat(hello).as("hello was null").isNotNull();
@@ -320,7 +320,7 @@ public class FeignClientTests {
@Test @Test
public void testMoreComplexHeader() { public void testMoreComplexHeader() {
String response = this.testClient.moreComplexContentType("{\"value\":\"OK\"}"); String response = testClient.moreComplexContentType("{\"value\":\"OK\"}");
assertThat(response).as("response was null").isNotNull(); assertThat(response).as("response was null").isNotNull();
assertThat(response).as("didn't respond with {\"value\":\"OK\"}") assertThat(response).as("didn't respond with {\"value\":\"OK\"}")
.isEqualTo("{\"value\":\"OK\"}"); .isEqualTo("{\"value\":\"OK\"}");
@@ -328,7 +328,7 @@ public class FeignClientTests {
@Test @Test
public void testDecodeNotFound() { public void testDecodeNotFound() {
ResponseEntity<String> response = this.decodingTestClient.notFound(); ResponseEntity<String> response = decodingTestClient.notFound();
assertThat(response).as("response was null").isNotNull(); assertThat(response).as("response was null").isNotNull();
assertThat(response.getStatusCode()).as("status code was wrong") assertThat(response.getStatusCode()).as("status code was wrong")
.isEqualTo(HttpStatus.NOT_FOUND); .isEqualTo(HttpStatus.NOT_FOUND);
@@ -337,35 +337,35 @@ public class FeignClientTests {
@Test @Test
public void testOptionalNotFound() { public void testOptionalNotFound() {
Optional<String> s = this.decodingTestClient.optional(); Optional<String> s = decodingTestClient.optional();
assertThat(s).isNotPresent(); assertThat(s).isNotPresent();
} }
@Test @Test
public void testConvertingExpander() { public void testConvertingExpander() {
assertThat(this.testClient.getToString(Arg.A)).isEqualTo(Arg.A.toString()); assertThat(testClient.getToString(Arg.A)).isEqualTo(Arg.A.toString());
assertThat(this.testClient.getToString(Arg.B)).isEqualTo(Arg.B.toString()); assertThat(testClient.getToString(Arg.B)).isEqualTo(Arg.B.toString());
assertThat(this.testClient.getToString(new OtherArg("foo"))).isEqualTo("bar"); assertThat(testClient.getToString(new OtherArg("foo"))).isEqualTo("bar");
List<OtherArg> args = new ArrayList<>(); List<OtherArg> args = new ArrayList<>();
args.add(new OtherArg("foo")); args.add(new OtherArg("foo"));
args.add(new OtherArg("goo")); args.add(new OtherArg("goo"));
List<String> expectedResult = new ArrayList<>(); List<String> expectedResult = new ArrayList<>();
expectedResult.add("bar"); expectedResult.add("bar");
expectedResult.add("goo"); expectedResult.add("goo");
assertThat(this.testClient.getToString(args)).isEqualTo(expectedResult); assertThat(testClient.getToString(args)).isEqualTo(expectedResult);
} }
@Test @Test
public void testHystrixFallbackWorks() { public void testHystrixFallbackWorks() {
Hello hello = this.hystrixClient.fail(); Hello hello = hystrixClient.fail();
assertThat(hello).as("hello was null").isNotNull(); assertThat(hello).as("hello was null").isNotNull();
assertThat(hello.getMessage()).as("message was wrong").isEqualTo("fallback"); assertThat(hello.getMessage()).as("message was wrong").isEqualTo("fallback");
} }
@Test @Test
public void testHystrixFallbackSingle() { public void testHystrixFallbackSingle() {
Single<Hello> single = this.hystrixClient.failSingle(); Single<Hello> single = hystrixClient.failSingle();
assertThat(single).as("single was null").isNotNull(); assertThat(single).as("single was null").isNotNull();
Hello hello = single.toBlocking().value(); Hello hello = single.toBlocking().value();
assertThat(hello).as("hello was null").isNotNull(); assertThat(hello).as("hello was null").isNotNull();
@@ -375,7 +375,7 @@ public class FeignClientTests {
@Test @Test
public void testHystrixFallbackCommand() { public void testHystrixFallbackCommand() {
HystrixCommand<Hello> command = this.hystrixClient.failCommand(); HystrixCommand<Hello> command = hystrixClient.failCommand();
assertThat(command).as("command was null").isNotNull(); assertThat(command).as("command was null").isNotNull();
Hello hello = command.execute(); Hello hello = command.execute();
assertThat(hello).as("hello was null").isNotNull(); assertThat(hello).as("hello was null").isNotNull();
@@ -385,7 +385,7 @@ public class FeignClientTests {
@Test @Test
public void testHystrixFallbackObservable() { public void testHystrixFallbackObservable() {
Observable<Hello> observable = this.hystrixClient.failObservable(); Observable<Hello> observable = hystrixClient.failObservable();
assertThat(observable).as("observable was null").isNotNull(); assertThat(observable).as("observable was null").isNotNull();
Hello hello = observable.toBlocking().first(); Hello hello = observable.toBlocking().first();
assertThat(hello).as("hello was null").isNotNull(); assertThat(hello).as("hello was null").isNotNull();
@@ -395,7 +395,7 @@ public class FeignClientTests {
@Test @Test
public void testHystrixFallbackFuture() throws Exception { public void testHystrixFallbackFuture() throws Exception {
Future<Hello> future = this.hystrixClient.failFuture(); Future<Hello> future = hystrixClient.failFuture();
assertThat(future).as("future was null").isNotNull(); assertThat(future).as("future was null").isNotNull();
Hello hello = future.get(1, TimeUnit.SECONDS); Hello hello = future.get(1, TimeUnit.SECONDS);
assertThat(hello).as("hello was null").isNotNull(); assertThat(hello).as("hello was null").isNotNull();
@@ -405,7 +405,7 @@ public class FeignClientTests {
@Test @Test
public void testHystrixClientWithFallBackFactory() throws Exception { public void testHystrixClientWithFallBackFactory() throws Exception {
Hello hello = this.hystrixClientWithFallBackFactory.fail(); Hello hello = hystrixClientWithFallBackFactory.fail();
assertThat(hello).as("hello was null").isNotNull(); assertThat(hello).as("hello was null").isNotNull();
assertThat(hello.getMessage()).as("hello#message was null").isNotNull(); assertThat(hello.getMessage()).as("hello#message was null").isNotNull();
assertThat(hello.getMessage().contains("500")).as( assertThat(hello.getMessage().contains("500")).as(
@@ -415,22 +415,29 @@ public class FeignClientTests {
@Test(expected = HystrixRuntimeException.class) @Test(expected = HystrixRuntimeException.class)
public void testInvalidTypeHystrixFallbackFactory() throws Exception { public void testInvalidTypeHystrixFallbackFactory() throws Exception {
this.invalidTypeHystrixClientWithFallBackFactory.fail(); invalidTypeHystrixClientWithFallBackFactory.fail();
} }
@Test(expected = HystrixRuntimeException.class) @Test(expected = HystrixRuntimeException.class)
public void testNullHystrixFallbackFactory() throws Exception { public void testNullHystrixFallbackFactory() throws Exception {
this.nullHystrixClientWithFallBackFactory.fail(); nullHystrixClientWithFallBackFactory.fail();
}
@Test
public void testFormURLEncoded() {
Hello hello = new Hello(HELLO_WORLD_1);
Hello response = testClient.postFormUrlEncoded(hello);
assertThat(response).isEqualTo(hello);
} }
@Test @Test
public void namedFeignClientWorks() { public void namedFeignClientWorks() {
assertThat(this.namedHystrixClient).as("namedHystrixClient was null").isNotNull(); assertThat(namedHystrixClient).as("namedHystrixClient was null").isNotNull();
} }
@Test @Test
public void testHystrixSetterFactory() { public void testHystrixSetterFactory() {
HystrixCommand<List<Hello>> command = this.hystrixSetterFactoryClient HystrixCommand<List<Hello>> command = hystrixSetterFactoryClient
.getHellosHystrix(); .getHellosHystrix();
assertThat(command).as("command was null").isNotNull(); assertThat(command).as("command was null").isNotNull();
String setterPrefix = TestHystrixSetterFactoryClientConfig.SETTER_PREFIX; String setterPrefix = TestHystrixSetterFactoryClientConfig.SETTER_PREFIX;
@@ -449,13 +456,13 @@ public class FeignClientTests {
@Test @Test
public void testSingleRequestPart() { public void testSingleRequestPart() {
String response = this.multipartClient.singlePart("abc"); String response = multipartClient.singlePart("abc");
assertThat(response).isEqualTo("abc"); assertThat(response).isEqualTo("abc");
} }
@Test @Test
public void testSinglePojoRequestPart() { public void testSinglePojoRequestPart() {
String response = this.multipartClient.singlePojoPart(new Hello(HELLO_WORLD_1)); String response = multipartClient.singlePojoPart(new Hello(HELLO_WORLD_1));
assertThat(response).isEqualTo(HELLO_WORLD_1); assertThat(response).isEqualTo(HELLO_WORLD_1);
} }
@@ -463,7 +470,7 @@ public class FeignClientTests {
public void testMultipleRequestParts() { public void testMultipleRequestParts() {
MockMultipartFile file = new MockMultipartFile("file", "hello.bin", null, MockMultipartFile file = new MockMultipartFile("file", "hello.bin", null,
"hello".getBytes()); "hello".getBytes());
String response = this.multipartClient.multipart("abc", "123", file); String response = multipartClient.multipart("abc", "123", file);
assertThat(response).isEqualTo("abc123hello.bin"); assertThat(response).isEqualTo("abc123hello.bin");
} }
@@ -473,8 +480,7 @@ public class FeignClientTests {
Hello pojo2 = new Hello(OI_TERRA_2); Hello pojo2 = new Hello(OI_TERRA_2);
MockMultipartFile file = new MockMultipartFile("file", "hello.bin", null, MockMultipartFile file = new MockMultipartFile("file", "hello.bin", null,
"hello".getBytes()); "hello".getBytes());
String response = this.multipartClient.multipartPojo("abc", "123", pojo1, pojo2, String response = multipartClient.multipartPojo("abc", "123", pojo1, pojo2, file);
file);
assertThat(response).isEqualTo("abc123hello world 1oi terra 2hello.bin"); assertThat(response).isEqualTo("abc123hello world 1oi terra 2hello.bin");
} }
@@ -483,10 +489,10 @@ public class FeignClientTests {
List<MultipartFile> multipartFiles = Arrays.asList( List<MultipartFile> multipartFiles = Arrays.asList(
new MockMultipartFile("file1", "hello1.bin", null, "hello".getBytes()), new MockMultipartFile("file1", "hello1.bin", null, "hello".getBytes()),
new MockMultipartFile("file2", "hello2.bin", null, "hello".getBytes())); new MockMultipartFile("file2", "hello2.bin", null, "hello".getBytes()));
String partNames = this.multipartClient String partNames = multipartClient
.requestPartListOfMultipartFilesReturnsPartNames(multipartFiles); .requestPartListOfMultipartFilesReturnsPartNames(multipartFiles);
assertThat(partNames).isEqualTo("files,files"); assertThat(partNames).isEqualTo("files,files");
String fileNames = this.multipartClient String fileNames = multipartClient
.requestPartListOfMultipartFilesReturnsFileNames(multipartFiles); .requestPartListOfMultipartFilesReturnsFileNames(multipartFiles);
assertThat(fileNames).contains("hello1.bin", "hello2.bin"); assertThat(fileNames).contains("hello1.bin", "hello2.bin");
} }
@@ -499,9 +505,8 @@ public class FeignClientTests {
"hello".getBytes()); "hello".getBytes());
MockMultipartFile file2 = new MockMultipartFile("file2", "hello2.bin", null, MockMultipartFile file2 = new MockMultipartFile("file2", "hello2.bin", null,
"hello".getBytes()); "hello".getBytes());
String response = this.multipartClient String response = multipartClient.requestPartListOfPojosAndListOfMultipartFiles(
.requestPartListOfPojosAndListOfMultipartFiles( Arrays.asList(pojo1, pojo2), Arrays.asList(file1, file2));
Arrays.asList(pojo1, pojo2), Arrays.asList(file1, file2));
assertThat(response).isEqualTo("hello world 1oi terra 2hello1.binhello2.bin"); assertThat(response).isEqualTo("hello world 1oi terra 2hello1.binhello2.bin");
} }
@@ -510,7 +515,7 @@ public class FeignClientTests {
String partName = UUID.randomUUID().toString(); String partName = UUID.randomUUID().toString();
MockMultipartFile file1 = new MockMultipartFile(partName, "hello1.bin", null, MockMultipartFile file1 = new MockMultipartFile(partName, "hello1.bin", null,
"hello".getBytes()); "hello".getBytes());
String response = this.multipartClient.requestBodySingleMultipartFile(file1); String response = multipartClient.requestBodySingleMultipartFile(file1);
assertThat(response).isEqualTo(partName); assertThat(response).isEqualTo(partName);
} }
@@ -520,7 +525,7 @@ public class FeignClientTests {
"hello".getBytes()); "hello".getBytes());
MockMultipartFile file2 = new MockMultipartFile("file2", "hello2.bin", null, MockMultipartFile file2 = new MockMultipartFile("file2", "hello2.bin", null,
"hello".getBytes()); "hello".getBytes());
String response = this.multipartClient String response = multipartClient
.requestBodyListOfMultipartFiles(Arrays.asList(file1, file2)); .requestBodyListOfMultipartFiles(Arrays.asList(file1, file2));
assertThat(response).contains("file1", "file2"); assertThat(response).contains("file1", "file2");
} }
@@ -535,7 +540,7 @@ public class FeignClientTests {
form.put("file1", file1); form.put("file1", file1);
form.put("file2", file2); form.put("file2", file2);
form.put("hello", "world"); form.put("hello", "world");
String response = this.multipartClient.requestBodyMap(form); String response = multipartClient.requestBodyMap(form);
assertThat(response).contains("file1", "file2", "hello"); assertThat(response).contains("file1", "file2", "hello");
} }
@@ -544,7 +549,7 @@ public class FeignClientTests {
MockMultipartFile file = new MockMultipartFile("file1", "hello1.bin", null, MockMultipartFile file = new MockMultipartFile("file1", "hello1.bin", null,
"hello".getBytes()); "hello".getBytes());
expected.expectCause(instanceOf(EncodeException.class)); expected.expectCause(instanceOf(EncodeException.class));
this.multipartClient.invalid(file); multipartClient.invalid(file);
} }
protected enum Arg { protected enum Arg {
@@ -615,6 +620,10 @@ public class FeignClientTests {
@RequestMapping(method = RequestMethod.GET, path = "/tostring") @RequestMapping(method = RequestMethod.GET, path = "/tostring")
String getToString(@RequestParam("arg") Arg arg); String getToString(@RequestParam("arg") Arg arg);
@PostMapping(path = "/form-urlencoded",
consumes = APPLICATION_FORM_URLENCODED_VALUE)
Hello postFormUrlEncoded(Hello hello);
@RequestMapping(method = RequestMethod.GET, path = "/tostring2") @RequestMapping(method = RequestMethod.GET, path = "/tostring2")
String getToString(@RequestParam("arg") OtherArg arg); String getToString(@RequestParam("arg") OtherArg arg);
@@ -776,7 +785,7 @@ public class FeignClientTests {
@Override @Override
public String toString() { public String toString() {
return this.value; return value;
} }
} }
@@ -810,13 +819,9 @@ public class FeignClientTests {
@Override @Override
public HystrixClientWithFallBackFactory create(final Throwable cause) { public HystrixClientWithFallBackFactory create(final Throwable cause) {
return new HystrixClientWithFallBackFactory() { return () -> {
@Override assertThat(cause).isNotNull().as("Cause was null");
public Hello fail() { return new Hello("Hello from the fallback side: " + cause.getMessage());
assertThat(cause).isNotNull().as("Cause was null");
return new Hello(
"Hello from the fallback side: " + cause.getMessage());
}
}; };
} }
@@ -876,18 +881,15 @@ public class FeignClientTests {
@Bean @Bean
public SetterFactory commandKeyIsRequestLineSetterFactory() { public SetterFactory commandKeyIsRequestLineSetterFactory() {
return new SetterFactory() { return (target, method) -> {
@Override String groupKey = SETTER_PREFIX + target.name();
public HystrixCommand.Setter create(Target<?> target, Method method) { RequestMapping requestMapping = method
String groupKey = SETTER_PREFIX + target.name(); .getAnnotation(RequestMapping.class);
RequestMapping requestMapping = method String commandKey = SETTER_PREFIX + requestMapping.method()[0] + " "
.getAnnotation(RequestMapping.class); + requestMapping.path()[0];
String commandKey = SETTER_PREFIX + requestMapping.method()[0] + " " return HystrixCommand.Setter
+ requestMapping.path()[0]; .withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
return HystrixCommand.Setter .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey));
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
.andCommandKey(HystrixCommandKey.Factory.asKey(commandKey));
}
}; };
} }
@@ -1154,6 +1156,12 @@ public class FeignClientTests {
return result.toString(); return result.toString();
} }
@PostMapping(path = "/form-urlencoded",
consumes = APPLICATION_FORM_URLENCODED_VALUE)
Hello postFormUrlEncoded(Hello hello) {
return hello;
}
} }
public static class Hello { public static class Hello {
@@ -1168,7 +1176,7 @@ public class FeignClientTests {
} }
public String getMessage() { public String getMessage() {
return this.message; return message;
} }
public void setMessage(String message) { public void setMessage(String message) {
@@ -1184,12 +1192,12 @@ public class FeignClientTests {
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);
} }
} }
@@ -1213,7 +1221,7 @@ public class FeignClientTests {
@Bean @Bean
public ServerList<Server> ribbonServerList() { public ServerList<Server> ribbonServerList() {
return new StaticServerList<>(new Server("localhost", this.port)); return new StaticServerList<>(new Server("localhost", port));
} }
} }
@@ -10,6 +10,10 @@ feign.client.config.default.retryer=org.springframework.cloud.openfeign.FeignCli
feign.client.config.default.decode404=true feign.client.config.default.decode404=true
feign.client.config.foo.requestInterceptors[0]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.FooRequestInterceptor feign.client.config.foo.requestInterceptors[0]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.FooRequestInterceptor
feign.client.config.foo.requestInterceptors[1]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.BarRequestInterceptor feign.client.config.foo.requestInterceptors[1]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.BarRequestInterceptor
feign.client.config.singleValue.defaultRequestHeaders[singleValueHeaders]=header
feign.client.config.singleValue.defaultQueryParameters[singleValueParameters]=parameter
feign.client.config.multipleValue.defaultRequestHeaders[multipleValueHeaders]=header1,header2
feign.client.config.multipleValue.defaultQueryParameters[multipleValueParameters]=parameter1,parameter2
feign.client.config.bar.connectTimeout=1000 feign.client.config.bar.connectTimeout=1000
feign.client.config.bar.readTimeout=1000 feign.client.config.bar.readTimeout=1000
feign.client.config.form.encoder=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.FormEncoder feign.client.config.form.encoder=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.FormEncoder
@@ -18,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

Some files were not shown because too many files have changed in this diff Show More