Compare commits

...
421 Commits
Author SHA1 Message Date
buildmaster 245b106a76 Bumping versions 2022-09-11 23:33:49 +00:00
Olga Maciaszek-Sharma 666a59df6b Adjust to changes in commons. 2022-09-05 16:50:00 +02:00
Olga Maciaszek-Sharma 5a21e22002 Merge remote-tracking branch 'origin/3.1.x' 2022-09-05 16:43:41 +02:00
Olga Maciaszek-Sharma bdcbaa7f3b Allow overriding binary content types. Fixes gh-734. 2022-09-05 16:37:12 +02:00
buildmaster 375241803d Bumping versions to 3.1.5-SNAPSHOT after release 2022-09-02 23:46:06 +00:00
buildmaster 0213d4be21 Going back to snapshots 2022-09-02 23:46:05 +00:00
buildmaster 73cde28fcf Update SNAPSHOT to 3.1.4 2022-09-02 23:44:34 +00:00
小魏,小魏,我们要去哪里呀 5bddccf720 Customize load balanced requests according to the chosen ServiceInstance (#735) 2022-09-01 11:38:09 +02:00
Olga Maciaszek-Sharma 5f40f245af Merge remote-tracking branch 'origin/main' 2022-08-31 12:40:12 +02:00
buildmaster e4bdc13c51 Going back to snapshots 2022-07-29 19:39:18 +00:00
buildmaster f344125527 Update SNAPSHOT to 4.0.0-M4 2022-07-29 19:37:18 +00:00
Olga Maciaszek-Sharma 26e157fd46 Merge remote-tracking branch 'origin/3.1.x' 2022-07-25 16:43:26 +02:00
Olga Maciaszek-Sharma efbf71294d Merge remote-tracking branch 'origin/3.0.x' into 3.1.x 2022-07-25 16:27:38 +02:00
fml2 b4c9567de5 Update spring-cloud-openfeign.adoc 2022-07-25 16:00:28 +02:00
fml2 9529e43c01 Update spring-cloud-openfeign.adoc 2022-07-25 15:52:05 +02:00
Kwangyong Kim a26095bb6c Fix a typo in sample code
I found a typo in the latest release.
It should be `@FeignClient(url = "http://localhost:8080")`
2022-07-25 15:22:52 +02:00
Nikita Konev 8fdb488697 fix cascading deserialization Spring Data's Page by setting @JsonIgnoreProperties(ignoreUnknown = true), revert ignoring getTotalPages(), getNumberOfElements(), isFirst(), isLast() (#653) 2022-07-25 15:12:22 +02:00
spencergibb 540ec0410d Removes libs-*-local repos 2022-07-18 13:03:18 -04:00
spencergibb 8989036e93 Removes libs-*-local repos 2022-07-18 12:59:55 -04:00
Olga Maciaszek-Sharma 1c8e8056e4 Remove vulnerable transitive dependency. Fix checkstyle. 2022-07-01 16:57:29 +02:00
Olga Maciaszek-Sharma a29f28506f Remove vulnerable transitive dependency. 2022-07-01 16:38:55 +02:00
Olga Maciaszek-Sharma 926f1151c1 Add deprecations for OAuth2. 2022-07-01 16:14:32 +02:00
buildmaster 1e70aec75c Bumping versions 2022-06-30 10:59:53 +00:00
buildmaster 7e01355317 Bumping versions to 3.0.8-SNAPSHOT after release 2022-06-29 22:15:46 +00:00
buildmaster fc459044b5 Going back to snapshots 2022-06-29 22:15:46 +00:00
buildmaster e321e72e3d Update SNAPSHOT to 3.0.7 2022-06-29 22:14:15 +00:00
Olga Maciaszek-Sharma ae63aae6eb Add deprecations for OAuth2. 2022-06-29 17:40:23 +02:00
Olga Maciaszek-Sharma 10fefea29b Remove incompatible test. 2022-06-28 15:46:11 +02:00
Olga MaciaszekSharma 24d9b08d5c Backport bugfix and resolve conflicts. 2022-06-28 15:36:06 +02:00
Olga Maciaszek-Sharma d4832788f6 Resolve conflicts for backport. 2022-06-28 15:02:16 +02:00
Olga Maciaszek-Sharma ff96850ec0 Wrap underlying checked exception with IllegalStateException. Add tests. 2022-06-28 14:53:37 +02:00
Olga Maciaszek-Sharma 9023cc2dc5 Unwarap InvocationTargetException and NoFallbackAvailableException. 2022-06-28 14:53:27 +02:00
Olga Maciaszek-Sharma 6c3b8c257e Fixes gh-680. 2022-06-28 14:44:00 +02:00
buildmaster 3f55dbecba Going back to snapshots 2022-06-15 12:52:34 +00:00
buildmaster 1a72f2502e Update SNAPSHOT to 4.0.0-M3 2022-06-15 12:50:33 +00:00
spencergibb f8b3ed971e Bumps to next snapshot version 2022-05-27 13:45:43 -04:00
buildmaster bc7d39fa04 Update SNAPSHOT to 3.1.3 2022-05-26 20:27:01 +00:00
Spencer Gibb 4cba1de153 don't upload docs to maven central 2022-05-26 12:08:43 -04:00
Olga Maciaszek-Sharma 8493de9aa6 Fix @LocalServerPort imports. 2022-05-18 14:10:43 +02:00
buildmaster 1bed516e03 Bumping versions 2022-04-28 10:56:37 +00:00
buildmaster a142f6f2c0 Bumping versions to 3.1.3-SNAPSHOT after release 2022-04-27 10:53:18 +00:00
buildmaster 434ce22328 Going back to snapshots 2022-04-27 10:53:18 +00:00
buildmaster 9f160e7688 Update SNAPSHOT to 3.1.2 2022-04-27 10:51:06 +00:00
Olga Maciaszek-Sharma a3f270d3b4 Revert "Update SNAPSHOT to 3.1.2"
This reverts commit 86a2f28a9e.
2022-04-27 11:09:37 +02:00
Olga Maciaszek-Sharma 1ff643f4c1 Revert "Going back to snapshots"
This reverts commit 4cd0c363be.
2022-04-27 11:09:33 +02:00
Olga Maciaszek-Sharma 6704982bcd Revert "Bumping versions to 3.1.3-SNAPSHOT after release"
This reverts commit 909da0afdf.
2022-04-27 11:09:30 +02:00
buildmaster 909da0afdf Bumping versions to 3.1.3-SNAPSHOT after release 2022-04-26 16:02:51 +00:00
buildmaster 4cd0c363be Going back to snapshots 2022-04-26 16:02:51 +00:00
buildmaster 86a2f28a9e Update SNAPSHOT to 3.1.2 2022-04-26 16:00:40 +00:00
buildmaster 001b7388a7 Going back to snapshots 2022-03-31 21:53:30 +00:00
buildmaster 0c5c3befbc Update SNAPSHOT to 4.0.0-M2 2022-03-31 21:51:31 +00:00
Olga Maciaszek-Sharma 952a7b0ff0 Fix merge 3.1.x. 2022-03-30 15:18:37 +02:00
Olga Maciaszek-Sharma 2b1ac9caa8 merge 3.1.x 2022-03-30 13:59:03 +02:00
Olga Maciaszek-Sharma 573d933b3d Adjust to changes in commons. 2022-03-29 17:04:32 +02:00
Olga Maciaszek-Sharma 2a008d12c8 Merge remote-tracking branch 'origin/3.1.x' 2022-03-16 14:05:31 +01:00
Olga Maciaszek-Sharma d76869f214 Reformat. 2022-03-16 13:56:57 +01:00
Bhavya Agrawal 12efc629a3 [CORRECTION] Add Test Support for @RequestMapping NoPath, OnlySlashPath, MissingSlashLeadingPath. (#692) 2022-03-16 13:53:35 +01:00
buildmaster 965c168c2c Bumping versions 2022-03-11 10:57:35 +00:00
Ryan Baxter 295b5e4861 Fixing checkstyle and test errors 2022-03-10 20:06:37 -05:00
Ryan Baxter efbb0b8224 Adopt new circuit breaking naming convention by default 2022-03-10 19:53:45 -05:00
Ryan Baxter 4e1859eea6 Merge branch '3.1.x' 2022-03-10 19:53:10 -05:00
Ryan Baxter f2386e365d Provide an alternate naming convention for CB ids to allow for configuration via configuration properties (#687)
Configuration properties cannot contain characters like hash, parens, or commas
2022-03-10 19:36:51 -05:00
spencergibb 0972d4211f Migrates to TestSocketUtils from spring-cloud-test-support 2022-03-09 12:47:33 -05:00
buildmaster 2f8f114667 Bumping versions 2022-02-28 23:22:06 +00:00
Olga Maciaszek-Sharma 0d0ff50842 Use raw types in ResponseData. (#685) 2022-02-28 16:48:31 +01:00
Olga Maciaszek-Sharma 088221b9fb Merge remote-tracking branch 'origin/3.1.x' 2022-02-25 13:14:29 +01:00
Olga Maciaszek-Sharma 765431dce1 Fixes gh-680. 2022-02-25 13:14:16 +01:00
Olga Maciaszek-Sharma 8998eb3423 Merge remote-tracking branch 'origin/3.1.x' 2022-02-24 12:57:55 +01:00
Olga Maciaszek-Sharma 75fc0f6b2e Unwrap cb exception (#683) 2022-02-24 12:35:02 +01:00
buildmaster f662c0547d Bumping versions 2022-02-24 10:53:13 +00:00
buildmaster fe43b6c52b Bumping versions 2022-02-24 10:52:51 +00:00
buildmaster aa4b8a280d Bumping versions to 3.1.2-SNAPSHOT after release 2022-02-17 16:55:45 +00:00
buildmaster 973c048be5 Going back to snapshots 2022-02-17 16:55:45 +00:00
buildmaster 5a19a0a128 Update SNAPSHOT to 3.1.1 2022-02-17 16:53:23 +00:00
Can Bezmen ddc1b94555 Fix gh-490 (#679) 2022-02-15 12:54:35 +01:00
Olga Maciaszek-Sharma cef268947f Merge remote-tracking branch 'origin/3.1.x' 2022-02-14 13:14:07 +01:00
Olga Maciaszek-Sharma e99dac2af1 Fix builder customisation for load-balanced scenarios. 2022-02-14 13:13:17 +01:00
buildmaster 8d802a3fee Bumping versions 2022-02-04 00:23:21 +00:00
Olga Maciaszek-Sharma e674f488d2 Remove unnecessary dependencies. 2022-02-03 17:19:50 +01:00
Olga Maciaszek-Sharma 2eea81f93b Merge remote-tracking branch 'origin/3.1.x' 2022-01-28 10:49:07 +01:00
Felix Dittrich 83b6f043dd Move Call of applyBuildCustomizers at end of getTarget Method (#674) 2022-01-28 10:42:00 +01:00
buildmaster ee8a42e401 Going back to snapshots 2022-01-27 21:47:37 +00:00
buildmaster 53428758ad Update SNAPSHOT to 4.0.0-M1 2022-01-27 21:45:39 +00:00
buildmaster 59ac5c1b3c Bumping versions 2022-01-27 00:24:12 +00:00
spencergibb 4f7892f34d formatting 2022-01-26 16:33:21 -05:00
buildmaster 261fc58a5e Bumping versions 2022-01-20 00:23:54 +00:00
Olga MaciaszekSharma 67e8c9072d Merge remote-tracking branch 'origin/3.1.x' 2022-01-17 12:41:39 +01:00
Olga MaciaszekSharma 813ff7c8b0 Resolve SpEL null in @FeignClient fields. Fixes gh-656. 2022-01-17 12:41:20 +01:00
Olga MaciaszekSharma 7b08279aae Merge remote-tracking branch 'origin/3.1.x' 2022-01-17 10:51:54 +01:00
Olga MaciaszekSharma b8519c01a0 Refactor property naming. 2022-01-17 10:11:21 +01:00
buildmaster f60859120d Bumping versions 2022-01-15 00:23:41 +00:00
Olga MaciaszekSharma c665d2c029 Merge remote-tracking branch 'origin/3.1.x' 2022-01-14 20:02:56 +01:00
Olga Maciaszek-Sharma d626518dc5 Configure readtimeout for okhttp (#669) 2022-01-14 20:02:06 +01:00
Olga MaciaszekSharma 7f425704e4 Merge remote-tracking branch 'origin/3.1.x' 2022-01-14 17:23:03 +01:00
Olga MaciaszekSharma 8b1c1dbf4c Merge remote-tracking branch 'origin/3.1.x' into 3.1.x 2022-01-14 17:22:45 +01:00
Olga MaciaszekSharma eb11b51ee7 Fix typo in javadoc. 2022-01-14 17:22:33 +01:00
Nikita Konev 5dff9cfc49 fix cascading deserialization Spring Data's Page by setting @JsonIgnoreProperties(ignoreUnknown = true), revert ignoring getTotalPages(), getNumberOfElements(), isFirst(), isLast() (#653) 2022-01-14 17:22:04 +01:00
Olga MaciaszekSharma 6c130af613 Merge remote-tracking branch 'origin/3.1.x' 2022-01-14 17:04:11 +01:00
Olga MaciaszekSharma 468d18b8f7 Upgrade protobuf to 3.19.3. 2022-01-14 17:03:53 +01:00
Olga MaciaszekSharma 98b2511d1f Merge remote-tracking branch 'origin/3.1.x' 2022-01-12 18:14:46 +01:00
Olga MaciaszekSharma 234361e0fc Upgrade protobuf to 3.19.2. 2022-01-12 18:14:28 +01:00
Olga MaciaszekSharma 10ad8a0c6e Update license entries. 2022-01-11 15:05:02 +01:00
Olga MaciaszekSharma 505894315d Merge remote-tracking branch 'origin/3.1.x' 2022-01-11 15:03:45 +01:00
Olga MaciaszekSharma d706e071f3 Merge remote-tracking branch 'origin/3.0.x' into 3.1.x 2022-01-11 14:58:44 +01:00
Olga MaciaszekSharma 3e5aa41490 Update license entries. 2022-01-11 14:47:10 +01:00
Olga MaciaszekSharma e2048b3719 Merge remote-tracking branch 'origin/3.1.x' 2022-01-11 14:28:05 +01:00
Olga MaciaszekSharma 653a35270d Upgrade Feign version to 11.8. Fixes gh-664. 2022-01-11 14:24:35 +01:00
Olga MaciaszekSharma c195a9a1db Merge remote-tracking branch 'origin/3.0.x' into 3.1.x 2022-01-11 14:19:51 +01:00
Olga Maciaszek-Sharma 3a1d19f74f Upgarde protobuf-java (security fix) and vavr. (#663) 2022-01-11 14:12:31 +01:00
buildmaster e389726ba2 Bumping versions 2022-01-06 00:32:53 +00:00
Spencer Gibb 2cf8adf482 Update github actions to use java 17 2022-01-04 13:16:49 -05:00
spencergibb 6a1d9fe074 Updates to version 4.0.0-SNAPSHOT
Updates to java 17, framework 6, boot 3 and javax -> jakarta
2022-01-04 13:02:13 -05:00
spencergibb b6b16a034a Updates to version 4.0.0-SNAPSHOT
Updates to java 17, framework 6, boot 3 and javax -> jakarta
2022-01-04 12:26:00 -05:00
spencergibb cabf06e2fd Adds .sdkmanrc 2022-01-04 12:14:44 -05:00
buildmaster 0853ccc1e5 Bumping versions to 3.0.7-SNAPSHOT after release 2021-12-15 17:02:34 +00:00
buildmaster 13f91320b1 Going back to snapshots 2021-12-15 17:02:33 +00:00
buildmaster 7af0efd569 Update SNAPSHOT to 3.0.6 2021-12-15 17:01:03 +00:00
buildmaster 60b55c7b06 Bumping versions 2021-12-14 00:23:24 +00:00
voytech.m 7f91d7ec5a gh-631 - Add support for customizing OAuth2FeignReqeustInterceptor.accessTokenProvider (injecting e.g. LoadBalancerInterceptor) (#642) 2021-12-13 18:07:41 +01:00
Olga MaciaszekSharma bf1aa72fad Merge remote-tracking branch 'origin/main' 2021-12-08 15:39:19 +01:00
buildmaster 9629f15491 Bumping versions 2021-12-02 00:22:24 +00:00
buildmaster 26a11826ab Bumping versions to 3.1.1-SNAPSHOT after release 2021-12-01 18:40:05 +00:00
buildmaster 098ecb9dd7 Going back to snapshots 2021-12-01 18:40:05 +00:00
buildmaster 1b0626a345 Update SNAPSHOT to 3.1.0 2021-12-01 18:37:07 +00:00
Olga MaciaszekSharma fe8bbbb6da Merge remote-tracking branch 'KENNYSOFT/fcc-querymapencoder' 2021-11-30 12:47:04 +01:00
Olga MaciaszekSharma b4f6f4ee30 Merge remote-tracking branch 'origin/3.0.x' 2021-11-29 16:47:58 +01:00
Been24 70a9002002 Update RetryableFeignBlockingLoadBalancerClient.java
fix log  class
2021-11-29 16:45:40 +01:00
Olga MaciaszekSharma ffbcf788bf Merge remote-tracking branch 'origin/3.0.x' 2021-11-29 16:38:36 +01:00
Nikita Konev ad892a23f0 Support size = 0 in PageJacksonModule 2021-11-29 16:30:20 +01:00
Olga Maciaszek-Sharma 85886c0cbb Add and configure duplicate finder. Remove duplicate classes. (#633) 2021-11-29 11:46:34 +01:00
buildmaster f7e4281002 Bumping versions 2021-11-27 00:23:06 +00:00
Hyeonmin Park bd46a10a7d Add queryMapEncoder to FeignClientProperties 2021-11-24 09:51:13 +09:00
Olga MaciaszekSharma 65efa29da5 Refactor. 2021-11-09 17:40:01 +01:00
buildmaster 4e23e0cf58 Going back to snapshots 2021-11-03 11:31:10 +00:00
buildmaster d11e0d9dd4 Update SNAPSHOT to 3.1.0-RC1 2021-11-03 11:29:49 +00:00
Olga MaciaszekSharma e5deb642a2 Revert "Temporarily disable codecov."
This reverts commit ba7346573e.
2021-11-02 17:45:59 +01:00
Olga MaciaszekSharma ba7346573e Temporarily disable codecov. 2021-11-02 17:25:27 +01:00
Olga Maciaszek-Sharma 38ccf1be95 Use LB per-client properties. (#622) 2021-11-02 17:24:43 +01:00
spencergibb 5fee522f4c Uses new LoadBalancerClientsProperties class, take 2 2021-10-28 14:48:11 -04:00
spencergibb ce04947d92 Uses new LoadBalancerClientsProperties class 2021-10-28 14:38:26 -04:00
spencergibb 61f71e6ac7 formatting 2021-10-28 14:38:08 -04:00
Olga MaciaszekSharma 939f279a38 Merge remote-tracking branch 'origin/3.0.x' 2021-10-28 18:20:16 +02:00
Hyeonmin Park c0f314a5f0 GitHub workflows: Use Java version in matrix, cache functionality of actions/setup-java@v2 (#614)
* Fix GitHub workflows not using Java version in matrix

* Use cache functionality of actions/setup-java@v2
2021-10-28 18:15:02 +02:00
Sam Kruglov 0cd57b2ce7 cache support (#607) (#608) 2021-10-28 17:59:52 +02:00
spencergibb 1752dd9815 Upgrades openfeign to 11.7 2021-10-26 15:33:04 -04:00
Sam Kruglov b78eacd714 make FeignClientSpecification public (#594) (#609) 2021-10-21 16:47:10 +02:00
buildmaster 56dc4e07e4 Bumping versions to 3.0.6-SNAPSHOT after release 2021-10-21 11:48:48 +00:00
buildmaster 9167752bfb Going back to snapshots 2021-10-21 11:48:47 +00:00
buildmaster 127c866616 Update SNAPSHOT to 3.0.5 2021-10-21 11:46:52 +00:00
buildmaster 876778935c Going back to snapshots 2021-10-21 11:36:13 +00:00
buildmaster ae97365b6c Update SNAPSHOT to 3.1.0-M4 2021-10-21 11:34:56 +00:00
Olga MaciaszekSharma fd6c1290fe Merge remote-tracking branch 'origin/3.0.x' 2021-10-21 13:23:05 +02:00
Olga MaciaszekSharma 0e6b33f480 Merge remote-tracking branch 'origin/2.2.x' into 3.0.x 2021-10-21 13:04:57 +02: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
buildmaster 7f03521b0d Bumping versions 2021-10-21 00:32:35 +00:00
Sam Kruglov 21adacbc43 allow @CollectionFormat on class level (#596) (#610) 2021-10-20 15:39:52 +02:00
buildmaster 3de4b98b3d Going back to snapshots 2021-10-20 02:18:15 +00:00
buildmaster a5e66077d6 Update SNAPSHOT to 3.1.0-M3 2021-10-20 02:16:47 +00:00
Olga MaciaszekSharma 02c0a1e0f6 Merge remote-tracking branch 'origin/3.0.x' 2021-10-11 18:47:07 +02:00
Olga MaciaszekSharma 98229d5ece Merge remote-tracking branch 'origin/3.0.x' 2021-10-11 18:45:46 +02:00
Olga MaciaszekSharma 548e4d55ef Revert default circuit breaker name prefix to target.type(). Fixes gh-606. 2021-10-11 18:40:21 +02:00
Olga MaciaszekSharma 9c0dda896f Use new Spring Hateoas API. 2021-10-11 13:24:59 +02:00
Szymon Linowski f018193b9f Merge branch '3.0.x' into switch-remaining-junit4-tests-to-junit-jupiter 2021-10-06 18:45:37 +02:00
Szymon Linowski 3432b7a965 Switch remaining jUnit4 tests to jUnit jupiter 2021-10-06 18:40:36 +02:00
Szymon Linowski 8d8d948f08 Merge branch 'main' into switch-remaining-junit4-tests-to-junit-jupiter 2021-10-05 16:19:59 +02:00
buildmaster c6ea224501 Going back to snapshots 2021-10-01 17:07:56 +00:00
buildmaster f5be046f90 Update SNAPSHOT to 3.1.0-M2 2021-10-01 17:06:36 +00:00
buildmaster 9018acfc40 Bumping versions 2021-09-30 00:23:25 +00:00
GongYi 6533389e16 Add a CookieValueParameterProcessor to support @CookieValue (#604) 2021-09-29 14:01:36 +02:00
buildmaster 1ff68c11d2 Bumping versions 2021-09-28 00:22:33 +00:00
buildmaster 55ceafae4d Bumping versions to 3.0.5-SNAPSHOT after release 2021-09-21 14:39:31 +00:00
buildmaster 0c87527ea5 Going back to snapshots 2021-09-21 14:39:31 +00:00
buildmaster a2c473db2a Update SNAPSHOT to 3.0.4 2021-09-21 14:37:38 +00:00
Can Bezmen ae33802a4b FIX gh-601 2021-09-20 15:35:28 +02:00
Szymon Linowski abdb699f1d Switch remaining jUnit4 tests to jUnit jupiter 2021-09-13 16:57:25 +02:00
Olga MaciaszekSharma 8b9254a008 Merge remote-tracking branch 'origin/3.0.x' 2021-09-09 17:59:25 +02:00
Olga MaciaszekSharma c761919bc9 Only add default query params and default headers if not already in template. Fixes gh-590. 2021-09-09 17:59:08 +02:00
Olga MaciaszekSharma 95a93dcc5c Merge remote-tracking branch 'origin/3.0.x' 2021-09-08 18:52:44 +02:00
Olga MaciaszekSharma 998baed0d3 Merge remote-tracking branch 'origin/3.0.x' into 3.0.x 2021-09-08 18:52:18 +02:00
Olga MaciaszekSharma 4fc80e6b01 Update docs. Fixes gh-585. 2021-09-08 18:52:11 +02:00
Szymon Linowski 685b42e85f Switch remaining jUnit4 tests to jUnit jupiter 2021-08-01 12:04:56 +02:00
buildmaster 8dd2c82968 Going back to snapshots 2021-07-30 18:17:15 +00:00
buildmaster f4615d198e Update SNAPSHOT to 3.1.0-M1 2021-07-30 18:15:57 +00:00
spencergibb fae18f2039 migrates from symlink to include 2021-07-30 14:13:10 -04:00
Yanming Zhou ff30485b40 Respect SpringDataWebProperties where possible (#583) 2021-07-28 11:36:54 +02:00
Yanming Zhou a3704f0614 Support regex expression for @PathVariable (#577)
Fix gh-576
2021-07-27 11:54:47 +02:00
Olga MaciaszekSharma 3322f95fe4 Merge remote-tracking branch 'origin/3.0.x' 2021-07-27 11:00:05 +02:00
Kwangyong Kim c101fd2c6e Add CircuitBreakerNameResolver (#575) 2021-07-27 10:59:32 +02:00
Olga MaciaszekSharma 626d0a739b Bump Feign to 11.6. Fixes gh-584. 2021-07-27 10:52:23 +02:00
Olga MaciaszekSharma 8f403f85f2 Merge remote-tracking branch 'origin/3.0.x' 2021-07-26 17:03:58 +02:00
Olga MaciaszekSharma 71930fd9f0 Do not reset RequestAttributes. Fixes gh-572. 2021-07-26 17:03:33 +02:00
Olga MaciaszekSharma 7581b2c27f Fix github workflows setup. 2021-07-26 16:05:39 +02:00
Olga MaciaszekSharma a3ea61a586 Merge remote-tracking branch 'origin/3.0.x' 2021-07-26 16:04:14 +02:00
Olga MaciaszekSharma 1b063edf7e Upgrade Feign to 11.4. Fixes gh-581. 2021-07-26 15:37:05 +02:00
Olga MaciaszekSharma b5283e2f88 Fix Github workflow setup. 2021-07-21 13:21:08 +02:00
Olga MaciaszekSharma f3f9525081 Fix branch name. 2021-07-21 13:20:24 +02:00
Olga MaciaszekSharma a08fd801c2 Remove unnecessary property info. 2021-07-21 13:20:08 +02:00
Olga MaciaszekSharma 183e6ff30a Fix Spring Cloud Build and Spring Cloud Commons versions. 2021-07-21 12:52:28 +02:00
Olga MaciaszekSharma fe91a99984 Fix Spring Cloud Build and Spring Cloud Commons versions. 2021-07-21 12:47:18 +02:00
Olga MaciaszekSharma c2539ac6a5 Merge remote-tracking branch 'origin/3.0.x' 2021-07-21 12:23:35 +02:00
ManasviGoyal 6aeb1ff676 Added Tip (#580) 2021-07-21 12:21:21 +02:00
spencergibb 948aa13cc1 Merge branch '3.1.x' 2021-07-09 14:48:33 -04:00
spencergibb 44c63798b0 rollback to 3.0.x versions 2021-07-09 14:47:28 -04:00
Jonathan SchneiderandModerne 769b38c5c1 Refactor: replace @RequestMapping annotations
Co-authored-by: Moderne <team@moderne.io>
2021-07-09 12:16:27 +02:00
Olga MaciaszekSharma d8cbd16b76 Merge remote-tracking branch 'origin/main' into 3.1.x 2021-07-09 12:03:00 +02:00
Can Bezmen 3c402201ec Codecov for main branch (#554) 2021-07-09 11:51:57 +02:00
buildmaster deb150ed88 Bumping versions 2021-07-09 00:24:22 +00: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
Olga MaciaszekSharma 6de9fdd3e1 Merge remote-tracking branch 'origin/2.2.x' 2021-07-05 13:19:39 +02:00
Olga MaciaszekSharma 45861dd657 Merge remote-tracking branch 'origin/2.2.x'. Refactor. 2021-07-05 12:09:23 +02:00
Olga MaciaszekSharma 1f5bdd4224 Merge remote-tracking branch 'origin/2.2.x' 2021-06-10 16:08:39 +02:00
buildmaster 280291ec93 Bumping versions 2021-05-28 00:22:29 +00:00
buildmaster 0de9dd614d Going back to snapshots 2021-05-27 21:20:38 +00:00
buildmaster 93fcf38c24 Update SNAPSHOT to 3.0.3 2021-05-27 21:18:46 +00:00
buildmaster be929043c3 Bumping versions to 3.0.4-SNAPSHOT after release 2021-05-27 08:11:04 +00:00
buildmaster c7316b008a Going back to snapshots 2021-05-27 08:11:04 +00:00
buildmaster 989616ebe6 Update SNAPSHOT to 3.0.3 2021-05-27 08:08:49 +00:00
Olga MaciaszekSharma 58b0c7866c Merge remote-tracking branch 'origin/2.2.x' into main 2021-05-24 16:02:34 +02:00
Olga Maciaszek-Sharma 1187c3e5b8 Use WebConverters for Hateoas. (#543) 2021-05-14 17:15:31 +02:00
Olga MaciaszekSharma ebe30c8d3c Upgrade SC Build to 3.1.0-SNAPSHOT. 2021-05-13 14:54:10 +02:00
Olga MaciaszekSharma 4ffc61e186 Merge remote-tracking branch 'origin/main' into 3.1.x 2021-05-12 13:57:21 +02:00
Olga MaciaszekSharma 5aa1b7a529 Merge remote-tracking branch 'origin/2.2.x' into main 2021-05-12 13:56:49 +02:00
Olga Maciaszek-Sharma 5f9a827a40 Upgrade feign to 11 (#540) 2021-05-11 15:45:00 +02:00
Olga MaciaszekSharma 80a7102b14 Fix gh actions setup for branch. 2021-05-11 15:10:09 +02:00
Olga MaciaszekSharma 26a0319095 Merge remote-tracking branch 'origin/main' into 3.1.x 2021-05-10 12:31:06 +02:00
Olga MaciaszekSharma fbcebb372c Switch to a different HalInstantiator constructor for Boot 2.5 compatibility. Fixes gh-536. 2021-04-27 16:22:03 +02:00
Olga MaciaszekSharma 7b6a0c2838 Merge remote-tracking branch 'origin/main' into 3.1.x 2021-04-26 19:28:49 +02:00
Olga MaciaszekSharma 1a00bbf705 Merge 2.2.x 2021-04-26 19:28:17 +02:00
Olga MaciaszekSharma d0e035b8ff Switch from master to main. 2021-04-26 17:48:29 +02:00
Olga MaciaszekSharma 1615a5a68c Switch GH actions to main. 2021-04-26 17:36:44 +02:00
Olga MaciaszekSharma 05365b79f9 Switch version to 3.1.0-SNAPSHOT. 2021-04-26 15:47:19 +02:00
Olga MaciaszekSharma 0c1ab36fe1 Merge remote-tracking branch 'origin/2.2.x' 2021-04-22 18:14:37 +02:00
Olga MaciaszekSharma 26fb4deb18 Merge remote-tracking branch 'origin/2.2.x' 2021-04-20 17:28:31 +02:00
buildmaster 4454c820cf Bumping versions 2021-04-20 11:36:51 +00:00
Andrii BohutskyiandAndrii Bohutskyi b8e966fe14 Support circuit breaker group name (#520)
Fixes gh-514

Co-authored-by: Andrii Bohutskyi <abohutskyi@playtika.com>
2021-04-20 11:41:51 +02:00
Jasbir e47255e79d Make feign.Request.Options as refreshable beans inside Feign clients (#526) 2021-04-19 18:27:28 +02:00
Olga MaciaszekSharma 96268d16da Fix checkstyle and formatting. 2021-04-13 15:21:46 +02:00
Olga MaciaszekSharma ac019b4af1 Merge 2.2.x 2021-04-13 15:20:29 +02:00
Olga MaciaszekSharma b8aea256da Merge remote-tracking branch 'origin/2.2.x'
# Please enter a commit message to explain why this merge is necessary,
# especially if it merges an updated upstream into a topic branch.
#
# Lines starting with '#' will be ignored, and an empty message aborts
# the commit.
2021-04-13 15:11:13 +02:00
Olga MaciaszekSharma f653a6730d Merge remote-tracking branch 'origin/2.2.x' 2021-04-13 15:08:50 +02:00
Olga MaciaszekSharma e2a54c1359 Fix GH actions setup 2021-04-13 15:04:10 +02:00
Olga MaciaszekSharma a5412cc872 Merge remote-tracking branch 'origin/2.2.x' 2021-04-13 14:54:18 +02:00
Olga MaciaszekSharma aa01ccb5b2 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientBuilder.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientBuilderTests.java
2021-04-13 13:11:21 +02:00
Olga MaciaszekSharma 86713156f6 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java
2021-04-12 14:35:43 +02:00
buildmaster 9db146761a Bumping versions 2021-03-30 11:36:40 +00:00
John Niang af418a04ac Expose request attributes for circuit breaker async invocation (#510) 2021-03-30 11:39:07 +02:00
spencergibb bcea218513 Ignore tests that use reflection in jdk 16 2021-03-18 18:52:34 -04:00
buildmaster 1c49f88e2b Bumping versions 2021-03-18 11:36:51 +00:00
buildmaster 3dbaf056ec Bumping versions to 3.0.3-SNAPSHOT after release 2021-03-17 21:46:51 +00:00
buildmaster 5637465ec8 Going back to snapshots 2021-03-17 21:46:50 +00:00
buildmaster 6d7ddfa7bd Update SNAPSHOT to 3.0.2 2021-03-17 21:45:22 +00:00
Olga MaciaszekSharma 809277ef3c Fix previous merge. 2021-03-16 12:24:04 +01:00
Olga MaciaszekSharma 7cf7051083 Embed code in doc. 2021-03-12 16:00:51 +01:00
Olga MaciaszekSharma 61aee7cb21 Fix checkstyle. 2021-03-11 16:25:45 +01:00
Olga MaciaszekSharma fb3924ac72 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/pom.xml
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignAutoConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/FeignLoadBalancerAutoConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/HttpClientFeignLoadBalancerConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientAutoConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/HttpClientFeignLoadBalancedConfiguration.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/loadbalancer/FeignLoadBalancerAutoConfigurationTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientPathTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientRetryTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/FeignHttpClientPropertiesTests.java
2021-03-11 16:06:21 +01:00
Olga MaciaszekSharma dbfc255146 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/app/client/InvoiceClient.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/app/resource/InvoiceResource.java
2021-03-10 17:44:36 +01:00
Olga MaciaszekSharma 33f3841e74 Merge remote-tracking branch 'origin/2.2.x'
# 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/FeignClientProperties.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignLoadBalancer.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/LoadBalancerFeignClient.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientOverrideDefaultsTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientUsingPropertiesTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignLoadBalancerTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/RetryableFeignLoadBalancerTests.java
2021-03-03 12:02:22 +01:00
Olga MaciaszekSharma 4b962e6170 Merge 2.2.x 2021-03-01 15:37:25 +01:00
Olga MaciaszekSharma 90d78a5d68 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignHttpClientUrlTests.java
2021-03-01 15:30:33 +01:00
Olga MaciaszekSharma dcc45128b9 Merge remote-tracking branch 'origin/2.2.x' 2021-02-26 18:28:56 +01:00
Olga MaciaszekSharma 4217a0c542 Merge remote-tracking branch 'origin/2.2.x' 2021-02-26 18:17:53 +01:00
Olga MaciaszekSharma 1dbf9c2d6c Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/src/main/asciidoc/_configprops.adoc
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignAutoConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringEncoder.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/proto/ProtobufSpringEncoderTest.java
2021-02-25 10:57:09 +01:00
Olga Maciaszek-Sharma b13711f906 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsRegistrar.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientBuilderTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/FeignPageableEncodingTests.java
2021-02-19 11:58:31 +01:00
Olga Maciaszek-Sharma c6e42de202 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/pom.xml
#	pom.xml
#	spring-cloud-openfeign-core/pom.xml
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignAutoConfiguration.java
#	spring-cloud-openfeign-dependencies/pom.xml
#	spring-cloud-starter-openfeign/pom.xml
2021-02-16 17:05:15 +01:00
Jonatan Ivanov e745dd0c7c Micrometer Support (#462)
Setting up micrometer for Feign, fixes #457
This makes spring-cloud-openfeign capable of configuring any Capability (e.g.: Metrics5Capability for Dropwizard Metrics or MicrometerCapability for micrometer). This also auto-configures MicrometerCapability if a MeterRegistry is available and feign-micrometer is on the classpath.
2021-02-09 11:58:10 -08:00
buildmaster 9ac5972600 Bumping versions 2021-02-09 11:37:43 +00:00
Olga Maciaszek-Sharma 40a2ed5030 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/FeignPageableEncodingTests.java
2021-02-08 18:40:33 +01:00
Olga Maciaszek-Sharma a3db5927b3 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/PageJacksonModuleTests.java
#	spring-cloud-openfeign-dependencies/pom.xml
2021-02-08 16:24:15 +01:00
Olga Maciaszek-Sharma 5d9d99d9ea Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignAutoConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/PageJacksonModule.java
2021-02-02 15:22:34 +01:00
buildmaster a789625a98 Bumping versions 2021-01-28 11:37:33 +00:00
spencergibb e7d66882ea Better classpath protections for pagable modules.
Fixes gh-474
2021-01-27 20:10:42 -05:00
buildmaster a4155e7653 Bumping versions to 3.0.2-SNAPSHOT after release 2021-01-27 20:52:26 +00:00
buildmaster 388b141369 Going back to snapshots 2021-01-27 20:52:26 +00:00
buildmaster a42b4e4b43 Update SNAPSHOT to 3.0.1 2021-01-27 20:50:54 +00:00
Olga Maciaszek-Sharma 793842a9ac Reformat. 2021-01-27 16:54:53 +01:00
Olga Maciaszek-Sharma ec4c935384 Merge remote-tracking branch 'origin/2.2.x' 2021-01-27 16:53:03 +01:00
Olga Maciaszek-Sharma 4453424bdb Fix broken reference in docs. 2021-01-27 13:33:57 +01:00
Olga Maciaszek-Sharma db2d07500d Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/FeignPageableEncodingTests.java
2021-01-26 10:03:04 +01:00
Olga Maciaszek-Sharma 252f118bba Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignCircuitBreaker.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/circuitbreaker/CircuitBreakerTests.java
#	src/checkstyle/checkstyle-suppressions.xml
2021-01-22 17:09:30 +01:00
Olga Maciaszek-Sharma 25b8202991 Use org security policy. 2021-01-22 10:11:22 +01:00
Olga Maciaszek-Sharma 5025285c5b Merge remote-tracking branch 'origin/2.2.x'
# 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:22:52 +01:00
Olga Maciaszek-Sharma 5f932b0158 Run FeignLoadBalancerAutoConfiguration after BlockingLoadBalancerClientAutoConfiguration and LoadBalancerAutoConfiguration. Fixes gh-454. 2021-01-19 13:12:39 +01:00
Olga Maciaszek-Sharma f5461821a1 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsRegistrar.java
2021-01-19 12:52:43 +01:00
Olga Maciaszek-Sharma 1b41e39740 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/src/main/asciidoc/sagan-index.adoc
2021-01-18 11:25:04 +01:00
Olga Maciaszek-Sharma 54a090e77b Edit sagan-index. 2021-01-18 11:21:29 +01:00
Olga Maciaszek-Sharma 8bc9a0eb0a Merge remote-tracking branch 'origin/2.2.x' 2021-01-18 11:20:59 +01:00
Olga Maciaszek-Sharma 147ef8c863 Merge remote-tracking branch 'origin/2.2.x' 2021-01-18 11:16:52 +01:00
Olga Maciaszek-Sharma 5011703eb9 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/src/main/asciidoc/_configprops.adoc
2021-01-14 15:58:02 +01:00
Olga Maciaszek-Sharma c508f68b85 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/src/main/asciidoc/spring-cloud-openfeign.adoc
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignAutoConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignCircuitBreaker.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignCircuitBreakerDisabledConditions.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignCircuitBreakerInvocationHandler.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignCircuitBreakerTargeter.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClient.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/circuitbreaker/CirciutBreakerTests.java
2021-01-14 15:31:13 +01:00
Marcin Grzejszczak 01f101a910 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.
2021-01-13 10:15:05 +01:00
buildmaster 69a03ffdb8 Bumping versions 2020-12-22 11:37:23 +00:00
buildmaster 2cf8b55316 Bumping versions to 3.0.1-SNAPSHOT after release 2020-12-21 19:45:02 +00:00
buildmaster eb30c13129 Going back to snapshots 2020-12-21 19:45:02 +00:00
buildmaster 258e8aee95 Update SNAPSHOT to 3.0.0 2020-12-21 19:42:15 +00:00
spencergibb ad21ff2276 Makes test use random port. 2020-12-21 14:37:13 -05:00
Olga Maciaszek-Sharma ecfba4b6e9 Support LB stats. (#447) 2020-12-18 18:08:01 +01:00
buildmaster c060e07115 Bumping versions 2020-12-16 11:37:21 +00:00
Marcin Grzejszczak e58b52ce05 Merge pull request #445 from spring-cloud/issues_#444
Moved the code from Spring Cloud Security
2020-12-16 08:42:56 +01:00
Marcin Grzejszczak 63a524843d Added support for Spring Cloud CircuitBreaker
fixes gh-279
2020-12-15 15:52:14 +01:00
Marcin Grzejszczak a697fd274b Moved the code, added conditional interceptorl fixes gh-444 2020-12-14 14:59:31 +01:00
buildmaster 9336c1d7c5 Going back to snapshots 2020-12-11 22:07:20 +00:00
buildmaster 3e7e74c5bf Update SNAPSHOT to 3.0.0-RC1 2020-12-11 22:06:22 +00:00
Olga Maciaszek-Sharma 86551041d9 Adjust to changes in commons. 2020-12-10 17:15:26 +01:00
Olga Maciaszek-Sharma 35a5b8d614 Adjust to changes in commons. 2020-12-10 14:17:15 +01:00
Olga Maciaszek-Sharma 7047439624 Remove deprecations. 2020-12-09 19:38:04 +01:00
Olga Maciaszek-Sharma 5e61666f7c Remove deprecations. 2020-12-09 18:49:54 +01:00
Olga Maciaszek-Sharma e3810f1586 Adjust to changes in commons. 2020-12-09 15:22:10 +01:00
buildmaster 9bdda59fbb Going back to snapshots 2020-12-01 22:47:14 +00:00
buildmaster e257ec31ff Update SNAPSHOT to 3.0.0-M6 2020-12-01 22:46:17 +00:00
Olga Maciaszek-Sharma 246805815f Merge remote-tracking branch 'origin/2.2.x' 2020-12-01 17:30:47 +01:00
Olga Maciaszek-Sharma 15054fa37e Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/src/main/asciidoc/_configprops.adoc
#	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 17:22:59 +01:00
Olga Maciaszek-Sharma b231783e84 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/FeignBlockingLoadBalancerClient.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/RetryableFeignBlockingLoadBalancerClient.java
2020-11-30 19:17:55 +01:00
Olga Maciaszek-Sharma a7c804db63 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/pom.xml
#	pom.xml
#	spring-cloud-openfeign-core/pom.xml
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignBuilderCustomizer.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/clientconfig/HttpClientFeignConfiguration.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignBuilderCustomizerTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientsRegistrarTests.java
#	spring-cloud-openfeign-dependencies/pom.xml
#	spring-cloud-starter-openfeign/pom.xml
2020-11-30 18:58:29 +01:00
buildmaster 4120ca2bc6 Bumping versions 2020-11-19 11:37:07 +00:00
buildmaster 29295425f3 Going back to snapshots 2020-11-17 20:42:04 +00:00
buildmaster ef9ded650f Update SNAPSHOT to 3.0.0-M5 2020-11-17 20:41:05 +00:00
buildmaster 3c25b010c3 Bumping versions 2020-11-17 11:37:02 +00:00
Olga Maciaszek-Sharma f9a8dd13f2 Adjust to changes in security config. 2020-11-03 11:49:21 +01:00
Olga Maciaszek-Sharma f6fdd63cef Merge remote-tracking branch 'origin/master' 2020-11-03 11:47:36 +01:00
Olga Maciaszek-Sharma 410d0f29a3 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsRegistrar.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientsRegistrarTests.java
2020-11-03 11:47:30 +01:00
Olga Maciaszek-Sharma 82de713d06 Remove unnecessary test configuration. 2020-11-03 11:46:15 +01:00
Olga Maciaszek-Sharma 5e455ed14b Adjust to changes in master. 2020-11-02 14:33:58 +01:00
Olga Maciaszek-Sharma a3584a9cc8 Merge remote-tracking branch 'origin/2.2.x' 2020-11-02 14:30:54 +01:00
Olga Maciaszek-Sharma ffb17a4552 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java
2020-10-29 16:54:47 +01:00
Olga Maciaszek-Sharma 20e2548a5d Automatic reformat. 2020-10-28 18:39:20 +01:00
Olga Maciaszek-Sharma d93defe1c1 Merge remote-tracking branch 'origin/2.2.x' 2020-10-28 18:37:15 +01:00
Olga Maciaszek-Sharma db8d10a511 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	pom.xml
2020-10-28 17:53:01 +01:00
Olga Maciaszek-Sharma 6649c86be1 Support loadbalancer lifecycle (#418)
* Add LoadBalancerLifecycle support.

* Add info on SC LoadBalancer documentation.
2020-10-27 11:12:34 -05:00
Olga Maciaszek-Sharma 3f0c2850ee Extract duplicate method to utility class. 2020-10-27 17:02:04 +01:00
Olga Maciaszek-Sharma 479e1ab743 Add info on SC LoadBalancer documentation. 2020-10-23 16:12:39 +02:00
Olga Maciaszek-Sharma 77a1367796 Add LoadBalancerLifecycle support. 2020-10-23 16:04:03 +02:00
buildmaster 89f8942dff Going back to snapshots 2020-10-03 13:57:43 +00:00
buildmaster d31ce6d428 Update SNAPSHOT to 3.0.0-M4 2020-10-03 13:56:37 +00:00
Olga Maciaszek-Sharma 3c3b9a5a14 Add support for passing hints to LoadBalancer. (#412) 2020-10-02 17:15:20 +02:00
Olga Maciaszek-Sharma 582e4c0175 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/DefaultFeignLoadBalancerConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/HttpClientFeignLoadBalancerConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/OkHttpFeignLoadBalancerConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/RetryableFeignBlockingLoadBalancerClient.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/loadbalancer/FeignLoadBalancerAutoConfigurationTests.java
2020-10-02 15:32:53 +02:00
Olga Maciaszek-Sharma db3513b97b Merge remote-tracking branch 'origin/2.2.x'
Fixes gh-286.

# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/DefaultFeignLoadBalancerConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/HttpClientFeignLoadBalancerConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/OkHttpFeignLoadBalancerConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignLoadBalancer.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/RetryableFeignLoadBalancer.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/loadbalancer/FeignLoadBalancerAutoConfigurationTests.java
2020-10-02 15:15:43 +02:00
Olga Maciaszek-Sharma 1178739437 Merge remote-tracking branch 'origin/2.2.x' 2020-09-17 14:51:13 +02:00
Olga Maciaszek-Sharma 2d9f51a17f Merge 2.2.x. 2020-09-17 14:09:15 +02:00
Olga Maciaszek-Sharma faff6aef8a Reformat with updated JavaFormat plugin version. 2020-09-17 13:54:45 +02:00
Olga Maciaszek-Sharma 80710a9f20 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/pom.xml
#	pom.xml
#	spring-cloud-openfeign-core/pom.xml
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientOverrideDefaultsTests.java
#	spring-cloud-openfeign-dependencies/pom.xml
#	spring-cloud-starter-openfeign/pom.xml
2020-09-16 13:01:34 +02:00
Olga Maciaszek-Sharma d41f041efc Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	pom.xml
2020-08-13 14:41:12 +02:00
Olga Maciaszek-Sharma 2f13eb4816 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/pom.xml
#	pom.xml
#	spring-cloud-openfeign-core/pom.xml
#	spring-cloud-openfeign-dependencies/pom.xml
#	spring-cloud-starter-openfeign/pom.xml
2020-08-03 10:05:52 +02:00
Olga Maciaszek-Sharma 62aa76fb97 Merge remote-tracking branch 'origin/2.2.x' 2020-07-30 16:24:25 +02:00
buildmaster 5ce900828f Going back to snapshots 2020-07-23 18:26:47 +00:00
buildmaster 48bb0cdba5 Update SNAPSHOT to 3.0.0-M3 2020-07-23 18:25:41 +00:00
spencergibb dc5eef0125 Updates to new BlockingLoadBalancerClient constructor 2020-07-23 13:36:14 -04:00
Olga Maciaszek-Sharma 343f436b71 Merge remote-tracking branch 'origin/2.2.x' 2020-07-17 15:07:20 +02:00
Olga Maciaszek-Sharma f184c3f293 Merge remote-tracking branch 'origin/2.2.x' 2020-07-14 17:38:50 +02:00
Olga Maciaszek-Sharma f600140004 Merge remote-tracking branch 'origin/2.2.x' 2020-07-14 16:03:00 +02:00
Olga Maciaszek-Sharma d07c229b0e Merge remote-tracking branch 'origin/2.2.x' 2020-07-14 15:20:23 +02:00
Olga Maciaszek-Sharma 84cb74a898 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java
2020-07-13 17:23:49 +02:00
Ryan Baxter 9677353c27 Fixing broken tests 2020-07-09 11:13:05 -04:00
spencergibb 4766d95def Adds junit-vintage-engine 2020-06-15 16:40:29 -04:00
Marcin Grzejszczak bba3f2e92c Updated props 2020-06-08 17:54:58 +02:00
Marcin Grzejszczak c4fd4eb42e Changed packaging to jar 2020-06-08 17:12:15 +02:00
Marcin Grzejszczak b56a4a1259 Uploading sources for docs 2020-06-08 16:48:07 +02:00
Olga Maciaszek-Sharma 4a4da0e2d1 Merge remote-tracking branch 'origin/2.2.x' 2020-06-05 18:27:15 +02:00
Olga Maciaszek-Sharma efca091fda Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	pom.xml
2020-06-05 16:30:27 +02:00
Olga Maciaszek-Sharma 2e2987e787 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/src/main/asciidoc/spring-cloud-openfeign.adoc
2020-06-04 14:59:17 +02:00
Olga Maciaszek-Sharma 7cd7ed5c70 Merge remote-tracking branch 'origin/master' 2020-06-04 13:40:57 +02:00
Olga Maciaszek-Sharma 5a6a75d22b Merge 2.2.x. 2020-06-04 13:40:24 +02:00
buildmaster a790386732 Bumping versions 2020-06-04 11:37:17 +00:00
buildmaster fa5162c2fc Going back to snapshots 2020-05-29 18:40:30 +00:00
buildmaster 6d3181e718 Update SNAPSHOT to 3.0.0-M2 2020-05-29 18:39:55 +00:00
buildmaster d0278f63b1 Bumping versions 2020-05-28 11:37:14 +00:00
Olga Maciaszek-Sharma 39e915e568 Merge remote-tracking branch 'origin/2.2.x' 2020-05-27 20:14:30 +02:00
buildmaster e03d7da36d Bumping versions 2020-05-27 11:37:14 +00:00
Marcin Grzejszczak dcd5a56c86 Setting up repository for docs.spring.io migration 2020-05-25 14:39:49 +02:00
Marcin Grzejszczak d492fe0742 Setting up repository for docs.spring.io migration 2020-05-25 13:42:33 +02:00
buildmaster c9fe3af3ef Bumping versions 2020-05-22 11:37:15 +00:00
Olga Maciaszek-Sharma afb0b436c0 Merge remote-tracking branch 'origin/2.2.x' 2020-05-14 12:16:01 +02:00
spencergibb f857cca5b3 Merge branch '2.2.x' 2020-05-13 15:29:43 -04:00
Olga Maciaszek-Sharma 94ad7066a6 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/encoding/FeignPageableEncodingTests.java
2020-05-11 13:39:15 +02:00
Olga Maciaszek-Sharma 1b66594ed4 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/HystrixTargeter.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/CachingSpringLoadBalancerFactory.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/DefaultFeignLoadBalancedConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignLoadBalancer.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignRetryPolicy.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientAutoConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/HttpClientFeignLoadBalancedConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/LoadBalancerFeignClient.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/OkHttpFeignLoadBalancedConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/RetryableFeignLoadBalancer.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/RibbonResponseStatusCodeException.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/FallbackCommand.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientBuilderTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/SpringRetryDisabledTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/SpringRetryEnabledTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/hystrix/security/HystrixSecurityApplication.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/hystrix/security/HystrixSecurityTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/hystrix/security/app/CustomConcurrenyStrategy.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/hystrix/security/app/ProxyUsernameController.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/hystrix/security/app/TestInterceptor.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/hystrix/security/app/UsernameController.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/CachingSpringLoadBalancerFactoryTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignLoadBalancerTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientPathTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientRetryTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonClientTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonHttpClientConfigurationTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/FeignRibbonOkHttpClientConfigurationTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/LoadBalancerFeignClientOverrideTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/RetryableFeignLoadBalancerTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/ribbon/RibbonResponseStatusCodeExceptionTest.java
2020-05-11 13:27:20 +02:00
Olga Maciaszek-Sharma 9a335536bc Update copyright comments dates. 2020-04-21 16:59:54 +02:00
buildmaster 6ac428b21c Bumping versions 2020-04-17 02:55:34 +00:00
Spencer Gibb 30eafcd02d Removes dep mgmt for netflix 2020-04-16 22:51:51 -04:00
Olga Maciaszek-Sharma 147136b85b Remove elements that are no longer valid from tests. 2020-04-16 14:10:09 +02:00
matt62king 45589b7977 exposed client factory bean and targeter (#282) 2020-04-16 13:50:36 +02:00
matt62king f4b49d5542 add customizer for feign builder (#289)
* 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
2020-04-15 13:55:27 +02:00
Olga Maciaszek-Sharma a6b5663c69 Merge branch '2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/ValidFeignClientTests.java
2020-04-14 16:47:36 +02:00
Ryan Baxter 8f421ced21 Merge remote-tracking branch 'origin/2.2.x' 2020-04-13 16:59:00 -04:00
buildmaster 78653c3e8e Going back to snapshots 2020-04-09 22:28:42 +00:00
buildmaster 1f3ee5cfec Update SNAPSHOT to 3.0.0.M1 2020-04-09 22:28:08 +00:00
Marcin Grzejszczak e4a8b0a6a6 Updated docs 2020-04-01 13:43:38 +02:00
Olga Maciaszek-Sharma c87e5f2dbf Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/src/main/asciidoc/spring-cloud-openfeign.adoc
2020-03-27 13:04:51 +01:00
nekkiy 0afb60a72a Fix double @RequestMapping with empty value (#245)
* Fix double @RequestMapping with empty value

* Fix code style

* Fix for review

* add author to SpringMvcContract

* split SpringMvcContractTests#testDoubleRequestMapping() test
2020-03-27 11:58:26 +01:00
Olga Maciaszek-Sharma a77bd2bdf1 Remove unnecessary exception clause. 2020-03-24 17:17:25 +01:00
Olga Maciaszek-Sharma 56bee946d8 Merge remote-tracking branch 'origin/2.2.x' 2020-03-24 17:13:36 +01:00
Olga Maciaszek-Sharma 90181f34c0 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/pom.xml
#	pom.xml
#	spring-cloud-openfeign-core/pom.xml
#	spring-cloud-openfeign-dependencies/pom.xml
#	spring-cloud-starter-openfeign/pom.xml
2020-03-20 20:05:09 +01:00
Olga Maciaszek-Sharma 6b9be3f513 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/pom.xml
#	pom.xml
#	spring-cloud-openfeign-core/pom.xml
#	spring-cloud-openfeign-dependencies/pom.xml
#	spring-cloud-starter-openfeign/pom.xml
2020-03-20 20:02:12 +01:00
Olga Maciaszek-Sharma efe264d2bb Adjust to ribbon changes in commons (#300)
* Adjust to Ribbon changes in commons.

* Switch to using LoadBalancerClient bean instead of BlockingLoadBalancerClient bean following changes in commons. Remove references of Ribbon from docs and javadocs.
2020-02-22 14:11:30 +01:00
Olga Maciaszek-Sharma ffa18c4346 Fix after merge. 2020-02-05 14:59:35 +01:00
Olga Maciaszek-Sharma d6e1a9f6a1 Merge branch '2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/.flattened-pom.xml
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignClientTests.java
#	spring-cloud-openfeign-dependencies/pom.xml
#	spring-cloud-starter-openfeign/.flattened-pom.xml
2020-02-05 14:41:11 +01:00
Ryan Baxter a2e968465a Merge remote-tracking branch 'origin/2.2.x' 2020-01-29 11:00:53 -05:00
Ryan Baxter 6b656195ce Merge remote-tracking branch 'origin/2.2.x' 2020-01-29 10:39:48 -05:00
buildmaster 186711914a Bumping versions 2020-01-24 11:37:05 +00:00
Spencer Gibb 569dd54ccc Moves multipart tests and un-ignores them.
fixes gh-287
2020-01-23 16:12:06 -05:00
Spencer Gibb 91895278bf Renames test classes to be unique 2020-01-23 16:08:58 -05:00
Spencer Gibb 8683a04048 Moves multipart tests and un-ignores them.
fixes gh-287
2020-01-23 16:07:30 -05:00
Spencer Gibb 7c531d9dae Restores ignored tests.
fixes gh-280
2020-01-23 15:46:12 -05:00
Olga Maciaszek-Sharma 487390fc20 Merge branch '2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/.flattened-pom.xml
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/valid/FeignClientTests.java
#	spring-cloud-openfeign-dependencies/pom.xml
#	spring-cloud-starter-openfeign/.flattened-pom.xml
2020-01-23 15:33:04 +01:00
Olga Maciaszek-Sharma c187ff8792 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/FeignBlockingLoadBalancerClient.java
2020-01-23 15:09:14 +01:00
Spencer Gibb 826c9e9699 Makes constuctor public 2020-01-22 16:55:35 -05:00
Spencer Gibb 87ebb3cbdf Removes ribbon from auto config 2020-01-22 12:51:07 -05:00
Spencer Gibb 14a43f976d Merge branch 'master' of github.com:spring-cloud/spring-cloud-openfeign 2020-01-21 12:41:37 -05:00
Spencer Gibb 08f0fe4ae1 Ignores broken tests.
See gh-280
2020-01-21 12:40:22 -05:00
Spencer Gibb 8a08e1ec4b Removes ribbon and hystrix support 2020-01-17 19:28:33 -05:00
Spencer Gibb bf1a5e6d33 Merge branch '2.2.x' 2020-01-17 18:59:33 -05:00
Spencer Gibb 5560bc19be ignores .flattened-pom.xml 2020-01-17 18:59:24 -05:00
Spencer Gibb 36fd5d7755 removes .flattened-pom.xml 2020-01-17 18:58:51 -05:00
Spencer Gibb 3b191bcb9e Updates version to 3.0.0.BUILD-SNAPSHOT 2020-01-17 18:58:05 -05:00
239 changed files with 8605 additions and 9547 deletions
+12 -14
View File
@@ -5,9 +5,9 @@ name: Build
on: on:
push: push:
branches: [ 2.2.x ] branches: [ main ]
pull_request: pull_request:
branches: [ 2.2.x ] branches: [ main ]
jobs: jobs:
build: build:
@@ -16,20 +16,18 @@ jobs:
strategy: strategy:
matrix: matrix:
java: ["8", "11", "16"] java: ["17"]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Set up JDK 1.8 - name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v1 uses: actions/setup-java@v2
with: with:
java-version: 1.8 distribution: 'zulu'
- name: Cache local Maven repository java-version: ${{ matrix.java }}
uses: actions/cache@v2 cache: 'maven'
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Build with Maven - name: Build with Maven
run: ./mvnw clean install -B -U run: ./mvnw clean install -B -U -P sonar
- uses: codecov/codecov-action@v1
with:
fail_ci_if_error: true
-1
View File
@@ -20,5 +20,4 @@ _site/
*.swo *.swo
.vscode/ .vscode/
.flattened-pom.xml .flattened-pom.xml
.sdkmanrc
+3
View File
@@ -0,0 +1,3 @@
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=17.0.1-tem
+56 -18
View File
@@ -5,7 +5,7 @@ Edit the files in the src/main/asciidoc/ directory instead.
//// ////
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://github.com/spring-cloud/spring-cloud-openfeign/workflows/Build/badge.svg?branch=main&style=svg["Build",link="https://github.com/spring-cloud/spring-cloud-openfeign/actions"]
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://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/main/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
@@ -40,7 +40,8 @@ and binding to the Spring Environment and other Spring programming model idioms.
== Building == Building
:jdkversion: 1.8
:jdkversion: 17
=== Basic Compile and Test === Basic Compile and Test
@@ -66,23 +67,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
@@ -317,6 +304,57 @@ Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on t
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.
=== Duplicate Finder
Spring Cloud Build brings along the `basepom:duplicate-finder-maven-plugin`, that enables flagging duplicate and conflicting classes and resources on the java classpath.
==== Duplicate Finder configuration
Duplicate finder is *enabled by default* and will run in the `verify` phase of your Maven build, but it will only take effect in your project if you add the `duplicate-finder-maven-plugin` to the `build` section of the projecst's `pom.xml`.
.pom.xml
[source,xml]
----
<build>
<plugins>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
----
For other properties, we have set defaults as listed in the https://github.com/basepom/duplicate-finder-maven-plugin/wiki[plugin documentation].
You can easily override them but setting the value of the selected property prefixed with `duplicate-finder-maven-plugin`. For example, set `duplicate-finder-maven-plugin.skip` to `true` in order to skip duplicates check in your build.
If you need to add `ignoredClassPatterns` or `ignoredResourcePatterns` to your setup, make sure to add them in the plugin configuration section of your project:
[source,xml]
----
<build>
<plugins>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
<configuration>
<ignoredClassPatterns>
<ignoredClassPattern>org.joda.time.base.BaseDateTime</ignoredClassPattern>
<ignoredClassPattern>.*module-info</ignoredClassPattern>
</ignoredClassPatterns>
<ignoredResourcePatterns>
<ignoredResourcePattern>changelog.txt</ignoredResourcePattern>
</ignoredResourcePatterns>
</configuration>
</plugin>
</plugins>
</build>
----
== License == License
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/main/LICENSE.txt[here]. The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/main/LICENSE.txt[here].
+10 -2
View File
@@ -6,10 +6,10 @@
<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.9.RELEASE</version> <version>4.0.0-SNAPSHOT</version>
</parent> </parent>
<artifactId>spring-cloud-openfeign-docs</artifactId> <artifactId>spring-cloud-openfeign-docs</artifactId>
<packaging>pom</packaging> <packaging>jar</packaging>
<name>Spring Cloud OpenFeign Docs</name> <name>Spring Cloud OpenFeign Docs</name>
<description>Spring Cloud Docs</description> <description>Spring Cloud Docs</description>
<properties> <properties>
@@ -17,6 +17,8 @@
<main.basedir>${basedir}/..</main.basedir> <main.basedir>${basedir}/..</main.basedir>
<configprops.inclusionPattern>feign.*</configprops.inclusionPattern> <configprops.inclusionPattern>feign.*</configprops.inclusionPattern>
<upload-docs-zip.phase>deploy</upload-docs-zip.phase> <upload-docs-zip.phase>deploy</upload-docs-zip.phase>
<!-- Don't upload docs jar to central / repo.spring.io -->
<maven-deploy-plugin-default.phase>none</maven-deploy-plugin-default.phase>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
@@ -24,6 +26,9 @@
<artifactId>spring-cloud-starter-openfeign</artifactId> <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>
<build>
<sourceDirectory>src/main/asciidoc</sourceDirectory>
</build>
<profiles> <profiles>
<profile> <profile>
<id>docs</id> <id>docs</id>
@@ -34,9 +39,11 @@
<artifactId>git-commit-id-plugin</artifactId> <artifactId>git-commit-id-plugin</artifactId>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId> <artifactId>maven-resources-plugin</artifactId>
</plugin> </plugin>
<plugin> <plugin>
@@ -48,6 +55,7 @@
<artifactId>asciidoctor-maven-plugin</artifactId> <artifactId>asciidoctor-maven-plugin</artifactId>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId> <artifactId>maven-antrun-plugin</artifactId>
</plugin> </plugin>
<plugin> <plugin>
+1 -1
View File
@@ -1,4 +1,4 @@
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://github.com/spring-cloud/spring-cloud-openfeign/workflows/Build/badge.svg?branch=main&style=svg["Build",link="https://github.com/spring-cloud/spring-cloud-openfeign/actions"]
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://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/main/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
+32 -28
View File
@@ -1,33 +1,37 @@
|=== |===
|Name | Default | Description |Name | Default | Description
|feign.autoconfiguration.jackson.enabled | `false` | If true, PageJacksonModule and SortJacksonModule bean will be provided for Jackson page decoding. |spring.cloud.openfeign.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. |spring.cloud.openfeign.circuitbreaker.enabled | `false` | If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker.
|feign.client.config | | |spring.cloud.openfeign.circuitbreaker.group.enabled | `false` | If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker with with group.
|feign.client.decode-slash | `true` | Feign clients do not encode slash `/` characters by default. To change this behavior, set the `decodeSlash` to `false`. |spring.cloud.openfeign.client.config | |
|feign.client.default-config | `default` | |spring.cloud.openfeign.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` | |spring.cloud.openfeign.client.default-config | `default` |
|feign.compression.request.enabled | `false` | Enables the request sent by Feign to be compressed. |spring.cloud.openfeign.client.default-to-properties | `true` |
|feign.compression.request.mime-types | `[text/xml, application/xml, application/json]` | The list of supported mime types. |spring.cloud.openfeign.client.refresh-enabled | `false` | Enables options value refresh capability for Feign.
|feign.compression.request.min-request-size | `2048` | The minimum threshold content size. |spring.cloud.openfeign.compression.request.enabled | `false` | Enables the request sent by Feign to be compressed.
|feign.compression.response.enabled | `false` | Enables the response from Feign to be compressed. |spring.cloud.openfeign.compression.request.mime-types | `[text/xml, application/xml, application/json]` | The list of supported mime types.
|feign.compression.response.useGzipDecoder | `false` | Enables the default gzip decoder to be used. |spring.cloud.openfeign.compression.request.min-request-size | `2048` | The minimum threshold content size.
|feign.encoder.charset-from-content-type | `false` | Indicates whether the charset should be derived from the {@code Content-Type} header. |spring.cloud.openfeign.compression.response.enabled | `false` | Enables the response from Feign to be compressed.
|feign.httpclient.connection-timeout | `2000` | |spring.cloud.openfeign.encoder.charset-from-content-type | `false` | Indicates whether the charset should be derived from the {@code Content-Type} header.
|feign.httpclient.connection-timer-repeat | `3000` | |spring.cloud.openfeign.httpclient.connection-timeout | `2000` |
|feign.httpclient.disable-ssl-validation | `false` | |spring.cloud.openfeign.httpclient.connection-timer-repeat | `3000` |
|feign.httpclient.enabled | `true` | Enables the use of the Apache HTTP Client by Feign. |spring.cloud.openfeign.httpclient.disable-ssl-validation | `false` |
|feign.httpclient.follow-redirects | `true` | |spring.cloud.openfeign.httpclient.enabled | `true` | Enables the use of the Apache HTTP Client by Feign.
|feign.httpclient.hc5.enabled | `false` | Enables the use of the Apache HTTP Client 5 by Feign. |spring.cloud.openfeign.httpclient.follow-redirects | `true` |
|feign.httpclient.hc5.pool-concurrency-policy | | Pool concurrency policies. |spring.cloud.openfeign.httpclient.hc5.enabled | `false` | Enables the use of the Apache HTTP Client 5 by Feign.
|feign.httpclient.hc5.pool-reuse-policy | | Pool connection re-use policies. |spring.cloud.openfeign.httpclient.hc5.pool-concurrency-policy | | Pool concurrency policies.
|feign.httpclient.hc5.socket-timeout | `5` | Default value for socket timeout. |spring.cloud.openfeign.httpclient.hc5.pool-reuse-policy | | Pool connection re-use policies.
|feign.httpclient.hc5.socket-timeout-unit | | Default value for socket timeout unit. |spring.cloud.openfeign.httpclient.hc5.socket-timeout | `5` | Default value for socket timeout.
|feign.httpclient.max-connections | `200` | |spring.cloud.openfeign.httpclient.hc5.socket-timeout-unit | | Default value for socket timeout unit.
|feign.httpclient.max-connections-per-route | `50` | |spring.cloud.openfeign.httpclient.max-connections | `200` |
|feign.httpclient.time-to-live | `900` | |spring.cloud.openfeign.httpclient.max-connections-per-route | `50` |
|feign.httpclient.time-to-live-unit | | |spring.cloud.openfeign.httpclient.ok-http.read-timeout | `60s` | {@link OkHttpClient} read timeout; defaults to 60 seconds.
|feign.hystrix.enabled | `false` | If true, an OpenFeign client will be wrapped with a Hystrix circuit breaker. |spring.cloud.openfeign.httpclient.time-to-live | `900` |
|feign.okhttp.enabled | `false` | Enables the use of the OK HTTP Client by Feign. |spring.cloud.openfeign.httpclient.time-to-live-unit | |
|spring.cloud.openfeign.metrics.enabled | `true` | Enables metrics capability for Feign.
|spring.cloud.openfeign.oauth2.enabled | `false` | Enables feign interceptor for managing oauth2 access token.
|spring.cloud.openfeign.oauth2.load-balanced | `false` | Enables load balancing for oauth2 access token provider.
|spring.cloud.openfeign.okhttp.enabled | `false` | Enables the use of the OK HTTP Client by Feign.
|=== |===
-1
View File
@@ -1 +0,0 @@
spring-cloud-openfeign.adoc
+1
View File
@@ -0,0 +1 @@
include::spring-cloud-openfeign.adoc[]
+290 -166
View File
@@ -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, Spring Cloud CircuitBreaker, as well as Spring Cloud LoadBalancer to provide a load-balanced http client when using Feign. Spring Cloud integrates 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
@@ -52,10 +52,13 @@ public interface StoreClient {
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json") @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
Store update(@PathVariable("storeId") Long storeId, Store store); Store update(@PathVariable("storeId") Long storeId, Store store);
@RequestMapping(method = RequestMethod.DELETE, value = "/stores/{storeId:\\d+}")
void delete(@PathVariable Long storeId);
} }
---- ----
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]. In the `@FeignClient` annotation the String value ("stores" above) is an arbitrary client name, which is used to create a https://github.com/spring-cloud/spring-cloud-commons/blob/main/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/blocking/client/BlockingLoadBalancerClient.java[Spring Cloud LoadBalancer client].
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.
@@ -65,12 +68,15 @@ 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
for the "stores" service. If your application is a Eureka client then for the "stores" service. If your application is a Eureka client then
it will resolve the service in the Eureka service registry. If you it will resolve the service in the Eureka service registry. If you
don't want to use Eureka, you can simply configure a list of servers don't want to use Eureka, you can configure a list of servers
in your external configuration using https://cloud.spring.io/spring-cloud-static/spring-cloud-commons/current/reference/html/#simplediscoveryclient[`SimpleDiscoveryClient`]. in your external configuration using https://docs.spring.io/spring-cloud-commons/docs/current/reference/html/#simplediscoveryclient[`SimpleDiscoveryClient`].
WARNING: In order to maintain backward compatibility, is used as the default load-balancer implementation. Spring Cloud OpenFeign supports all the features available for the blocking mode of Spring Cloud LoadBalancer. You can read more about them in the https://docs.spring.io/spring-cloud-commons/docs/current/reference/html/#spring-cloud-loadbalancer[project documentation].
However, Spring Cloud Netflix Ribbon is now in maintenance mode, so we recommend using Spring Cloud LoadBalancer instead.
To do this, set the value of `spring.cloud.loadbalancer.ribbon.enabled` to `false`. TIP: To use `@EnableFeignClients` annotation on `@Configuration`-annotated-classes, make sure to specify where the clients are located, for example:
`@EnableFeignClients(basePackages = "com.example.clients")`
or list them explicitly:
`@EnableFeignClients(clients = InventoryServiceFeignClient.class)`
[[spring-cloud-feign-overriding-defaults]] [[spring-cloud-feign-overriding-defaults]]
=== Overriding Feign Defaults === Overriding Feign Defaults
@@ -94,8 +100,6 @@ In this case the client is composed from the components already in `FeignClients
NOTE: `FooConfiguration` does not need to be annotated with `@Configuration`. However, if it is, then take care to exclude it from any `@ComponentScan` that would otherwise include this configuration as it will become the default source for `feign.Decoder`, `feign.Encoder`, `feign.Contract`, etc., when specified. This can be avoided by putting it in a separate, non-overlapping package from any `@ComponentScan` or `@SpringBootApplication`, or it can be explicitly excluded in `@ComponentScan`. NOTE: `FooConfiguration` does not need to be annotated with `@Configuration`. However, if it is, then take care to exclude it from any `@ComponentScan` that would otherwise include this configuration as it will become the default source for `feign.Decoder`, `feign.Encoder`, `feign.Contract`, etc., when specified. This can be avoided by putting it in a separate, non-overlapping package from any `@ComponentScan` or `@SpringBootApplication`, or it can be explicitly excluded in `@ComponentScan`.
NOTE: The `serviceId` attribute is now deprecated in favor of the `name` attribute.
NOTE: Using `contextId` attribute of the `@FeignClient` annotation in addition to changing the name of NOTE: Using `contextId` attribute of the `@FeignClient` annotation in addition to changing the name of
the `ApplicationContext` ensemble, it will override the alias of the client name the `ApplicationContext` ensemble, it will override the alias of the client name
and it will be used as part of the name of the configuration bean created for that client. and it will be used as part of the name of the configuration bean created for that client.
@@ -117,15 +121,16 @@ Spring Cloud OpenFeign provides the following beans by default for feign (`BeanT
* `Decoder` feignDecoder: `ResponseEntityDecoder` (which wraps a `SpringDecoder`) * `Decoder` feignDecoder: `ResponseEntityDecoder` (which wraps a `SpringDecoder`)
* `Encoder` feignEncoder: `SpringEncoder` * `Encoder` feignEncoder: `SpringEncoder`
* `Logger` feignLogger: `Slf4jLogger` * `Logger` feignLogger: `Slf4jLogger`
* `MicrometerCapability` micrometerCapability: If `feign-micrometer` is on the classpath and `MeterRegistry` is available
* `CachingCapability` cachingCapability: If `@EnableCaching` annotation is used. Can be disabled via `spring.cloud.openfeign.cache.enabled`.
* `Contract` feignContract: `SpringMvcContract` * `Contract` feignContract: `SpringMvcContract`
* `Feign.Builder` feignBuilder: `HystrixFeign.Builder`
* `Feign.Builder` feignBuilder: `FeignCircuitBreaker.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 Spring Cloud LoadBalancer is on the classpath, `FeignBlockingLoadBalancerClient` is used.
If none of them is in the classpath, the default feign client is used. If none of them is on 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 `spring-cloud-starter-loadbalancer`. However, as is an optional dependency, you need to make sure it been added to your project if you want to use it.
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. The OkHttpClient and ApacheHttpClient and ApacheHC5 feign clients can be used by setting `spring.cloud.openfeign.okhttp.enabled` or `spring.cloud.openfeign.httpclient.enabled` or `spring.cloud.openfeign.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 or `org.apache.hc.client5.http.impl.classic.CloseableHttpClient` when using Apache HC5. 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:
@@ -137,6 +142,7 @@ Spring Cloud OpenFeign _does not_ provide the following beans by default for fei
* `Collection<RequestInterceptor>` * `Collection<RequestInterceptor>`
* `SetterFactory` * `SetterFactory`
* `QueryMapEncoder` * `QueryMapEncoder`
* `Capability` (`MicrometerCapability` and `CachingCapability` are provided by default)
A bean of `Retryer.NEVER_RETRY` with the type `Retryer` is created by default, which will disable retrying. A bean of `Retryer.NEVER_RETRY` with the type `Retryer` is created by default, which will disable retrying.
Notice this retrying behavior is different from the Feign default one, where it will automatically retry IOExceptions, Notice this retrying behavior is different from the Feign default one, where it will automatically retry IOExceptions,
@@ -167,7 +173,9 @@ This replaces the `SpringMvcContract` with `feign.Contract.Default` and adds a `
application.yml application.yml
[source,yaml] [source,yaml]
---- ----
feign: spring:
cloud:
openfeign:
client: client:
config: config:
feignName: feignName:
@@ -187,18 +195,25 @@ feign:
encoder: com.example.SimpleEncoder encoder: com.example.SimpleEncoder
decoder: com.example.SimpleDecoder decoder: com.example.SimpleDecoder
contract: com.example.SimpleContract contract: com.example.SimpleContract
capabilities:
- com.example.FooCapability
- com.example.BarCapability
queryMapEncoder: com.example.SimpleQueryMapEncoder
metrics.enabled: false
---- ----
Default configurations can be specified in the `@EnableFeignClients` attribute `defaultConfiguration` in a similar manner as described above. The difference is that this configuration will apply to _all_ feign clients. Default configurations can be specified in the `@EnableFeignClients` attribute `defaultConfiguration` in a similar manner as described above. The difference is that this configuration will apply to _all_ feign clients.
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 configure 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`. You can use `spring.cloud.openfeign.client.config.feignName.defaultQueryParameters` and `spring.cloud.openfeign.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]
---- ----
feign: spring:
cloud:
openfeign:
client: client:
config: config:
default: default:
@@ -209,27 +224,7 @@ feign:
If we create both `@Configuration` bean and configuration properties, configuration properties will win. If we create both `@Configuration` bean and configuration properties, configuration properties will win.
It will override `@Configuration` values. But if you want to change the priority to `@Configuration`, It will override `@Configuration` values. But if you want to change the priority to `@Configuration`,
you can change `feign.client.default-to-properties` to `false`. you can change `spring.cloud.openfeign.client.default-to-properties` to `false`.
NOTE: If you need to use `ThreadLocal` bound variables in your `RequestInterceptor`s you will need to either set the
thread isolation strategy for Hystrix to `SEMAPHORE` or disable Hystrix in Feign.
application.yml
[source,yaml]
----
# To disable Hystrix in Feign
feign:
hystrix:
enabled: false
# To set thread isolation to SEMAPHORE
hystrix:
command:
default:
execution:
isolation:
strategy: SEMAPHORE
----
If we want to create multiple feign clients with the same name or url If we want to create multiple feign clients with the same name or url
so that they would point to the same server but each with a different custom configuration then so that they would point to the same server but each with a different custom configuration then
@@ -275,13 +270,13 @@ public FeignClientConfigurer feignClientConfigurer() {
} }
---- ----
TIP: By default, Feign clients do not encode slash `/` characters. You can change this behaviour, by setting the value of `feign.client.decodeSlash` to `false`. TIP: By default, Feign clients do not encode slash `/` characters. You can change this behaviour, by setting the value of `spring.cloud.openfeign.client.decodeSlash` to `false`.
==== `SpringEncoder` configuration ==== `SpringEncoder` configuration
In the `SpringEncoder` that we provide, we set `null` charset for binary content types and `UTF-8` for all the other ones. 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`. You can modify this behaviour to derive the charset from the `Content-Type` header charset instead by setting the value of `spring.cloud.openfeign.encoder.charset-from-content-type` to `true`.
[[timeout-handling]] [[timeout-handling]]
=== Timeout Handling === Timeout Handling
@@ -293,32 +288,6 @@ We can configure timeouts on both the default and the named client. OpenFeign wo
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. 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
@@ -337,11 +306,12 @@ class FooController {
private FooClient adminClient; private FooClient adminClient;
@Autowired @Autowired
public FooController(Decoder decoder, Encoder encoder, Client client, Contract contract) { public FooController(Client client, Encoder encoder, Decoder decoder, Contract contract, MicrometerCapability micrometerCapability) {
this.fooClient = Feign.builder().client(client) this.fooClient = Feign.builder().client(client)
.encoder(encoder) .encoder(encoder)
.decoder(decoder) .decoder(decoder)
.contract(contract) .contract(contract)
.addCapability(micrometerCapability)
.requestInterceptor(new BasicAuthRequestInterceptor("user", "user")) .requestInterceptor(new BasicAuthRequestInterceptor("user", "user"))
.target(FooClient.class, "https://PROD-SVC"); .target(FooClient.class, "https://PROD-SVC");
@@ -349,6 +319,7 @@ class FooController {
.encoder(encoder) .encoder(encoder)
.decoder(decoder) .decoder(decoder)
.contract(contract) .contract(contract)
.addCapability(micrometerCapability)
.requestInterceptor(new BasicAuthRequestInterceptor("admin", "admin")) .requestInterceptor(new BasicAuthRequestInterceptor("admin", "admin"))
.target(FooClient.class, "https://PROD-SVC"); .target(FooClient.class, "https://PROD-SVC");
} }
@@ -367,80 +338,10 @@ the default Feign native annotations.
You can also use the `Builder`to configure FeignClient not to inherit beans from the parent context. You can also use the `Builder`to configure FeignClient not to inherit beans from the parent context.
You can do this by overriding calling `inheritParentContext(false)` on the `Builder`. You can do this by overriding calling `inheritParentContext(false)` on the `Builder`.
[[spring-cloud-feign-hystrix]]
=== Feign Hystrix Support
If Hystrix is on the classpath and `feign.hystrix.enabled=true`, Feign will wrap all methods with a circuit breaker. Returning a `com.netflix.hystrix.HystrixCommand` is also available. This lets you use reactive patterns (with a call to `.toObservable()` or `.observe()` or asynchronous use (with a call to `.queue()`).
To disable Hystrix 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();
}
}
----
WARNING: Prior to the Spring Cloud Dalston release, if Hystrix was on the classpath Feign would have wrapped
all methods in a circuit breaker by default. This default behavior was changed in Spring Cloud Dalston in
favor for an opt-in approach.
[[spring-cloud-feign-hystrix-fallback]]
=== Feign Hystrix Fallbacks
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]
----
@FeignClient(name = "hello", fallback = HystrixClientFallback.class)
protected interface HystrixClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello iFailSometimes();
}
static class HystrixClientFallback implements HystrixClient {
@Override
public Hello iFailSometimes() {
return new Hello("fallback");
}
}
----
If one needs access to the cause that made the fallback trigger, one can use the `fallbackFactory` attribute inside `@FeignClient`.
[source,java,indent=0]
----
@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
protected interface HystrixClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello iFailSometimes();
}
@Component
static class HystrixClientFallbackFactory implements FallbackFactory<HystrixClient> {
@Override
public HystrixClient create(Throwable cause) {
return new HystrixClient() {
@Override
public Hello iFailSometimes() {
return new Hello("fallback; reason was: " + cause.getMessage());
}
};
}
}
----
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]] [[spring-cloud-feign-circuitbreaker]]
=== Feign Spring Cloud CircuitBreaker Support === 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. If Spring Cloud CircuitBreaker is on the classpath and `spring.cloud.openfeign.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.: To disable Spring Cloud CircuitBreaker support on a per-client basis create a vanilla `Feign.Builder` with the "prototype" scope, e.g.:
@@ -456,7 +357,64 @@ public class FooConfiguration {
} }
---- ----
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`. The circuit breaker name follows this pattern `<feignClientClassName>#<calledMethod>(<parameterTypes>)`. When calling a `@FeignClient` with `FooClient` interface and the called interface method that has no parameters is `bar` then the circuit breaker name will be `FooClient#bar()`.
NOTE: As of 2020.0.2, the circuit breaker name pattern has changed from `<feignClientName>_<calledMethod>`.
Using `CircuitBreakerNameResolver` introduced in 2020.0.4, circuit breaker names can retain the old pattern.
Providing a bean of `CircuitBreakerNameResolver`, you can change the circuit breaker name pattern.
[source,java,indent=0]
----
@Configuration
public class FooConfiguration {
@Bean
public CircuitBreakerNameResolver circuitBreakerNameResolver() {
return (String feignClientName, Target<?> target, Method method) -> feignClientName + "_" + method.getName();
}
}
----
To enable Spring Cloud CircuitBreaker group set the `spring.cloud.openfeign.circuitbreaker.group.enabled` property to `true` (by default `false`).
[[spring-clou-feign-circuitbreaker-configurationproperties]]
=== Configuring CircuitBreakers With Configuration Properties
You can configure CircuitBreakers via configuration properties.
For example, if you had this Feign client
[source,java,indent=0]
----
@FeignClient(url = "http://localhost:8080")
public interface DemoClient {
@GetMapping("demo")
String getDemo();
}
----
You could configure it using configuration properties by doing the following
[source,yaml,indent=0]
----
feign:
circuitbreaker:
enabled: true
alphanumeric-ids:
enabled: true
resilience4j:
circuitbreaker:
instances:
DemoClientgetDemo:
minimumNumberOfCalls: 69
timelimiter:
instances:
DemoClientgetDemo:
timeoutDuration: 10s
----
NOTE: If you want to switch back to the circuit breaker names used prior to Spring Cloud
2022.0.0 you can set `spring.cloud.openfeign.circuitbreaker.alphanumeric-ids.enabled` to `false`.
[[spring-cloud-feign-circuitbreaker-fallback]] [[spring-cloud-feign-circuitbreaker-fallback]]
=== Feign Spring Cloud CircuitBreaker Fallbacks === Feign Spring Cloud CircuitBreaker Fallbacks
@@ -465,19 +423,77 @@ Spring Cloud CircuitBreaker supports the notion of a fallback: a default code pa
[source,java,indent=0] [source,java,indent=0]
---- ----
include::{core_path}/src/test/java/org/springframework/cloud/openfeign/circuitbreaker/CircuitBreakerTests.java[tags=client_with_fallback, indent=0] @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";
}
}
---- ----
If one needs access to the cause that made the fallback trigger, one can use the `fallbackFactory` attribute inside `@FeignClient`. If one needs access to the cause that made the fallback trigger, one can use the `fallbackFactory` attribute inside `@FeignClient`.
[source,java,indent=0] [source,java,indent=0]
---- ----
include::{core_path}/src/test/java/org/springframework/cloud/openfeign/circuitbreaker/CircuitBreakerTests.java[tags=client_with_fallback_factory, indent=0] @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";
}
}
---- ----
=== 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 Spring Cloud CircuitBreaker 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.
[source,java,indent=0] [source,java,indent=0]
---- ----
@@ -523,10 +539,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
@@ -535,29 +548,21 @@ Feign requests. You can do this by enabling one of the properties:
[source,java] [source,java]
---- ----
feign.compression.request.enabled=true spring.cloud.openfeign.compression.request.enabled=true
feign.compression.response.enabled=true spring.cloud.openfeign.compression.response.enabled=true
---- ----
Feign request compression gives you settings similar to what you may set for your web server: Feign request compression gives you settings similar to what you may set for your web server:
[source,java] [source,java]
---- ----
feign.compression.request.enabled=true spring.cloud.openfeign.compression.request.enabled=true
feign.compression.request.mime-types=text/xml,application/xml,application/json spring.cloud.openfeign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=2048 spring.cloud.openfeign.compression.request.min-request-size=2048
---- ----
These properties allow you to be selective about the compressed media types and minimum request threshold length. These properties allow you to be selective about the compressed media types and minimum request threshold length.
For http clients except OkHttpClient, default gzip decoder can be enabled to decode gzip response in UTF-8 encoding:
[source,java]
----
feign.compression.response.enabled=true
feign.compression.response.useGzipDecoder=true
----
=== Feign logging === Feign logging
A logger is created for each Feign client created. By default the name of the logger is the full class name of the interface used to create the Feign client. Feign logging only responds to the `DEBUG` level. A logger is created for each Feign client created. By default the name of the logger is the full class name of the interface used to create the Feign client. Feign logging only responds to the `DEBUG` level.
@@ -589,6 +594,75 @@ public class FooConfiguration {
} }
---- ----
=== Feign Capability support
The Feign capabilities expose core Feign components so that these components can be modified. For example, the capabilities can take the `Client`, _decorate_ it, and give the decorated instance back to Feign.
The support for metrics libraries is a good real-life example for this. See <<feign-metrics>>.
Creating one or more `Capability` beans and placing them in a `@FeignClient` configuration lets you register them and modify the behavior of the involved client.
[source,java,indent=0]
----
@Configuration
public class FooConfiguration {
@Bean
Capability customCapability() {
return new CustomCapability();
}
}
----
=== Feign metrics
If all of the following conditions are true, a `MicrometerCapability` bean is created and registered so that your Feign client publishes metrics to Micrometer:
* `feign-micrometer` is on the classpath
* A `MeterRegistry` bean is available
* feign metrics properties are set to `true` (by default)
- `spring.cloud.openfeign.metrics.enabled=true` (for all clients)
- `spring.cloud.openfeign.client.config.feignName.metrics.enabled=true` (for a single client)
NOTE: If your application already uses Micrometer, enabling metrics is as simple as putting `feign-micrometer` onto your classpath.
You can also disable the feature by either:
* excluding `feign-micrometer` from your classpath
* setting one of the feign metrics properties to `false`
- `spring.cloud.openfeign.metrics.enabled=false`
- `spring.cloud.openfeign.client.config.feignName.metrics.enabled=false`
NOTE: `spring.cloud.openfeign.metrics.enabled=false` disables metrics support for *all* Feign clients regardless of the value of the client-level flags: `spring.cloud.openfeign.client.config.feignName.metrics.enabled`.
If you want to enable or disable merics per client, don't set `spring.cloud.openfeign.metrics.enabled` and use `spring.cloud.openfeign.client.config.feignName.metrics.enabled`.
You can also customize the `MicrometerCapability` by registering your own bean:
[source,java,indent=0]
----
@Configuration
public class FooConfiguration {
@Bean
public MicrometerCapability micrometerCapability(MeterRegistry meterRegistry) {
return new MicrometerCapability(meterRegistry);
}
}
----
=== Feign Caching
If `@EnableCaching` annotation is used, a `CachingCapability` bean is created and registered so that your Feign client recognizes `@Cache*` annotations on its interface:
[source,java,indent=0]
----
public interface DemoClient {
@GetMapping("/demo/{filterParam}")
@Cacheable(cacheNames = "demo-cache", key = "#keyParam")
String demoEndpoint(String keyParam, @PathVariable String filterParam);
}
----
You can also disable the feature via property `spring.cloud.openfeign.cache.enabled=false`.
=== Feign @QueryMap support === Feign @QueryMap support
The OpenFeign `@QueryMap` annotation provides support for POJOs to be used as The OpenFeign `@QueryMap` annotation provides support for POJOs to be used as
@@ -676,26 +750,27 @@ public interface DemoTemplate {
---- ----
=== Feign `CollectionFormat` support === Feign `CollectionFormat` support
We support `feign.CollectionFormat` by providing the `@CollectionFormat` annotation. You can annotate a Feign client method with it by passing the desired `feign.CollectionFormat` as annotation value. We support `feign.CollectionFormat` by providing the `@CollectionFormat` annotation.
You can annotate a Feign client method (or the whole class to affect all methods) with it by passing the desired `feign.CollectionFormat` as annotation value.
In the following example, the `CSV` format is used instead of the default `EXPLODED` to process the method. In the following example, the `CSV` format is used instead of the default `EXPLODED` to process the method.
[source,java,indent=0] [source,java,indent=0]
---- ----
@FeignClient(name = "demo") @FeignClient(name = "demo")
protected interface PageableFeignClient { protected interface PageableFeignClient {
@CollectionFormat(feign.CollectionFormat.CSV) @CollectionFormat(feign.CollectionFormat.CSV)
@GetMapping(path = "/page") @GetMapping(path = "/page")
ResponseEntity performRequest(Pageable page); ResponseEntity performRequest(Pageable page);
} }
---- ----
TIP: Set the `CSV` format while sending `Pageable` as a query parameter in order for it to be encoded correctly. TIP: Set the `CSV` format while sending `Pageable` as a query parameter in order for it to be encoded correctly.
=== Reactive Support === Reactive Support
As the https://github.com/OpenFeign/feign[OpenFeign project] does not currently support reactive clients, such as https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html[Spring WebClient], neither does Spring Cloud OpenFeign. We will add support for it here as soon as it becomes available in the core project. As the https://github.com/OpenFeign/feign[OpenFeign project] does not currently support reactive clients, such as https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html[Spring WebClient], neither does Spring Cloud OpenFeign.We will add support for it here as soon as it becomes available in the core project.
Until that is done, we recommend using https://github.com/Playtika/feign-reactive[feign-reactive] for Spring WebClient support. Until that is done, we recommend using https://github.com/Playtika/feign-reactive[feign-reactive] for Spring WebClient support.
@@ -707,17 +782,66 @@ To work around this problem you can use an `ObjectProvider` when autowiring your
[source,java,indent=0] [source,java,indent=0]
---- ----
@Autowired @Autowired
ObjectProvider<TestFeginClient> testFeginClient; ObjectProvider<TestFeignClient> testFeignClient;
---- ----
=== Spring Data Support === Spring Data Support
You may consider enabling Jackson Modules for the support `org.springframework.data.domain.Page` and `org.springframework.data.domain.Sort` decoding. You may consider enabling Jackson Modules for the support `org.springframework.data.domain.Page` and `org.springframework.data.domain.Sort` decoding.
[source,java] [source,java]
---- ----
feign.autoconfiguration.jackson.enabled=true spring.cloud.openfeign.autoconfiguration.jackson.enabled=true
---- ----
=== Spring `@RefreshScope` Support
If Feign client refresh is enabled, each feign client is created with `feign.Request.Options` as a refresh-scoped bean. This means properties such as `connectTimeout` and `readTimeout` can be refreshed against any Feign client instance through `POST /actuator/refresh`.
By default, refresh behavior in Feign clients is disabled. Use the following property to enable refresh behavior:
[source,java]
----
spring.cloud.openfeign.client.refresh-enabled=true
----
TIP: DO NOT annotate the `@FeignClient` interface with the `@RefreshScope` annotation.
=== OAuth2 Support
OAuth2 support can be enabled by setting following flag:
----
spring.cloud.openfeign.oauth2.enabled=true
----
When the flag is set to true, and the oauth2 client context resource details are present, a bean of class `OAuth2FeignRequestInterceptor` is created. Before each request, the interceptor resolves the required access token and includes it as a header.
Sometimes, when load balancing is enabled for Feign clients, you may want to use load balancing for fetching access tokens, too. To do so, you should ensure that the load balancer is on the classpath (spring-cloud-starter-loadbalancer) and explicitly enable load balancing for OAuth2FeignRequestInterceptor by setting the following flag:
----
spring.cloud.openfeign.oauth2.load-balanced=true
----
=== Transform the load-balanced HTTP request
You can use the selected `ServiceInstance` to transform the load-balanced HTTP Request.
For `Request`, you need to implement and define `LoadBalancerFeignRequestTransformer`, as follows:
[source,java,indent=0]
----
@Bean
public LoadBalancerFeignRequestTransformer transformer() {
return new LoadBalancerFeignRequestTransformer() {
@Override
public Request transformRequest(Request request, ServiceInstance instance) {
Map<String, Collection<String>> headers = new HashMap<>(request.headers());
headers.put("X-ServiceId", Collections.singletonList(instance.getServiceId()));
headers.put("X-InstanceId", Collections.singletonList(instance.getInstanceId()));
return Request.create(request.httpMethod(), request.url(), headers, request.body(), request.charset(),
request.requestTemplate());
}
};
}
----
If multiple transformers are defined, they are applied in the order in which beans are defined.
Alternatively, you can use `LoadBalancerFeignRequestTransformer.DEFAULT_ORDER` to specify the order.
== Configuration properties == Configuration properties
To see the list of all Spring Cloud OpenFeign 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].
+17 -23
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.9.RELEASE</version> <version>4.0.0-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.5.RELEASE</version> <version>4.0.0-SNAPSHOT</version>
<relativePath/> <relativePath/>
</parent> </parent>
<scm> <scm>
@@ -26,8 +26,7 @@
<properties> <properties>
<main.basedir>${basedir}</main.basedir> <main.basedir>${basedir}</main.basedir>
<jackson.version>2.11.3</jackson.version> <jackson.version>2.11.3</jackson.version>
<spring-cloud-commons.version>2.2.9.RELEASE</spring-cloud-commons.version> <spring-cloud-commons.version>4.0.0-SNAPSHOT</spring-cloud-commons.version>
<spring-cloud-netflix.version>2.2.9.RELEASE</spring-cloud-netflix.version>
<!-- Plugin versions --> <!-- Plugin versions -->
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version> <maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
@@ -65,13 +64,6 @@
</additionalConfig> </additionalConfig>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId> <artifactId>maven-checkstyle-plugin</artifactId>
@@ -80,6 +72,15 @@
<groupId>io.spring.javaformat</groupId> <groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId> <artifactId>spring-javaformat-maven-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
<configuration>
<ignoredResourcePatterns>
<ignoredResourcePattern>mozilla/public-suffix-list.txt</ignoredResourcePattern>
</ignoredResourcePatterns>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
@@ -94,13 +95,6 @@
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-dependencies</artifactId>
<version>${spring-cloud-netflix.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons-dependencies</artifactId> <artifactId>spring-cloud-commons-dependencies</artifactId>
@@ -141,7 +135,7 @@
<repository> <repository>
<id>spring-snapshots</id> <id>spring-snapshots</id>
<name>Spring Snapshots</name> <name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-snapshot-local</url> <url>https://repo.spring.io/snapshot</url>
<snapshots> <snapshots>
<enabled>true</enabled> <enabled>true</enabled>
</snapshots> </snapshots>
@@ -152,7 +146,7 @@
<repository> <repository>
<id>spring-milestones</id> <id>spring-milestones</id>
<name>Spring Milestones</name> <name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url> <url>https://repo.spring.io/milestone</url>
<snapshots> <snapshots>
<enabled>false</enabled> <enabled>false</enabled>
</snapshots> </snapshots>
@@ -170,7 +164,7 @@
<pluginRepository> <pluginRepository>
<id>spring-snapshots</id> <id>spring-snapshots</id>
<name>Spring Snapshots</name> <name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-snapshot-local</url> <url>https://repo.spring.io/snapshot</url>
<snapshots> <snapshots>
<enabled>true</enabled> <enabled>true</enabled>
</snapshots> </snapshots>
@@ -181,7 +175,7 @@
<pluginRepository> <pluginRepository>
<id>spring-milestones</id> <id>spring-milestones</id>
<name>Spring Milestones</name> <name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url> <url>https://repo.spring.io/milestone</url>
<snapshots> <snapshots>
<enabled>false</enabled> <enabled>false</enabled>
</snapshots> </snapshots>
@@ -189,7 +183,7 @@
<pluginRepository> <pluginRepository>
<id>spring-releases</id> <id>spring-releases</id>
<name>Spring Releases</name> <name>Spring Releases</name>
<url>https://repo.spring.io/libs-release-local</url> <url>https://repo.spring.io/release</url>
<snapshots> <snapshots>
<enabled>false</enabled> <enabled>false</enabled>
</snapshots> </snapshots>
+43 -64
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.9.RELEASE</version> <version>4.0.0-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>
@@ -21,10 +21,6 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId> <artifactId>spring-boot-autoconfigure</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-ribbon</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId> <artifactId>spring-boot-starter-actuator</artifactId>
@@ -65,15 +61,16 @@
<artifactId>reactor-core</artifactId> <artifactId>reactor-core</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava-reactive-streams</artifactId>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.retry</groupId> <groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId> <artifactId>spring-retry</artifactId>
<optional>true</optional> <optional>true</optional>
<exclusions>
<exclusion>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
@@ -89,11 +86,6 @@
<artifactId>spring-cloud-context</artifactId> <artifactId>spring-cloud-context</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>com.netflix.ribbon</groupId>
<artifactId>ribbon-loadbalancer</artifactId>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>io.github.openfeign</groupId> <groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId> <artifactId>feign-core</artifactId>
@@ -102,6 +94,13 @@
<dependency> <dependency>
<groupId>io.github.openfeign.form</groupId> <groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId> <artifactId>feign-form-spring</artifactId>
<exclusions>
<!-- Vulnerable in 3.8.0-->
<exclusion>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.github.openfeign</groupId> <groupId>io.github.openfeign</groupId>
@@ -110,7 +109,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.github.openfeign</groupId> <groupId>io.github.openfeign</groupId>
<artifactId>feign-hc5</artifactId> <artifactId>feign-micrometer</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency> <dependency>
@@ -120,7 +119,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.github.openfeign</groupId> <groupId>io.github.openfeign</groupId>
<artifactId>feign-hystrix</artifactId> <artifactId>feign-hc5</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency> <dependency>
@@ -128,46 +127,30 @@
<artifactId>feign-okhttp</artifactId> <artifactId>feign-okhttp</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-serialization</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-metrics-event-stream</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-javanica</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.netflix.ribbon</groupId>
<artifactId>ribbon-core</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.netflix.ribbon</groupId>
<artifactId>ribbon-httpclient</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava</artifactId>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>com.squareup.okhttp3</groupId> <groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId> <artifactId>okhttp</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<optional>true</optional>
<exclusions>
<exclusion>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.activation</groupId>
<artifactId>javax.activation-api</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.activation</groupId>
<artifactId>jakarta.activation</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure-processor</artifactId> <artifactId>spring-boot-autoconfigure-processor</artifactId>
@@ -198,16 +181,6 @@
<artifactId>reactor-test</artifactId> <artifactId>reactor-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.netflix.ribbon</groupId>
<artifactId>ribbon</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId> <artifactId>spring-boot-starter-data-rest</artifactId>
@@ -222,13 +195,13 @@
<dependency> <dependency>
<groupId>com.google.protobuf</groupId> <groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId> <artifactId>protobuf-java</artifactId>
<version>3.14.0</version> <version>3.19.3</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.3</version> <version>0.10.4</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@@ -236,6 +209,12 @@
<artifactId>spring-cloud-loadbalancer</artifactId> <artifactId>spring-cloud-loadbalancer</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<profiles> <profiles>
<profile> <profile>
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -43,8 +43,7 @@ public interface AnnotatedParameterProcessor {
* @param method the method that contains the annotation * @param method the method that contains the annotation
* @return whether the parameter is http * @return whether the parameter is http
*/ */
boolean processArgument(AnnotatedParameterContext context, Annotation annotation, boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method);
Method method);
/** /**
* Specifies the parameter context. * Specifies the parameter context.
@@ -0,0 +1,42 @@
/*
* Copyright 2013-2022 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.Capability;
import feign.InvocationHandlerFactory;
import org.springframework.cache.interceptor.CacheInterceptor;
/**
* Allows Spring's @Cache* annotations to be declared on the feign client's methods.
*
* @author Sam Kruglov
*/
public class CachingCapability implements Capability {
private final CacheInterceptor cacheInterceptor;
public CachingCapability(CacheInterceptor cacheInterceptor) {
this.cacheInterceptor = cacheInterceptor;
}
@Override
public InvocationHandlerFactory enrich(InvocationHandlerFactory invocationHandlerFactory) {
return new FeignCachingInvocationHandlerFactory(invocationHandlerFactory, cacheInterceptor);
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -14,22 +14,21 @@
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.cloud.openfeign.hystrix.security.app; package org.springframework.cloud.openfeign;
import org.springframework.web.bind.annotation.RequestHeader; import java.lang.reflect.Method;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import feign.Target;
/** /**
* @author Daniel Lavoie * Used to resolve a circuitbreaker name which will be used in
* {@link org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory}.
*
* @author Kwangyong Kim
* @since 2020.0.4
*/ */
@RestController public interface CircuitBreakerNameResolver {
@RequestMapping("/username")
public class UsernameController {
@RequestMapping String resolveCircuitBreakerName(String feignClientName, Target<?> target, Method method);
public String getUsername(@RequestHeader String username) {
return username;
}
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -25,9 +25,10 @@ import java.lang.annotation.Target;
* Indicates which collection format should be used while processing the annotated method. * Indicates which collection format should be used while processing the annotated method.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Sam Kruglov
* @see feign.CollectionFormat * @see feign.CollectionFormat
*/ */
@Target(ElementType.METHOD) @Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface CollectionFormat { public @interface CollectionFormat {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2016-2020 the original author or authors. * Copyright 2016-2022 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.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -25,8 +25,8 @@ import feign.Target;
class DefaultTargeter implements Targeter { class DefaultTargeter implements Targeter {
@Override @Override
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context,
FeignContext context, Target.HardCodedTarget<T> target) { Target.HardCodedTarget<T> target) {
return feign.target(target); return feign.target(target);
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 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,20 +17,24 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Method;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;
import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.Module;
import feign.Capability;
import feign.Client; import feign.Client;
import feign.Feign; import feign.Feign;
import feign.RequestInterceptor;
import feign.Target;
import feign.hc5.ApacheHttp5Client; import feign.hc5.ApacheHttp5Client;
import feign.httpclient.ApacheHttpClient; import feign.httpclient.ApacheHttpClient;
import feign.okhttp.OkHttpClient; import feign.okhttp.OkHttpClient;
import jakarta.annotation.PreDestroy;
import okhttp3.ConnectionPool; import okhttp3.ConnectionPool;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@@ -41,21 +45,24 @@ 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.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 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.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.cache.interceptor.CacheInterceptor;
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.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory; import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.cloud.client.loadbalancer.RetryLoadBalancerInterceptor;
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.security.OAuth2FeignRequestInterceptor;
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptorConfigurer;
import org.springframework.cloud.openfeign.support.FeignEncoderProperties; 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.PageJacksonModule;
@@ -66,6 +73,10 @@ 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.Page;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import static org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptorBuilder.buildWithConfigurers;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
@@ -75,12 +86,15 @@ import org.springframework.data.domain.Sort;
* @author Tim Peeters * @author Tim Peeters
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh * @author Nguyen Ky Thanh
* @author Andrii Bohutskyi
* @author Kwangyong Kim
* @author Sam Kruglov
* @author Wojciech Mąka
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Feign.class) @ConditionalOnClass(Feign.class)
@EnableConfigurationProperties({ FeignClientProperties.class, @EnableConfigurationProperties({ FeignClientProperties.class, FeignHttpClientProperties.class,
FeignHttpClientProperties.class, FeignEncoderProperties.class }) FeignEncoderProperties.class })
@Import(DefaultGzipDecoderConfiguration.class)
public class FeignAutoConfiguration { public class FeignAutoConfiguration {
private static final Log LOG = LogFactory.getLog(FeignAutoConfiguration.class); private static final Log LOG = LogFactory.getLog(FeignAutoConfiguration.class);
@@ -100,10 +114,16 @@ public class FeignAutoConfiguration {
return context; return context;
} }
@Bean
@ConditionalOnProperty(value = "spring.cloud.openfeign.cache.enabled", matchIfMissing = true)
@ConditionalOnBean(CacheInterceptor.class)
public Capability cachingCapability(CacheInterceptor cacheInterceptor) {
return new CachingCapability(cacheInterceptor);
}
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Module.class, Page.class, Sort.class }) @ConditionalOnClass({ Module.class, Page.class, Sort.class })
@ConditionalOnProperty(value = "feign.autoconfiguration.jackson.enabled", @ConditionalOnProperty(value = "spring.cloud.openfeign.autoconfiguration.jackson.enabled", havingValue = "true")
havingValue = "true")
protected static class FeignJacksonConfiguration { protected static class FeignJacksonConfiguration {
@Bean @Bean
@@ -121,7 +141,7 @@ public class FeignAutoConfiguration {
} }
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@Conditional(DefaultFeignTargeterConditions.class) @Conditional(FeignCircuitBreakerDisabledConditions.class)
protected static class DefaultFeignTargeterConfiguration { protected static class DefaultFeignTargeterConfiguration {
@Bean @Bean
@@ -133,44 +153,70 @@ public class FeignAutoConfiguration {
} }
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@Conditional(FeignCircuitBreakerDisabledConditions.class) @ConditionalOnClass(CircuitBreaker.class)
@ConditionalOnClass(name = "feign.hystrix.HystrixFeign") @ConditionalOnProperty(value = "spring.cloud.openfeign.circuitbreaker.enabled", havingValue = "true")
@ConditionalOnProperty(value = "feign.hystrix.enabled", havingValue = "true", protected static class CircuitBreakerPresentFeignTargeterConfiguration {
matchIfMissing = true)
protected static class HystrixFeignTargeterConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean(CircuitBreakerFactory.class)
public Targeter feignTargeter() { public Targeter defaultFeignTargeter() {
return new HystrixTargeter(); return new DefaultTargeter();
} }
@Bean
@ConditionalOnMissingBean(CircuitBreakerNameResolver.class)
@ConditionalOnProperty(value = "spring.cloud.openfeign.circuitbreaker.alphanumeric-ids.enabled",
havingValue = "false")
public CircuitBreakerNameResolver circuitBreakerNameResolver() {
return new DefaultCircuitBreakerNameResolver();
} }
@Configuration(proxyBeanMethods = false) @Bean
@ConditionalOnClass(CircuitBreaker.class) @ConditionalOnMissingBean(CircuitBreakerNameResolver.class)
@ConditionalOnProperty(value = "feign.circuitbreaker.enabled", havingValue = "true") @ConditionalOnProperty(value = "spring.cloud.openfeign.circuitbreaker.alphanumeric-ids.enabled",
protected static class CircuitBreakerPresentFeignTargeterConfiguration { havingValue = "true", matchIfMissing = true)
public CircuitBreakerNameResolver alphanumericCircuitBreakerNameResolver() {
return new AlphanumericCircuitBreakerNameResolver();
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnBean(CircuitBreakerFactory.class) @ConditionalOnBean(CircuitBreakerFactory.class)
public Targeter circuitBreakerFeignTargeter( public Targeter circuitBreakerFeignTargeter(CircuitBreakerFactory circuitBreakerFactory,
CircuitBreakerFactory circuitBreakerFactory) { @Value("${spring.cloud.openfeign.circuitbreaker.group.enabled:false}") boolean circuitBreakerGroupEnabled,
return new FeignCircuitBreakerTargeter(circuitBreakerFactory); CircuitBreakerNameResolver circuitBreakerNameResolver) {
return new FeignCircuitBreakerTargeter(circuitBreakerFactory, circuitBreakerGroupEnabled,
circuitBreakerNameResolver);
}
static class DefaultCircuitBreakerNameResolver implements CircuitBreakerNameResolver {
@Override
public String resolveCircuitBreakerName(String feignClientName, Target<?> target, Method method) {
return Feign.configKey(target.type(), method);
}
}
static class AlphanumericCircuitBreakerNameResolver extends DefaultCircuitBreakerNameResolver {
@Override
public String resolveCircuitBreakerName(String feignClientName, Target<?> target, Method method) {
return super.resolveCircuitBreakerName(feignClientName, target, method).replaceAll("[^a-zA-Z0-9]", "");
}
} }
} }
// the following configuration is for alternate feign clients if // the following configuration is for alternate feign clients if
// ribbon is not on the class path. // SC loadbalancer is not on the class path.
// see corresponding configurations in FeignRibbonClientAutoConfiguration // see corresponding configurations in FeignLoadBalancerAutoConfiguration
// for load balanced ribbon clients. // for load-balanced clients.
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttpClient.class) @ConditionalOnClass(ApacheHttpClient.class)
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
@ConditionalOnMissingBean(CloseableHttpClient.class) @ConditionalOnMissingBean(CloseableHttpClient.class)
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true) @ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.enabled", matchIfMissing = true)
@Conditional(HttpClient5DisabledConditions.class) @Conditional(HttpClient5DisabledConditions.class)
protected static class HttpClientFeignConfiguration { protected static class HttpClientFeignConfiguration {
@@ -187,13 +233,10 @@ public class FeignAutoConfiguration {
public HttpClientConnectionManager connectionManager( public HttpClientConnectionManager connectionManager(
ApacheHttpClientConnectionManagerFactory connectionManagerFactory, ApacheHttpClientConnectionManagerFactory connectionManagerFactory,
FeignHttpClientProperties httpClientProperties) { FeignHttpClientProperties httpClientProperties) {
final HttpClientConnectionManager connectionManager = connectionManagerFactory final HttpClientConnectionManager connectionManager = connectionManagerFactory.newConnectionManager(
.newConnectionManager(httpClientProperties.isDisableSslValidation(), httpClientProperties.isDisableSslValidation(), httpClientProperties.getMaxConnections(),
httpClientProperties.getMaxConnections(), httpClientProperties.getMaxConnectionsPerRoute(), httpClientProperties.getTimeToLive(),
httpClientProperties.getMaxConnectionsPerRoute(), httpClientProperties.getTimeToLiveUnit(), this.registryBuilder);
httpClientProperties.getTimeToLive(),
httpClientProperties.getTimeToLiveUnit(),
this.registryBuilder);
this.connectionManagerTimer.schedule(new TimerTask() { this.connectionManagerTimer.schedule(new TimerTask() {
@Override @Override
public void run() { public void run() {
@@ -209,10 +252,8 @@ public class FeignAutoConfiguration {
FeignHttpClientProperties httpClientProperties) { FeignHttpClientProperties httpClientProperties) {
RequestConfig defaultRequestConfig = RequestConfig.custom() RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(httpClientProperties.getConnectionTimeout()) .setConnectTimeout(httpClientProperties.getConnectionTimeout())
.setRedirectsEnabled(httpClientProperties.isFollowRedirects()) .setRedirectsEnabled(httpClientProperties.isFollowRedirects()).build();
.build(); this.httpClient = httpClientFactory.createBuilder().setConnectionManager(httpClientConnectionManager)
this.httpClient = httpClientFactory.createBuilder()
.setConnectionManager(httpClientConnectionManager)
.setDefaultRequestConfig(defaultRequestConfig).build(); .setDefaultRequestConfig(defaultRequestConfig).build();
return this.httpClient; return this.httpClient;
} }
@@ -242,35 +283,32 @@ public class FeignAutoConfiguration {
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OkHttpClient.class) @ConditionalOnClass(OkHttpClient.class)
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
@ConditionalOnMissingBean(okhttp3.OkHttpClient.class) @ConditionalOnMissingBean(okhttp3.OkHttpClient.class)
@ConditionalOnProperty("feign.okhttp.enabled") @ConditionalOnProperty("spring.cloud.openfeign.okhttp.enabled")
protected static class OkHttpFeignConfiguration { protected static class OkHttpFeignConfiguration {
private okhttp3.OkHttpClient okHttpClient; private okhttp3.OkHttpClient okHttpClient;
@Bean @Bean
@ConditionalOnMissingBean(ConnectionPool.class) @ConditionalOnMissingBean(ConnectionPool.class)
public ConnectionPool httpClientConnectionPool( public ConnectionPool httpClientConnectionPool(FeignHttpClientProperties httpClientProperties,
FeignHttpClientProperties httpClientProperties,
OkHttpClientConnectionPoolFactory connectionPoolFactory) { OkHttpClientConnectionPoolFactory connectionPoolFactory) {
Integer maxTotalConnections = httpClientProperties.getMaxConnections(); int maxTotalConnections = httpClientProperties.getMaxConnections();
Long timeToLive = httpClientProperties.getTimeToLive(); long timeToLive = httpClientProperties.getTimeToLive();
TimeUnit ttlUnit = httpClientProperties.getTimeToLiveUnit(); TimeUnit ttlUnit = httpClientProperties.getTimeToLiveUnit();
return connectionPoolFactory.create(maxTotalConnections, timeToLive, ttlUnit); return connectionPoolFactory.create(maxTotalConnections, timeToLive, ttlUnit);
} }
@Bean @Bean
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, ConnectionPool connectionPool,
ConnectionPool connectionPool,
FeignHttpClientProperties httpClientProperties) { FeignHttpClientProperties httpClientProperties) {
Boolean followRedirects = httpClientProperties.isFollowRedirects(); boolean followRedirects = httpClientProperties.isFollowRedirects();
Integer connectTimeout = httpClientProperties.getConnectionTimeout(); int connectTimeout = httpClientProperties.getConnectionTimeout();
Boolean disableSslValidation = httpClientProperties.isDisableSslValidation(); boolean disableSslValidation = httpClientProperties.isDisableSslValidation();
Duration readTimeout = httpClientProperties.getOkHttp().getReadTimeout();
this.okHttpClient = httpClientFactory.createBuilder(disableSslValidation) this.okHttpClient = httpClientFactory.createBuilder(disableSslValidation)
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS) .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects)
.followRedirects(followRedirects).connectionPool(connectionPool) .readTimeout(readTimeout).connectionPool(connectionPool).build();
.build();
return this.okHttpClient; return this.okHttpClient;
} }
@@ -292,35 +330,49 @@ public class FeignAutoConfiguration {
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttp5Client.class) @ConditionalOnClass(ApacheHttp5Client.class)
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
@ConditionalOnMissingBean(org.apache.hc.client5.http.impl.classic.CloseableHttpClient.class) @ConditionalOnMissingBean(org.apache.hc.client5.http.impl.classic.CloseableHttpClient.class)
@ConditionalOnProperty(value = "feign.httpclient.hc5.enabled", havingValue = "true") @ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.hc5.enabled", havingValue = "true")
@Import(org.springframework.cloud.openfeign.clientconfig.HttpClient5FeignConfiguration.class) @Import(org.springframework.cloud.openfeign.clientconfig.HttpClient5FeignConfiguration.class)
protected static class HttpClient5FeignConfiguration { protected static class HttpClient5FeignConfiguration {
@Bean @Bean
@ConditionalOnMissingBean(Client.class) @ConditionalOnMissingBean(Client.class)
public Client feignClient( public Client feignClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient httpClient5) {
org.apache.hc.client5.http.impl.classic.CloseableHttpClient httpClient5) {
return new ApacheHttp5Client(httpClient5); return new ApacheHttp5Client(httpClient5);
} }
} }
static class DefaultFeignTargeterConditions extends AllNestedConditions { @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OAuth2ClientContext.class)
@ConditionalOnProperty("spring.cloud.openfeign.oauth2.enabled")
@Deprecated // spring-security-oauth2 reached EOL
protected static class Oauth2FeignConfiguration {
DefaultFeignTargeterConditions() { @ConditionalOnBean({ RetryLoadBalancerInterceptor.class, OAuth2ClientContext.class,
super(ConfigurationPhase.PARSE_CONFIGURATION); OAuth2ProtectedResourceDetails.class })
@ConditionalOnProperty(value = "spring.cloud.openfeign.oauth2.load-balanced", havingValue = "true")
@Bean
public OAuth2FeignRequestInterceptorConfigurer retryLoadBalancerInterceptorInjectingConfigurer(
final RetryLoadBalancerInterceptor loadBalancerInterceptor) {
return builder -> builder.withAccessTokenProviderInterceptors(loadBalancerInterceptor);
} }
@Conditional(FeignCircuitBreakerDisabledConditions.class) @ConditionalOnBean({ LoadBalancerInterceptor.class, OAuth2ClientContext.class,
static class FeignCircuitBreakerDisabled { OAuth2ProtectedResourceDetails.class })
@ConditionalOnProperty(value = "spring.cloud.openfeign.oauth2.load-balanced", havingValue = "true")
@Bean
public OAuth2FeignRequestInterceptorConfigurer loadBalancerInterceptorInjectingConfigurer(
final LoadBalancerInterceptor loadBalancerInterceptor) {
return builder -> builder.withAccessTokenProviderInterceptors(loadBalancerInterceptor);
} }
@Conditional(HystrixDisabledConditions.class) @Bean
static class HystrixDisabled { @ConditionalOnMissingBean(OAuth2FeignRequestInterceptor.class)
@ConditionalOnBean({ OAuth2ClientContext.class, OAuth2ProtectedResourceDetails.class })
public RequestInterceptor oauth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext,
OAuth2ProtectedResourceDetails resource, List<OAuth2FeignRequestInterceptorConfigurer> configurers) {
return buildWithConfigurers(oAuth2ClientContext, resource, configurers);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2019 the original author or authors. * Copyright 2013-2022 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.
@@ -0,0 +1,82 @@
/*
* Copyright 2013-2022 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.AccessibleObject;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Optional;
import feign.InvocationHandlerFactory;
import feign.Target;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.cache.interceptor.CacheInterceptor;
/**
* Allows Spring's @Cache* annotations to be declared on the feign client's methods.
*
* @author Sam Kruglov
*/
public class FeignCachingInvocationHandlerFactory implements InvocationHandlerFactory {
private final InvocationHandlerFactory delegateFactory;
private final CacheInterceptor cacheInterceptor;
public FeignCachingInvocationHandlerFactory(InvocationHandlerFactory delegateFactory,
CacheInterceptor cacheInterceptor) {
this.delegateFactory = delegateFactory;
this.cacheInterceptor = cacheInterceptor;
}
@Override
public InvocationHandler create(Target target, Map<Method, MethodHandler> dispatch) {
final InvocationHandler delegateHandler = delegateFactory.create(target, dispatch);
return (proxy, method, argsNullable) -> {
Object[] args = Optional.ofNullable(argsNullable).orElseGet(() -> new Object[0]);
return cacheInterceptor.invoke(new MethodInvocation() {
@Override
public Method getMethod() {
return method;
}
@Override
public Object[] getArguments() {
return args;
}
@Override
public Object proceed() throws Throwable {
return delegateHandler.invoke(proxy, method, args);
}
@Override
public Object getThis() {
return target;
}
@Override
public AccessibleObject getStaticPart() {
return method;
}
});
};
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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,6 +26,8 @@ import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
* Allows Feign interfaces to work with {@link CircuitBreaker}. * Allows Feign interfaces to work with {@link CircuitBreaker}.
* *
* @author Marcin Grzejszczak * @author Marcin Grzejszczak
* @author Andrii Bohutskyi
* @author Kwangyong Kim
* @since 3.0.0 * @since 3.0.0
*/ */
public final class FeignCircuitBreaker { public final class FeignCircuitBreaker {
@@ -50,6 +52,10 @@ public final class FeignCircuitBreaker {
private String feignClientName; private String feignClientName;
private boolean circuitBreakerGroupEnabled;
private CircuitBreakerNameResolver circuitBreakerNameResolver;
Builder circuitBreakerFactory(CircuitBreakerFactory circuitBreakerFactory) { Builder circuitBreakerFactory(CircuitBreakerFactory circuitBreakerFactory) {
this.circuitBreakerFactory = circuitBreakerFactory; this.circuitBreakerFactory = circuitBreakerFactory;
return this; return this;
@@ -60,14 +66,21 @@ public final class FeignCircuitBreaker {
return this; return this;
} }
public <T> T target(Target<T> target, T fallback) { Builder circuitBreakerGroupEnabled(boolean circuitBreakerGroupEnabled) {
return build( this.circuitBreakerGroupEnabled = circuitBreakerGroupEnabled;
fallback != null ? new FallbackFactory.Default<T>(fallback) : null) return this;
.newInstance(target);
} }
public <T> T target(Target<T> target, Builder circuitBreakerNameResolver(CircuitBreakerNameResolver circuitBreakerNameResolver) {
FallbackFactory<? extends T> fallbackFactory) { this.circuitBreakerNameResolver = circuitBreakerNameResolver;
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); return build(fallbackFactory).newInstance(target);
} }
@@ -77,10 +90,9 @@ public final class FeignCircuitBreaker {
} }
public Feign build(final FallbackFactory<?> nullableFallbackFactory) { public Feign build(final FallbackFactory<?> nullableFallbackFactory) {
super.invocationHandlerFactory( super.invocationHandlerFactory((target, dispatch) -> new FeignCircuitBreakerInvocationHandler(
(target, dispatch) -> new FeignCircuitBreakerInvocationHandler( circuitBreakerFactory, feignClientName, target, dispatch, nullableFallbackFactory,
circuitBreakerFactory, target, dispatch, circuitBreakerGroupEnabled, circuitBreakerNameResolver));
nullableFallbackFactory));
return super.build(); return super.build();
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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,7 +31,7 @@ class FeignCircuitBreakerDisabledConditions extends AnyNestedCondition {
} }
@ConditionalOnProperty(value = "feign.circuitbreaker.enabled", havingValue = "false", @ConditionalOnProperty(value = "spring.cloud.openfeign.circuitbreaker.enabled", havingValue = "false",
matchIfMissing = true) matchIfMissing = true)
static class CircuitBreakerDisabled { static class CircuitBreakerDisabled {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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; package org.springframework.cloud.openfeign;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Proxy; import java.lang.reflect.Proxy;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@@ -24,12 +25,14 @@ import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Supplier; import java.util.function.Supplier;
import feign.Feign;
import feign.InvocationHandlerFactory; import feign.InvocationHandlerFactory;
import feign.Target; import feign.Target;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker; import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory; import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.NoFallbackAvailableException;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import static feign.Util.checkNotNull; import static feign.Util.checkNotNull;
@@ -37,6 +40,8 @@ class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
private final CircuitBreakerFactory factory; private final CircuitBreakerFactory factory;
private final String feignClientName;
private final Target<?> target; private final Target<?> target;
private final Map<Method, InvocationHandlerFactory.MethodHandler> dispatch; private final Map<Method, InvocationHandlerFactory.MethodHandler> dispatch;
@@ -45,25 +50,30 @@ class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
private final Map<Method, Method> fallbackMethodMap; private final Map<Method, Method> fallbackMethodMap;
FeignCircuitBreakerInvocationHandler(CircuitBreakerFactory factory, Target<?> target, private final boolean circuitBreakerGroupEnabled;
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch,
FallbackFactory<?> nullableFallbackFactory) { private final CircuitBreakerNameResolver circuitBreakerNameResolver;
FeignCircuitBreakerInvocationHandler(CircuitBreakerFactory factory, String feignClientName, Target<?> target,
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch, FallbackFactory<?> nullableFallbackFactory,
boolean circuitBreakerGroupEnabled, CircuitBreakerNameResolver circuitBreakerNameResolver) {
this.factory = factory; this.factory = factory;
this.feignClientName = feignClientName;
this.target = checkNotNull(target, "target"); this.target = checkNotNull(target, "target");
this.dispatch = checkNotNull(dispatch, "dispatch"); this.dispatch = checkNotNull(dispatch, "dispatch");
this.fallbackMethodMap = toFallbackMethod(dispatch); this.fallbackMethodMap = toFallbackMethod(dispatch);
this.nullableFallbackFactory = nullableFallbackFactory; this.nullableFallbackFactory = nullableFallbackFactory;
this.circuitBreakerGroupEnabled = circuitBreakerGroupEnabled;
this.circuitBreakerNameResolver = circuitBreakerNameResolver;
} }
@Override @Override
public Object invoke(final Object proxy, final Method method, final Object[] args) public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
throws Throwable {
// early exit if the invoked method is from java.lang.Object // early exit if the invoked method is from java.lang.Object
// code is the same as ReflectiveFeign.FeignInvocationHandler // code is the same as ReflectiveFeign.FeignInvocationHandler
if ("equals".equals(method.getName())) { if ("equals".equals(method.getName())) {
try { try {
Object otherHandler = args.length > 0 && args[0] != null Object otherHandler = args.length > 0 && args[0] != null ? Proxy.getInvocationHandler(args[0]) : null;
? Proxy.getInvocationHandler(args[0]) : null;
return equals(otherHandler); return equals(otherHandler);
} }
catch (IllegalArgumentException e) { catch (IllegalArgumentException e) {
@@ -76,8 +86,10 @@ class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
else if ("toString".equals(method.getName())) { else if ("toString".equals(method.getName())) {
return toString(); return toString();
} }
String circuitName = Feign.configKey(target.type(), method);
CircuitBreaker circuitBreaker = this.factory.create(circuitName); String circuitName = circuitBreakerNameResolver.resolveCircuitBreakerName(feignClientName, target, method);
CircuitBreaker circuitBreaker = circuitBreakerGroupEnabled ? factory.create(circuitName, feignClientName)
: factory.create(circuitName);
Supplier<Object> supplier = asSupplier(method, args); Supplier<Object> supplier = asSupplier(method, args);
if (this.nullableFallbackFactory != null) { if (this.nullableFallbackFactory != null) {
Function<Throwable, Object> fallbackFunction = throwable -> { Function<Throwable, Object> fallbackFunction = throwable -> {
@@ -85,19 +97,35 @@ class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
try { try {
return this.fallbackMethodMap.get(method).invoke(fallback, args); return this.fallbackMethodMap.get(method).invoke(fallback, args);
} }
catch (Exception e) { catch (Exception exception) {
throw new IllegalStateException(e); unwrapAndRethrow(exception);
} }
return null;
}; };
return circuitBreaker.run(supplier, fallbackFunction); return circuitBreaker.run(supplier, fallbackFunction);
} }
return circuitBreaker.run(supplier); return circuitBreaker.run(supplier);
} }
private void unwrapAndRethrow(Exception exception) {
if (exception instanceof InvocationTargetException || exception instanceof NoFallbackAvailableException) {
Throwable underlyingException = exception.getCause();
if (underlyingException instanceof RuntimeException) {
throw (RuntimeException) underlyingException;
}
if (underlyingException != null) {
throw new IllegalStateException(underlyingException);
}
throw new IllegalStateException(exception);
}
}
private Supplier<Object> asSupplier(final Method method, final Object[] args) { private Supplier<Object> asSupplier(final Method method, final Object[] args) {
final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return () -> { return () -> {
try { try {
return this.dispatch.get(method).invoke(args); RequestContextHolder.setRequestAttributes(requestAttributes);
return dispatch.get(method).invoke(args);
} }
catch (RuntimeException throwable) { catch (RuntimeException throwable) {
throw throwable; throw throwable;
@@ -117,8 +145,7 @@ class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
* reflection calls. * reflection calls.
* @return cached methods map for fallback invoking * @return cached methods map for fallback invoking
*/ */
static Map<Method, Method> toFallbackMethod( static Map<Method, Method> toFallbackMethod(Map<Method, InvocationHandlerFactory.MethodHandler> dispatch) {
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch) {
Map<Method, Method> result = new LinkedHashMap<Method, Method>(); Map<Method, Method> result = new LinkedHashMap<Method, Method>();
for (Method method : dispatch.keySet()) { for (Method method : dispatch.keySet()) {
method.setAccessible(true); method.setAccessible(true);
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -27,71 +27,70 @@ class FeignCircuitBreakerTargeter implements Targeter {
private final CircuitBreakerFactory circuitBreakerFactory; private final CircuitBreakerFactory circuitBreakerFactory;
FeignCircuitBreakerTargeter(CircuitBreakerFactory circuitBreakerFactory) { private final boolean circuitBreakerGroupEnabled;
private final CircuitBreakerNameResolver circuitBreakerNameResolver;
FeignCircuitBreakerTargeter(CircuitBreakerFactory circuitBreakerFactory, boolean circuitBreakerGroupEnabled,
CircuitBreakerNameResolver circuitBreakerNameResolver) {
this.circuitBreakerFactory = circuitBreakerFactory; this.circuitBreakerFactory = circuitBreakerFactory;
this.circuitBreakerGroupEnabled = circuitBreakerGroupEnabled;
this.circuitBreakerNameResolver = circuitBreakerNameResolver;
} }
@Override @Override
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context,
FeignContext context, Target.HardCodedTarget<T> target) { Target.HardCodedTarget<T> target) {
if (!(feign instanceof FeignCircuitBreaker.Builder)) { if (!(feign instanceof FeignCircuitBreaker.Builder)) {
return feign.target(target); return feign.target(target);
} }
FeignCircuitBreaker.Builder builder = (FeignCircuitBreaker.Builder) feign; FeignCircuitBreaker.Builder builder = (FeignCircuitBreaker.Builder) feign;
String name = !StringUtils.hasText(factory.getContextId()) ? factory.getName() String name = !StringUtils.hasText(factory.getContextId()) ? factory.getName() : factory.getContextId();
: factory.getContextId();
Class<?> fallback = factory.getFallback(); Class<?> fallback = factory.getFallback();
if (fallback != void.class) { if (fallback != void.class) {
return targetWithFallback(name, context, target, builder, fallback); return targetWithFallback(name, context, target, builder, fallback);
} }
Class<?> fallbackFactory = factory.getFallbackFactory(); Class<?> fallbackFactory = factory.getFallbackFactory();
if (fallbackFactory != void.class) { if (fallbackFactory != void.class) {
return targetWithFallbackFactory(name, context, target, builder, return targetWithFallbackFactory(name, context, target, builder, fallbackFactory);
fallbackFactory);
} }
return builder(name, builder).target(target); return builder(name, builder).target(target);
} }
private <T> T targetWithFallbackFactory(String feignClientName, FeignContext context, private <T> T targetWithFallbackFactory(String feignClientName, FeignContext context,
Target.HardCodedTarget<T> target, FeignCircuitBreaker.Builder builder, Target.HardCodedTarget<T> target, FeignCircuitBreaker.Builder builder, Class<?> fallbackFactoryClass) {
Class<?> fallbackFactoryClass) { FallbackFactory<? extends T> fallbackFactory = (FallbackFactory<? extends T>) getFromContext("fallbackFactory",
FallbackFactory<? extends T> fallbackFactory = (FallbackFactory<? extends T>) getFromContext( feignClientName, context, fallbackFactoryClass, FallbackFactory.class);
"fallbackFactory", feignClientName, context, fallbackFactoryClass,
FallbackFactory.class);
return builder(feignClientName, builder).target(target, fallbackFactory); return builder(feignClientName, builder).target(target, fallbackFactory);
} }
private <T> T targetWithFallback(String feignClientName, FeignContext context, private <T> T targetWithFallback(String feignClientName, FeignContext context, Target.HardCodedTarget<T> target,
Target.HardCodedTarget<T> target, FeignCircuitBreaker.Builder builder, FeignCircuitBreaker.Builder builder, Class<?> fallback) {
Class<?> fallback) { T fallbackInstance = getFromContext("fallback", feignClientName, context, fallback, target.type());
T fallbackInstance = getFromContext("fallback", feignClientName, context,
fallback, target.type());
return builder(feignClientName, builder).target(target, fallbackInstance); return builder(feignClientName, builder).target(target, fallbackInstance);
} }
private <T> T getFromContext(String fallbackMechanism, String feignClientName, private <T> T getFromContext(String fallbackMechanism, String feignClientName, FeignContext context,
FeignContext context, Class<?> beanType, Class<T> targetType) { Class<?> beanType, Class<T> targetType) {
Object fallbackInstance = context.getInstance(feignClientName, beanType); Object fallbackInstance = context.getInstance(feignClientName, beanType);
if (fallbackInstance == null) { if (fallbackInstance == null) {
throw new IllegalStateException(String.format( throw new IllegalStateException(
"No " + fallbackMechanism String.format("No " + fallbackMechanism + " instance of type %s found for feign client %s",
+ " instance of type %s found for feign client %s",
beanType, feignClientName)); beanType, feignClientName));
} }
if (!targetType.isAssignableFrom(beanType)) { if (!targetType.isAssignableFrom(beanType)) {
throw new IllegalStateException(String.format("Incompatible " throw new IllegalStateException(String.format("Incompatible " + fallbackMechanism
+ fallbackMechanism
+ " instance. Fallback/fallbackFactory of type %s is not assignable to %s for feign client %s", + " instance. Fallback/fallbackFactory of type %s is not assignable to %s for feign client %s",
beanType, targetType, feignClientName)); beanType, targetType, feignClientName));
} }
return (T) fallbackInstance; return (T) fallbackInstance;
} }
private FeignCircuitBreaker.Builder builder(String feignClientName, private FeignCircuitBreaker.Builder builder(String feignClientName, FeignCircuitBreaker.Builder builder) {
FeignCircuitBreaker.Builder builder) { return builder.circuitBreakerFactory(circuitBreakerFactory).feignClientName(feignClientName)
return builder.circuitBreakerFactory(this.circuitBreakerFactory) .circuitBreakerGroupEnabled(circuitBreakerGroupEnabled)
.feignClientName(feignClientName); .circuitBreakerNameResolver(circuitBreakerNameResolver);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 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.
@@ -27,9 +27,9 @@ import org.springframework.core.annotation.AliasFor;
/** /**
* Annotation for interfaces declaring that a REST client with that interface should be * Annotation for interfaces declaring that a REST client with that interface should be
* created (e.g. for autowiring into another component). If ribbon is available it will be * created (e.g. for autowiring into another component). If SC LoadBalancer is available
* used to load balance the backend requests, and the load balancer can be configured * it will be used to load balance the backend requests, and the load balancer can be
* using a <code>@RibbonClient</code> with the same name (i.e. value) as the feign client. * configured using the same name (i.e. value) as the feign client.
* *
* @author Spencer Gibb * @author Spencer Gibb
* @author Venil Noronha * @author Venil Noronha
@@ -50,14 +50,6 @@ public @interface FeignClient {
@AliasFor("name") @AliasFor("name")
String value() default ""; String value() default "";
/**
* The service id with optional protocol prefix. Synonym for {@link #value() value}.
* @deprecated use {@link #name() name} instead
* @return the service id with optional protocol prefix
*/
@Deprecated
String serviceId() default "";
/** /**
* This will be used as the bean name instead of name if present, but will not be used * This will be used as the bean name instead of name if present, but will not be used
* as a service id. * as a service id.
@@ -128,15 +120,13 @@ public @interface FeignClient {
* factory must produce instances of fallback classes that implement the interface * factory must produce instances of fallback classes that implement the interface
* 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 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;
/** /**
* @return path prefix to be used by all method-level mappings. Can be used with or * @return path prefix to be used by all method-level mappings.
* without <code>@RibbonClient</code>.
*/ */
String path() default ""; String path() default "";
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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,7 +17,6 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import feign.Feign; import feign.Feign;
import feign.hystrix.FallbackFactory;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
@@ -43,6 +42,11 @@ public class FeignClientBuilder {
return new Builder<>(this.applicationContext, type, name); return new Builder<>(this.applicationContext, type, name);
} }
public <T> Builder<T> forType(final Class<T> type, final FeignClientFactoryBean clientFactoryBean,
final String name) {
return new Builder<>(this.applicationContext, clientFactoryBean, type, name);
}
/** /**
* Builder of feign targets. * Builder of feign targets.
* *
@@ -52,9 +56,13 @@ public class FeignClientBuilder {
private FeignClientFactoryBean feignClientFactoryBean; private FeignClientFactoryBean feignClientFactoryBean;
private Builder(final ApplicationContext applicationContext, final Class<T> type, private Builder(final ApplicationContext applicationContext, final Class<T> type, final String name) {
final String name) { this(applicationContext, new FeignClientFactoryBean(), type, name);
this.feignClientFactoryBean = new FeignClientFactoryBean(); }
private Builder(final ApplicationContext applicationContext, final FeignClientFactoryBean clientFactoryBean,
final Class<T> type, final String name) {
this.feignClientFactoryBean = clientFactoryBean;
this.feignClientFactoryBean.setApplicationContext(applicationContext); this.feignClientFactoryBean.setApplicationContext(applicationContext);
this.feignClientFactoryBean.setType(type); this.feignClientFactoryBean.setType(type);
@@ -109,13 +117,6 @@ public class FeignClientBuilder {
return this; return this;
} }
public Builder<T> fallbackFactory(
final Class<? extends FallbackFactory<? extends T>> fallbackFactory) {
FeignClientsRegistrar.validateFallbackFactory(fallbackFactory);
this.feignClientFactoryBean.setFallbackFactory(fallbackFactory);
return this;
}
/** /**
* @return the created Feign client * @return the created Feign client
*/ */
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 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,11 +17,13 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.List; 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;
import feign.Capability;
import feign.Client; import feign.Client;
import feign.Contract; import feign.Contract;
import feign.ExceptionPropagationPolicy; import feign.ExceptionPropagationPolicy;
@@ -48,7 +50,6 @@ 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.loadbalancer.RetryableFeignBlockingLoadBalancerClient;
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.core.annotation.AnnotationAwareOrderComparator;
@@ -64,10 +65,14 @@ import org.springframework.util.StringUtils;
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Ilia Ilinykh * @author Ilia Ilinykh
* @author Marcin Grzejszczak * @author Marcin Grzejszczak
* @author Jonatan Ivanov
* @author Sam Kruglov * @author Sam Kruglov
* @author Jasbir Singh
* @author Hyeonmin Park
* @author Felix Dittrich
*/ */
public class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean, public class FeignClientFactoryBean
ApplicationContextAware, BeanFactoryAware { implements FactoryBean<Object>, InitializingBean, 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
@@ -104,7 +109,9 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
private boolean followRedirects = new Request.Options().isFollowRedirects(); private boolean followRedirects = new Request.Options().isFollowRedirects();
private List<FeignBuilderCustomizer> additionalCustomizers = new ArrayList<>(); private boolean refreshableClient = false;
private final List<FeignBuilderCustomizer> additionalCustomizers = new ArrayList<>();
@Override @Override
public void afterPropertiesSet() { public void afterPropertiesSet() {
@@ -126,45 +133,36 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
// @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) { private void applyBuildCustomizers(FeignContext context, Feign.Builder builder) {
Map<String, FeignBuilderCustomizer> customizerMap = context Map<String, FeignBuilderCustomizer> customizerMap = context.getInstances(contextId,
.getInstances(contextId, FeignBuilderCustomizer.class); FeignBuilderCustomizer.class);
if (customizerMap != null) { if (customizerMap != null) {
customizerMap.values().stream() customizerMap.values().stream().sorted(AnnotationAwareOrderComparator.INSTANCE)
.sorted(AnnotationAwareOrderComparator.INSTANCE) .forEach(feignBuilderCustomizer -> feignBuilderCustomizer.customize(builder));
.forEach(feignBuilderCustomizer -> feignBuilderCustomizer
.customize(builder));
} }
additionalCustomizers.forEach(customizer -> customizer.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 = beanFactory != null FeignClientProperties properties = beanFactory != null ? beanFactory.getBean(FeignClientProperties.class)
? beanFactory.getBean(FeignClientProperties.class)
: applicationContext.getBean(FeignClientProperties.class); : applicationContext.getBean(FeignClientProperties.class);
FeignClientConfigurer feignClientConfigurer = getOptional(context, FeignClientConfigurer feignClientConfigurer = getOptional(context, FeignClientConfigurer.class);
FeignClientConfigurer.class);
setInheritParentContext(feignClientConfigurer.inheritParentConfiguration()); setInheritParentContext(feignClientConfigurer.inheritParentConfiguration());
if (properties != null && inheritParentContext) { if (properties != null && inheritParentContext) {
if (properties.isDefaultToProperties()) { if (properties.isDefaultToProperties()) {
configureUsingConfiguration(context, builder); configureUsingConfiguration(context, builder);
configureUsingProperties( configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder);
properties.getConfig().get(properties.getDefaultConfig()),
builder);
configureUsingProperties(properties.getConfig().get(contextId), builder); configureUsingProperties(properties.getConfig().get(contextId), builder);
} }
else { else {
configureUsingProperties( configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder);
properties.getConfig().get(properties.getDefaultConfig()),
builder);
configureUsingProperties(properties.getConfig().get(contextId), builder); configureUsingProperties(properties.getConfig().get(contextId), builder);
configureUsingConfiguration(context, builder); configureUsingConfiguration(context, builder);
} }
@@ -174,8 +172,7 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
} }
} }
protected void configureUsingConfiguration(FeignContext context, protected void configureUsingConfiguration(FeignContext context, Feign.Builder builder) {
Feign.Builder builder) {
Logger.Level level = getInheritedAwareOptional(context, Logger.Level.class); Logger.Level level = getInheritedAwareOptional(context, Logger.Level.class);
if (level != null) { if (level != null) {
builder.logLevel(level); builder.logLevel(level);
@@ -184,52 +181,56 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
if (retryer != null) { if (retryer != null) {
builder.retryer(retryer); builder.retryer(retryer);
} }
ErrorDecoder errorDecoder = getInheritedAwareOptional(context, ErrorDecoder errorDecoder = getInheritedAwareOptional(context, ErrorDecoder.class);
ErrorDecoder.class);
if (errorDecoder != null) { if (errorDecoder != null) {
builder.errorDecoder(errorDecoder); builder.errorDecoder(errorDecoder);
} }
else { else {
FeignErrorDecoderFactory errorDecoderFactory = getOptional(context, FeignErrorDecoderFactory errorDecoderFactory = getOptional(context, FeignErrorDecoderFactory.class);
FeignErrorDecoderFactory.class);
if (errorDecoderFactory != null) { if (errorDecoderFactory != null) {
ErrorDecoder factoryErrorDecoder = errorDecoderFactory.create(type); ErrorDecoder factoryErrorDecoder = errorDecoderFactory.create(type);
builder.errorDecoder(factoryErrorDecoder); builder.errorDecoder(factoryErrorDecoder);
} }
} }
Request.Options options = getInheritedAwareOptional(context, Request.Options options = getInheritedAwareOptional(context, Request.Options.class);
Request.Options.class); if (options == null) {
options = getOptionsByName(context, contextId);
}
if (options != null) { if (options != null) {
builder.options(options); builder.options(options);
readTimeoutMillis = options.readTimeoutMillis(); readTimeoutMillis = options.readTimeoutMillis();
connectTimeoutMillis = options.connectTimeoutMillis(); connectTimeoutMillis = options.connectTimeoutMillis();
followRedirects = options.isFollowRedirects(); followRedirects = options.isFollowRedirects();
} }
Map<String, RequestInterceptor> requestInterceptors = getInheritedAwareInstances( Map<String, RequestInterceptor> requestInterceptors = getInheritedAwareInstances(context,
context, RequestInterceptor.class); RequestInterceptor.class);
if (requestInterceptors != null) { if (requestInterceptors != null) {
List<RequestInterceptor> interceptors = new ArrayList<>( List<RequestInterceptor> interceptors = new ArrayList<>(requestInterceptors.values());
requestInterceptors.values());
AnnotationAwareOrderComparator.sort(interceptors); AnnotationAwareOrderComparator.sort(interceptors);
builder.requestInterceptors(interceptors); builder.requestInterceptors(interceptors);
} }
QueryMapEncoder queryMapEncoder = getInheritedAwareOptional(context, QueryMapEncoder queryMapEncoder = getInheritedAwareOptional(context, QueryMapEncoder.class);
QueryMapEncoder.class);
if (queryMapEncoder != null) { if (queryMapEncoder != null) {
builder.queryMapEncoder(queryMapEncoder); builder.queryMapEncoder(queryMapEncoder);
} }
if (decode404) { if (decode404) {
builder.decode404(); builder.decode404();
} }
ExceptionPropagationPolicy exceptionPropagationPolicy = getInheritedAwareOptional( ExceptionPropagationPolicy exceptionPropagationPolicy = getInheritedAwareOptional(context,
context, ExceptionPropagationPolicy.class); ExceptionPropagationPolicy.class);
if (exceptionPropagationPolicy != null) { if (exceptionPropagationPolicy != null) {
builder.exceptionPropagationPolicy(exceptionPropagationPolicy); builder.exceptionPropagationPolicy(exceptionPropagationPolicy);
} }
Map<String, Capability> capabilities = getInheritedAwareInstances(context, Capability.class);
if (capabilities != null) {
capabilities.values().stream().sorted(AnnotationAwareOrderComparator.INSTANCE)
.forEach(builder::addCapability);
}
} }
protected void configureUsingProperties( protected void configureUsingProperties(FeignClientProperties.FeignClientConfiguration config,
FeignClientProperties.FeignClientConfiguration config,
Feign.Builder builder) { Feign.Builder builder) {
if (config == null) { if (config == null) {
return; return;
@@ -239,15 +240,15 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
builder.logLevel(config.getLoggerLevel()); builder.logLevel(config.getLoggerLevel());
} }
connectTimeoutMillis = config.getConnectTimeout() != null if (!refreshableClient) {
? config.getConnectTimeout() : connectTimeoutMillis; connectTimeoutMillis = config.getConnectTimeout() != null ? config.getConnectTimeout()
readTimeoutMillis = config.getReadTimeout() != null ? config.getReadTimeout() : connectTimeoutMillis;
: readTimeoutMillis; readTimeoutMillis = config.getReadTimeout() != null ? config.getReadTimeout() : readTimeoutMillis;
followRedirects = config.isFollowRedirects() != null ? config.isFollowRedirects() followRedirects = config.isFollowRedirects() != null ? config.isFollowRedirects() : followRedirects;
: followRedirects;
builder.options(new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS, builder.options(new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS, readTimeoutMillis,
readTimeoutMillis, TimeUnit.MILLISECONDS, followRedirects)); TimeUnit.MILLISECONDS, followRedirects));
}
if (config.getRetryer() != null) { if (config.getRetryer() != null) {
Retryer retryer = getOrInstantiate(config.getRetryer()); Retryer retryer = getOrInstantiate(config.getRetryer());
@@ -259,8 +260,7 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
builder.errorDecoder(errorDecoder); builder.errorDecoder(errorDecoder);
} }
if (config.getRequestInterceptors() != null if (config.getRequestInterceptors() != null && !config.getRequestInterceptors().isEmpty()) {
&& !config.getRequestInterceptors().isEmpty()) {
// this will add request interceptor to builder, not replace existing // this will add request interceptor to builder, not replace existing
for (Class<RequestInterceptor> bean : config.getRequestInterceptors()) { for (Class<RequestInterceptor> bean : config.getRequestInterceptors()) {
RequestInterceptor interceptor = getOrInstantiate(bean); RequestInterceptor interceptor = getOrInstantiate(bean);
@@ -278,15 +278,8 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
builder.encoder(getOrInstantiate(config.getEncoder())); builder.encoder(getOrInstantiate(config.getEncoder()));
} }
if (Objects.nonNull(config.getDefaultRequestHeaders())) { addDefaultRequestHeaders(config, builder);
builder.requestInterceptor(requestTemplate -> requestTemplate addDefaultQueryParams(config, builder);
.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()));
@@ -299,12 +292,48 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
if (Objects.nonNull(config.getExceptionPropagationPolicy())) { if (Objects.nonNull(config.getExceptionPropagationPolicy())) {
builder.exceptionPropagationPolicy(config.getExceptionPropagationPolicy()); builder.exceptionPropagationPolicy(config.getExceptionPropagationPolicy());
} }
if (config.getCapabilities() != null) {
config.getCapabilities().stream().map(this::getOrInstantiate).forEach(builder::addCapability);
}
if (config.getQueryMapEncoder() != null) {
builder.queryMapEncoder(getOrInstantiate(config.getQueryMapEncoder()));
}
}
private void addDefaultQueryParams(FeignClientProperties.FeignClientConfiguration config, Feign.Builder builder) {
Map<String, Collection<String>> defaultQueryParameters = config.getDefaultQueryParameters();
if (Objects.nonNull(defaultQueryParameters)) {
builder.requestInterceptor(requestTemplate -> {
Map<String, Collection<String>> queries = requestTemplate.queries();
defaultQueryParameters.keySet().forEach(key -> {
if (!queries.containsKey(key)) {
requestTemplate.query(key, defaultQueryParameters.get(key));
}
});
});
}
}
private void addDefaultRequestHeaders(FeignClientProperties.FeignClientConfiguration config,
Feign.Builder builder) {
Map<String, Collection<String>> defaultRequestHeaders = config.getDefaultRequestHeaders();
if (Objects.nonNull(defaultRequestHeaders)) {
builder.requestInterceptor(requestTemplate -> {
Map<String, Collection<String>> headers = requestTemplate.headers();
defaultRequestHeaders.keySet().forEach(key -> {
if (!headers.containsKey(key)) {
requestTemplate.header(key, defaultRequestHeaders.get(key));
}
});
});
}
} }
private <T> T getOrInstantiate(Class<T> tClass) { private <T> T getOrInstantiate(Class<T> tClass) {
try { try {
return beanFactory != null ? beanFactory.getBean(tClass) return beanFactory != null ? beanFactory.getBean(tClass) : applicationContext.getBean(tClass);
: applicationContext.getBean(tClass);
} }
catch (NoSuchBeanDefinitionException e) { catch (NoSuchBeanDefinitionException e) {
return BeanUtils.instantiateClass(tClass); return BeanUtils.instantiateClass(tClass);
@@ -314,8 +343,7 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
protected <T> T get(FeignContext context, Class<T> type) { protected <T> T get(FeignContext context, Class<T> type) {
T instance = context.getInstance(contextId, type); T instance = context.getInstance(contextId, type);
if (instance == null) { if (instance == null) {
throw new IllegalStateException( throw new IllegalStateException("No bean found of type " + type + " for " + contextId);
"No bean found of type " + type + " for " + contextId);
} }
return instance; return instance;
} }
@@ -333,8 +361,7 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
} }
} }
protected <T> Map<String, T> getInheritedAwareInstances(FeignContext context, protected <T> Map<String, T> getInheritedAwareInstances(FeignContext context, Class<T> type) {
Class<T> type) {
if (inheritParentContext) { if (inheritParentContext) {
return context.getInstances(contextId, type); return context.getInstances(contextId, type);
} }
@@ -343,17 +370,31 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
} }
} }
protected <T> T loadBalance(Feign.Builder builder, FeignContext context, protected <T> T loadBalance(Feign.Builder builder, FeignContext context, HardCodedTarget<T> target) {
HardCodedTarget<T> target) {
Client client = getOptional(context, Client.class); Client client = getOptional(context, Client.class);
if (client != null) { if (client != null) {
builder.client(client); builder.client(client);
applyBuildCustomizers(context, builder);
Targeter targeter = get(context, Targeter.class); Targeter targeter = get(context, Targeter.class);
return targeter.target(this, builder, context, target); return targeter.target(this, builder, context, target);
} }
throw new IllegalStateException( throw new IllegalStateException(
"No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-netflix-ribbon or spring-cloud-starter-loadbalancer?"); "No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalancer?");
}
/**
* Meant to get Options bean from context with bean name.
* @param context context of Feign client
* @param contextId name of feign client
* @return returns Options found in context
*/
protected Request.Options getOptionsByName(FeignContext context, String contextId) {
if (refreshableClient) {
return context.getInstance(contextId, Request.Options.class.getCanonicalName() + "-" + contextId,
Request.Options.class);
}
return null;
} }
@Override @Override
@@ -367,16 +408,14 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
* information * information
*/ */
<T> T getTarget() { <T> T getTarget() {
FeignContext context = beanFactory != null FeignContext context = beanFactory != null ? beanFactory.getBean(FeignContext.class)
? beanFactory.getBean(FeignContext.class)
: applicationContext.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()) { if (LOG.isInfoEnabled()) {
LOG.info("For '" + name LOG.info("For '" + name + "' URL not provided. Will try picking an instance via load-balancing.");
+ "' 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;
@@ -385,8 +424,7 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
url = name; url = name;
} }
url += cleanPath(); url += cleanPath();
return (T) loadBalance(builder, context, return (T) loadBalance(builder, context, new HardCodedTarget<>(type, name, url));
new HardCodedTarget<>(type, name, url));
} }
if (StringUtils.hasText(url) && !url.startsWith("http")) { if (StringUtils.hasText(url) && !url.startsWith("http")) {
url = "http://" + url; url = "http://" + url;
@@ -394,11 +432,6 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
String url = this.url + cleanPath(); String url = this.url + cleanPath();
Client client = getOptional(context, Client.class); Client client = getOptional(context, Client.class);
if (client != null) { if (client != null) {
if (client instanceof LoadBalancerFeignClient) {
// not load balancing because we have a url,
// but ribbon is on the classpath, so unwrap
client = ((LoadBalancerFeignClient) client).getDelegate();
}
if (client instanceof FeignBlockingLoadBalancerClient) { if (client instanceof FeignBlockingLoadBalancerClient) {
// not load balancing because we have a url, // not load balancing because we have a url,
// but Spring Cloud LoadBalancer is on the classpath, so unwrap // but Spring Cloud LoadBalancer is on the classpath, so unwrap
@@ -407,17 +440,21 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
if (client instanceof RetryableFeignBlockingLoadBalancerClient) { if (client instanceof RetryableFeignBlockingLoadBalancerClient) {
// not load balancing because we have a url, // not load balancing because we have a url,
// but Spring Cloud LoadBalancer is on the classpath, so unwrap // but Spring Cloud LoadBalancer is on the classpath, so unwrap
client = ((RetryableFeignBlockingLoadBalancerClient) client) client = ((RetryableFeignBlockingLoadBalancerClient) client).getDelegate();
.getDelegate();
} }
builder.client(client); builder.client(client);
} }
applyBuildCustomizers(context, builder);
Targeter targeter = get(context, Targeter.class); Targeter targeter = get(context, Targeter.class);
return (T) targeter.target(this, builder, context, return (T) targeter.target(this, builder, context, new HardCodedTarget<>(type, name, url));
new HardCodedTarget<>(type, name, url));
} }
private String cleanPath() { private String cleanPath() {
if (path == null) {
return "";
}
String path = this.path.trim(); String path = this.path.trim();
if (StringUtils.hasLength(path)) { if (StringUtils.hasLength(path)) {
if (!path.startsWith("/")) { if (!path.startsWith("/")) {
@@ -526,6 +563,10 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
this.fallbackFactory = fallbackFactory; this.fallbackFactory = fallbackFactory;
} }
public void setRefreshableClient(boolean refreshableClient) {
this.refreshableClient = refreshableClient;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o) {
@@ -536,40 +577,33 @@ public class FeignClientFactoryBean implements FactoryBean<Object>, Initializing
} }
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) && Objects.equals(beanFactory, that.beanFactory) && decode404 == that.decode404
&& decode404 == that.decode404 && inheritParentContext == that.inheritParentContext && Objects.equals(fallback, that.fallback)
&& inheritParentContext == that.inheritParentContext && Objects.equals(fallbackFactory, that.fallbackFactory) && Objects.equals(name, that.name)
&& Objects.equals(fallback, that.fallback) && Objects.equals(path, that.path) && Objects.equals(type, that.type) && Objects.equals(url, that.url)
&& Objects.equals(fallbackFactory, that.fallbackFactory)
&& Objects.equals(name, that.name) && Objects.equals(path, that.path)
&& Objects.equals(type, that.type) && Objects.equals(url, that.url)
&& Objects.equals(connectTimeoutMillis, that.connectTimeoutMillis) && Objects.equals(connectTimeoutMillis, that.connectTimeoutMillis)
&& Objects.equals(readTimeoutMillis, that.readTimeoutMillis) && Objects.equals(readTimeoutMillis, that.readTimeoutMillis)
&& Objects.equals(followRedirects, that.followRedirects); && Objects.equals(followRedirects, that.followRedirects)
&& Objects.equals(refreshableClient, that.refreshableClient);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(applicationContext, beanFactory, decode404, return Objects.hash(applicationContext, beanFactory, decode404, inheritParentContext, fallback, fallbackFactory,
inheritParentContext, fallback, fallbackFactory, name, path, type, url, name, path, type, url, readTimeoutMillis, connectTimeoutMillis, followRedirects, refreshableClient);
readTimeoutMillis, connectTimeoutMillis, followRedirects);
} }
@Override @Override
public String toString() { public String toString() {
return new StringBuilder("FeignClientFactoryBean{").append("type=").append(type) return new StringBuilder("FeignClientFactoryBean{").append("type=").append(type).append(", ").append("name='")
.append(", ").append("name='").append(name).append("', ").append("url='") .append(name).append("', ").append("url='").append(url).append("', ").append("path='").append(path)
.append(url).append("', ").append("path='").append(path).append("', ") .append("', ").append("decode404=").append(decode404).append(", ").append("inheritParentContext=")
.append("decode404=").append(decode404).append(", ") .append(inheritParentContext).append(", ").append("applicationContext=").append(applicationContext)
.append("inheritParentContext=").append(inheritParentContext).append(", ") .append(", ").append("beanFactory=").append(beanFactory).append(", ").append("fallback=")
.append("applicationContext=").append(applicationContext).append(", ") .append(fallback).append(", ").append("fallbackFactory=").append(fallbackFactory).append("}")
.append("beanFactory=").append(beanFactory).append(", ") .append("connectTimeoutMillis=").append(connectTimeoutMillis).append("}").append("readTimeoutMillis=")
.append("fallback=").append(fallback).append(", ") .append(readTimeoutMillis).append("}").append("followRedirects=").append(followRedirects)
.append("fallbackFactory=").append(fallbackFactory).append("}") .append("refreshableClient=").append(refreshableClient).append("}").toString();
.append("connectTimeoutMillis=").append(connectTimeoutMillis).append("}")
.append("readTimeoutMillis=").append(readTimeoutMillis).append("}")
.append("followRedirects=").append(followRedirects).append("}")
.toString();
} }
@Override @Override
@@ -0,0 +1,52 @@
/*
* Copyright 2021-2022 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.util.Map;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* @author Jonatan Ivanov
*/
class FeignClientMetricsEnabledCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
FeignClientProperties feignClientProperties = context.getBeanFactory()
.getBeanProvider(FeignClientProperties.class).getIfAvailable();
if (feignClientProperties != null) {
Map<String, FeignClientProperties.FeignClientConfiguration> feignClientConfigMap = feignClientProperties
.getConfig();
if (feignClientConfigMap != null) {
FeignClientProperties.FeignClientConfiguration feignClientConfig = feignClientConfigMap
.get(context.getEnvironment().getProperty("spring.cloud.openfeign.client.name"));
if (feignClientConfig != null) {
FeignClientProperties.MetricsProperties metrics = feignClientConfig.getMetrics();
if (metrics != null && metrics.getEnabled() != null) {
return metrics.getEnabled();
}
}
}
}
return true;
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 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,11 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import feign.Capability;
import feign.Contract; import feign.Contract;
import feign.ExceptionPropagationPolicy; import feign.ExceptionPropagationPolicy;
import feign.Logger; import feign.Logger;
import feign.QueryMapEncoder;
import feign.RequestInterceptor; import feign.RequestInterceptor;
import feign.Retryer; import feign.Retryer;
import feign.codec.Decoder; import feign.codec.Decoder;
@@ -37,9 +39,11 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
* @author Eko Kurniawan Khannedy * @author Eko Kurniawan Khannedy
* @author Ilia Ilinykh * @author Ilia Ilinykh
* @author Ram Anaswara * @author Ram Anaswara
* @author Jonatan Ivanov
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Hyeonmin Park
*/ */
@ConfigurationProperties("feign.client") @ConfigurationProperties("spring.cloud.openfeign.client")
public class FeignClientProperties { public class FeignClientProperties {
private boolean defaultToProperties = true; private boolean defaultToProperties = true;
@@ -95,10 +99,8 @@ public class FeignClientProperties {
return false; return false;
} }
FeignClientProperties that = (FeignClientProperties) o; FeignClientProperties that = (FeignClientProperties) o;
return defaultToProperties == that.defaultToProperties return defaultToProperties == that.defaultToProperties && Objects.equals(defaultConfig, that.defaultConfig)
&& Objects.equals(defaultConfig, that.defaultConfig) && Objects.equals(config, that.config) && Objects.equals(decodeSlash, that.decodeSlash);
&& Objects.equals(config, that.config)
&& Objects.equals(decodeSlash, that.decodeSlash);
} }
@Override @Override
@@ -137,6 +139,12 @@ public class FeignClientProperties {
private ExceptionPropagationPolicy exceptionPropagationPolicy; private ExceptionPropagationPolicy exceptionPropagationPolicy;
private List<Class<Capability>> capabilities;
private Class<QueryMapEncoder> queryMapEncoder;
private MetricsProperties metrics;
private Boolean followRedirects; private Boolean followRedirects;
public Logger.Level getLoggerLevel() { public Logger.Level getLoggerLevel() {
@@ -183,8 +191,7 @@ public class FeignClientProperties {
return requestInterceptors; return requestInterceptors;
} }
public void setRequestInterceptors( public void setRequestInterceptors(List<Class<RequestInterceptor>> requestInterceptors) {
List<Class<RequestInterceptor>> requestInterceptors) {
this.requestInterceptors = requestInterceptors; this.requestInterceptors = requestInterceptors;
} }
@@ -192,8 +199,7 @@ public class FeignClientProperties {
return defaultRequestHeaders; return defaultRequestHeaders;
} }
public void setDefaultRequestHeaders( public void setDefaultRequestHeaders(Map<String, Collection<String>> defaultRequestHeaders) {
Map<String, Collection<String>> defaultRequestHeaders) {
this.defaultRequestHeaders = defaultRequestHeaders; this.defaultRequestHeaders = defaultRequestHeaders;
} }
@@ -201,8 +207,7 @@ public class FeignClientProperties {
return defaultQueryParameters; return defaultQueryParameters;
} }
public void setDefaultQueryParameters( public void setDefaultQueryParameters(Map<String, Collection<String>> defaultQueryParameters) {
Map<String, Collection<String>> defaultQueryParameters) {
this.defaultQueryParameters = defaultQueryParameters; this.defaultQueryParameters = defaultQueryParameters;
} }
@@ -242,11 +247,34 @@ public class FeignClientProperties {
return exceptionPropagationPolicy; return exceptionPropagationPolicy;
} }
public void setExceptionPropagationPolicy( public void setExceptionPropagationPolicy(ExceptionPropagationPolicy exceptionPropagationPolicy) {
ExceptionPropagationPolicy exceptionPropagationPolicy) {
this.exceptionPropagationPolicy = exceptionPropagationPolicy; this.exceptionPropagationPolicy = exceptionPropagationPolicy;
} }
public List<Class<Capability>> getCapabilities() {
return capabilities;
}
public void setCapabilities(List<Class<Capability>> capabilities) {
this.capabilities = capabilities;
}
public Class<QueryMapEncoder> getQueryMapEncoder() {
return queryMapEncoder;
}
public void setQueryMapEncoder(Class<QueryMapEncoder> queryMapEncoder) {
this.queryMapEncoder = queryMapEncoder;
}
public MetricsProperties getMetrics() {
return metrics;
}
public void setMetrics(MetricsProperties metrics) {
this.metrics = metrics;
}
public Boolean isFollowRedirects() { public Boolean isFollowRedirects() {
return followRedirects; return followRedirects;
} }
@@ -264,29 +292,60 @@ public class FeignClientProperties {
return false; return false;
} }
FeignClientConfiguration that = (FeignClientConfiguration) o; FeignClientConfiguration that = (FeignClientConfiguration) o;
return loggerLevel == that.loggerLevel return loggerLevel == that.loggerLevel && Objects.equals(connectTimeout, that.connectTimeout)
&& Objects.equals(connectTimeout, that.connectTimeout) && Objects.equals(readTimeout, that.readTimeout) && Objects.equals(retryer, that.retryer)
&& Objects.equals(readTimeout, that.readTimeout)
&& Objects.equals(retryer, that.retryer)
&& Objects.equals(errorDecoder, that.errorDecoder) && Objects.equals(errorDecoder, that.errorDecoder)
&& Objects.equals(requestInterceptors, that.requestInterceptors) && Objects.equals(requestInterceptors, that.requestInterceptors)
&& Objects.equals(decode404, that.decode404) && Objects.equals(decode404, that.decode404) && Objects.equals(encoder, that.encoder)
&& Objects.equals(encoder, that.encoder) && Objects.equals(decoder, that.decoder) && Objects.equals(contract, that.contract)
&& Objects.equals(decoder, that.decoder) && Objects.equals(exceptionPropagationPolicy, that.exceptionPropagationPolicy)
&& Objects.equals(contract, that.contract)
&& Objects.equals(exceptionPropagationPolicy,
that.exceptionPropagationPolicy)
&& Objects.equals(defaultRequestHeaders, that.defaultRequestHeaders) && Objects.equals(defaultRequestHeaders, that.defaultRequestHeaders)
&& Objects.equals(defaultQueryParameters, that.defaultQueryParameters) && Objects.equals(defaultQueryParameters, that.defaultQueryParameters)
&& Objects.equals(capabilities, that.capabilities)
&& Objects.equals(queryMapEncoder, that.queryMapEncoder) && Objects.equals(metrics, that.metrics)
&& Objects.equals(followRedirects, that.followRedirects); && Objects.equals(followRedirects, that.followRedirects);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(loggerLevel, connectTimeout, readTimeout, retryer, return Objects.hash(loggerLevel, connectTimeout, readTimeout, retryer, errorDecoder, requestInterceptors,
errorDecoder, requestInterceptors, decode404, encoder, decoder, decode404, encoder, decoder, contract, exceptionPropagationPolicy, defaultQueryParameters,
contract, exceptionPropagationPolicy, defaultQueryParameters, defaultRequestHeaders, capabilities, queryMapEncoder, metrics, followRedirects);
defaultRequestHeaders, followRedirects); }
}
/**
* Metrics configuration for Feign Client.
*/
public static class MetricsProperties {
private Boolean enabled = true;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MetricsProperties that = (MetricsProperties) o;
return Objects.equals(enabled, that.enabled);
}
@Override
public int hashCode() {
return Objects.hash(enabled);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -25,7 +25,7 @@ import org.springframework.cloud.context.named.NamedContextFactory;
* @author Dave Syer * @author Dave Syer
* @author Gregor Zurowski * @author Gregor Zurowski
*/ */
class FeignClientSpecification implements NamedContextFactory.Specification { public class FeignClientSpecification implements NamedContextFactory.Specification {
private String name; private String name;
@@ -34,7 +34,7 @@ class FeignClientSpecification implements NamedContextFactory.Specification {
FeignClientSpecification() { FeignClientSpecification() {
} }
FeignClientSpecification(String name, Class<?>[] configuration) { public FeignClientSpecification(String name, Class<?>[] configuration) {
this.name = name; this.name = name;
this.configuration = configuration; this.configuration = configuration;
} }
@@ -64,8 +64,7 @@ class FeignClientSpecification implements NamedContextFactory.Specification {
return false; return false;
} }
FeignClientSpecification that = (FeignClientSpecification) o; FeignClientSpecification that = (FeignClientSpecification) o;
return Objects.equals(this.name, that.name) return Objects.equals(this.name, that.name) && Arrays.equals(this.configuration, that.configuration);
&& Arrays.equals(this.configuration, that.configuration);
} }
@Override @Override
@@ -75,9 +74,8 @@ class FeignClientSpecification implements NamedContextFactory.Specification {
@Override @Override
public String toString() { public String toString() {
return new StringBuilder("FeignClientSpecification{").append("name='") return new StringBuilder("FeignClientSpecification{").append("name='").append(this.name).append("', ")
.append(this.name).append("', ").append("configuration=") .append("configuration=").append(Arrays.toString(this.configuration)).append("}").toString();
.append(Arrays.toString(this.configuration)).append("}").toString();
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 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,7 +19,6 @@ package org.springframework.cloud.openfeign;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.netflix.hystrix.HystrixCommand;
import feign.Contract; import feign.Contract;
import feign.Feign; import feign.Feign;
import feign.Logger; import feign.Logger;
@@ -29,8 +28,9 @@ import feign.codec.Decoder;
import feign.codec.Encoder; import feign.codec.Encoder;
import feign.form.MultipartFormContentProcessor; import feign.form.MultipartFormContentProcessor;
import feign.form.spring.SpringFormEncoder; import feign.form.spring.SpringFormEncoder;
import feign.hystrix.HystrixFeign; import feign.micrometer.MicrometerCapability;
import feign.optionals.OptionalDecoder; import feign.optionals.OptionalDecoder;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.ObjectProvider;
@@ -47,6 +47,7 @@ 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.FeignEncoderProperties; import org.springframework.cloud.openfeign.support.FeignEncoderProperties;
import org.springframework.cloud.openfeign.support.HttpMessageConverterCustomizer;
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.PageableSpringQueryMapEncoder;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
@@ -54,6 +55,7 @@ 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;
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.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.ConversionService;
@@ -66,8 +68,10 @@ 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 Jonatan Ivanov
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Hyeonmin Park * @author Hyeonmin Park
* @author Yanming Zhou
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
public class FeignClientsConfiguration { public class FeignClientsConfiguration {
@@ -95,33 +99,30 @@ public class FeignClientsConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public Decoder feignDecoder() { public Decoder feignDecoder(ObjectProvider<HttpMessageConverterCustomizer> customizers) {
return new OptionalDecoder( return new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(messageConverters, customizers)));
new ResponseEntityDecoder(new SpringDecoder(this.messageConverters)));
} }
@Bean @Bean
@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, encoderProperties); ObjectProvider<HttpMessageConverterCustomizer> customizers) {
return springEncoder(formWriterProvider, encoderProperties, customizers);
} }
@Bean @Bean
@ConditionalOnClass(name = "org.springframework.data.domain.Pageable") @ConditionalOnClass(name = "org.springframework.data.domain.Pageable")
@ConditionalOnMissingBean @ConditionalOnMissingBean
public Encoder feignEncoderPageable( public Encoder feignEncoderPageable(ObjectProvider<AbstractFormWriter> formWriterProvider,
ObjectProvider<AbstractFormWriter> formWriterProvider) { ObjectProvider<HttpMessageConverterCustomizer> customizers) {
PageableSpringEncoder encoder = new PageableSpringEncoder( PageableSpringEncoder encoder = new PageableSpringEncoder(
springEncoder(formWriterProvider, encoderProperties)); springEncoder(formWriterProvider, encoderProperties, customizers));
if (springDataWebProperties != null) { if (springDataWebProperties != null) {
encoder.setPageParameter( encoder.setPageParameter(springDataWebProperties.getPageable().getPageParameter());
springDataWebProperties.getPageable().getPageParameter()); encoder.setSizeParameter(springDataWebProperties.getPageable().getSizeParameter());
encoder.setSizeParameter( encoder.setSortParameter(springDataWebProperties.getSort().getSortParameter());
springDataWebProperties.getPageable().getSizeParameter());
encoder.setSortParameter(
springDataWebProperties.getSort().getSortParameter());
} }
return encoder; return encoder;
} }
@@ -130,22 +131,26 @@ public class FeignClientsConfiguration {
@ConditionalOnClass(name = "org.springframework.data.domain.Pageable") @ConditionalOnClass(name = "org.springframework.data.domain.Pageable")
@ConditionalOnMissingBean @ConditionalOnMissingBean
public QueryMapEncoder feignQueryMapEncoderPageable() { public QueryMapEncoder feignQueryMapEncoderPageable() {
return new PageableSpringQueryMapEncoder(); PageableSpringQueryMapEncoder queryMapEncoder = new PageableSpringQueryMapEncoder();
if (springDataWebProperties != null) {
queryMapEncoder.setPageParameter(springDataWebProperties.getPageable().getPageParameter());
queryMapEncoder.setSizeParameter(springDataWebProperties.getPageable().getSizeParameter());
queryMapEncoder.setSortParameter(springDataWebProperties.getSort().getSortParameter());
}
return queryMapEncoder;
} }
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public Contract feignContract(ConversionService feignConversionService) { public Contract feignContract(ConversionService feignConversionService) {
boolean decodeSlash = feignClientProperties == null boolean decodeSlash = feignClientProperties == null || feignClientProperties.isDecodeSlash();
|| feignClientProperties.isDecodeSlash(); return new SpringMvcContract(parameterProcessors, feignConversionService, decodeSlash);
return new SpringMvcContract(this.parameterProcessors, feignConversionService,
decodeSlash);
} }
@Bean @Bean
public FormattingConversionService feignConversionService() { public FormattingConversionService feignConversionService() {
FormattingConversionService conversionService = new DefaultFormattingConversionService(); FormattingConversionService conversionService = new DefaultFormattingConversionService();
for (FeignFormatterRegistrar feignFormatterRegistrar : this.feignFormatterRegistrars) { for (FeignFormatterRegistrar feignFormatterRegistrar : feignFormatterRegistrars) {
feignFormatterRegistrar.registerFormatters(conversionService); feignFormatterRegistrar.registerFormatters(conversionService);
} }
return conversionService; return conversionService;
@@ -157,17 +162,10 @@ public class FeignClientsConfiguration {
return Retryer.NEVER_RETRY; return Retryer.NEVER_RETRY;
} }
@Bean
@Scope("prototype")
@ConditionalOnMissingBean
public Feign.Builder feignBuilder(Retryer retryer) {
return Feign.builder().retryer(retryer);
}
@Bean @Bean
@ConditionalOnMissingBean(FeignLoggerFactory.class) @ConditionalOnMissingBean(FeignLoggerFactory.class)
public FeignLoggerFactory feignLoggerFactory() { public FeignLoggerFactory feignLoggerFactory() {
return new DefaultFeignLoggerFactory(this.logger); return new DefaultFeignLoggerFactory(logger);
} }
@Bean @Bean
@@ -178,48 +176,45 @@ public class FeignClientsConfiguration {
} }
private Encoder springEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider, private Encoder springEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider,
FeignEncoderProperties encoderProperties) { FeignEncoderProperties encoderProperties, ObjectProvider<HttpMessageConverterCustomizer> customizers) {
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), messageConverters, encoderProperties,
this.messageConverters, encoderProperties); customizers);
} }
else { else {
return new SpringEncoder(new SpringFormEncoder(), this.messageConverters, return new SpringEncoder(new SpringFormEncoder(), messageConverters, encoderProperties, customizers);
encoderProperties);
} }
} }
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ HystrixCommand.class, HystrixFeign.class })
protected static class HystrixFeignConfiguration {
@Bean
@Scope("prototype")
@ConditionalOnMissingBean
@ConditionalOnProperty(name = "feign.hystrix.enabled")
public Feign.Builder feignHystrixBuilder() {
return HystrixFeign.builder();
}
}
private class SpringPojoFormEncoder extends SpringFormEncoder { private class SpringPojoFormEncoder extends SpringFormEncoder {
SpringPojoFormEncoder(AbstractFormWriter formWriter) { SpringPojoFormEncoder(AbstractFormWriter formWriter) {
super(); super();
MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor( MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor(MULTIPART);
MULTIPART);
processor.addFirstWriter(formWriter); processor.addFirstWriter(formWriter);
} }
} }
@Configuration(proxyBeanMethods = false)
@Conditional(FeignCircuitBreakerDisabledConditions.class)
protected static class DefaultFeignBuilderConfiguration {
@Bean
@Scope("prototype")
@ConditionalOnMissingBean
public Feign.Builder feignBuilder(Retryer retryer) {
return Feign.builder().retryer(retryer);
}
}
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(CircuitBreaker.class) @ConditionalOnClass(CircuitBreaker.class)
@ConditionalOnProperty("feign.circuitbreaker.enabled") @ConditionalOnProperty("spring.cloud.openfeign.circuitbreaker.enabled")
protected static class CircuitBreakerPresentFeignBuilderConfiguration { protected static class CircuitBreakerPresentFeignBuilderConfiguration {
@Bean @Bean
@@ -239,4 +234,19 @@ public class FeignClientsConfiguration {
} }
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(type = "io.micrometer.core.instrument.MeterRegistry")
@ConditionalOnClass(name = "feign.micrometer.MicrometerCapability")
@ConditionalOnProperty(name = "spring.cloud.openfeign.metrics.enabled", matchIfMissing = true)
@Conditional(FeignClientMetricsEnabledCondition.class)
protected static class MetricsConfiguration {
@Bean
@ConditionalOnMissingBean
public MicrometerCapability micrometerCapability(MeterRegistry meterRegistry) {
return new MicrometerCapability(meterRegistry);
}
}
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 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.
@@ -29,6 +29,9 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import feign.Request;
import org.springframework.aop.scope.ScopedProxyUtils;
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.annotation.AnnotatedGenericBeanDefinition;
@@ -63,9 +66,9 @@ import org.springframework.util.StringUtils;
* @author Michal Domagala * @author Michal Domagala
* @author Marcin Grzejszczak * @author Marcin Grzejszczak
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Jasbir Singh
*/ */
class FeignClientsRegistrar class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
// patterned after Spring Integration IntegrationComponentScanRegistrar // patterned after Spring Integration IntegrationComponentScanRegistrar
// and RibbonClientsConfigurationRegistgrar // and RibbonClientsConfigurationRegistgrar
@@ -78,8 +81,7 @@ class FeignClientsRegistrar
} }
static void validateFallback(final Class clazz) { static void validateFallback(final Class clazz) {
Assert.isTrue(!clazz.isInterface(), Assert.isTrue(!clazz.isInterface(), "Fallback class must implement the interface annotated by @FeignClient");
"Fallback class must implement the interface annotated by @FeignClient");
} }
static void validateFallbackFactory(final Class clazz) { static void validateFallbackFactory(final Class clazz) {
@@ -144,16 +146,13 @@ class FeignClientsRegistrar
} }
@Override @Override
public void registerBeanDefinitions(AnnotationMetadata metadata, public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
BeanDefinitionRegistry registry) {
registerDefaultConfiguration(metadata, registry); registerDefaultConfiguration(metadata, registry);
registerFeignClients(metadata, registry); registerFeignClients(metadata, registry);
} }
private void registerDefaultConfiguration(AnnotationMetadata metadata, private void registerDefaultConfiguration(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
BeanDefinitionRegistry registry) { Map<String, Object> defaultAttrs = metadata.getAnnotationAttributes(EnableFeignClients.class.getName(), true);
Map<String, Object> defaultAttrs = metadata
.getAnnotationAttributes(EnableFeignClients.class.getName(), true);
if (defaultAttrs != null && defaultAttrs.containsKey("defaultConfiguration")) { if (defaultAttrs != null && defaultAttrs.containsKey("defaultConfiguration")) {
String name; String name;
@@ -163,19 +162,15 @@ class FeignClientsRegistrar
else { else {
name = "default." + metadata.getClassName(); name = "default." + metadata.getClassName();
} }
registerClientConfiguration(registry, name, registerClientConfiguration(registry, name, defaultAttrs.get("defaultConfiguration"));
defaultAttrs.get("defaultConfiguration"));
} }
} }
public void registerFeignClients(AnnotationMetadata metadata, public void registerFeignClients(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
BeanDefinitionRegistry registry) {
LinkedHashSet<BeanDefinition> candidateComponents = new LinkedHashSet<>(); LinkedHashSet<BeanDefinition> candidateComponents = new LinkedHashSet<>();
Map<String, Object> attrs = metadata Map<String, Object> attrs = metadata.getAnnotationAttributes(EnableFeignClients.class.getName());
.getAnnotationAttributes(EnableFeignClients.class.getName()); final Class<?>[] clients = attrs == null ? null : (Class<?>[]) attrs.get("clients");
final Class<?>[] clients = attrs == null ? null
: (Class<?>[]) attrs.get("clients");
if (clients == null || clients.length == 0) { if (clients == null || clients.length == 0) {
ClassPathScanningCandidateComponentProvider scanner = getScanner(); ClassPathScanningCandidateComponentProvider scanner = getScanner();
scanner.setResourceLoader(this.resourceLoader); scanner.setResourceLoader(this.resourceLoader);
@@ -196,23 +191,21 @@ class FeignClientsRegistrar
// verify annotated class is an interface // verify annotated class is an interface
AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent; AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
AnnotationMetadata annotationMetadata = beanDefinition.getMetadata(); AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
Assert.isTrue(annotationMetadata.isInterface(), Assert.isTrue(annotationMetadata.isInterface(), "@FeignClient can only be specified on an interface");
"@FeignClient can only be specified on an interface");
Map<String, Object> attributes = annotationMetadata Map<String, Object> attributes = annotationMetadata
.getAnnotationAttributes(FeignClient.class.getCanonicalName()); .getAnnotationAttributes(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);
} }
} }
} }
private void registerFeignClient(BeanDefinitionRegistry registry, private void registerFeignClient(BeanDefinitionRegistry registry, AnnotationMetadata annotationMetadata,
AnnotationMetadata annotationMetadata, Map<String, Object> attributes) { Map<String, Object> attributes) {
String className = annotationMetadata.getClassName(); String className = annotationMetadata.getClassName();
Class clazz = ClassUtils.resolveClassName(className, null); Class clazz = ClassUtils.resolveClassName(className, null);
ConfigurableBeanFactory beanFactory = registry instanceof ConfigurableBeanFactory ConfigurableBeanFactory beanFactory = registry instanceof ConfigurableBeanFactory
@@ -224,24 +217,20 @@ class FeignClientsRegistrar
factoryBean.setName(name); factoryBean.setName(name);
factoryBean.setContextId(contextId); factoryBean.setContextId(contextId);
factoryBean.setType(clazz); factoryBean.setType(clazz);
BeanDefinitionBuilder definition = BeanDefinitionBuilder factoryBean.setRefreshableClient(isClientRefreshEnabled());
.genericBeanDefinition(clazz, () -> { BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(clazz, () -> {
factoryBean.setUrl(getUrl(beanFactory, attributes)); factoryBean.setUrl(getUrl(beanFactory, attributes));
factoryBean.setPath(getPath(beanFactory, attributes)); factoryBean.setPath(getPath(beanFactory, attributes));
factoryBean.setDecode404(Boolean factoryBean.setDecode404(Boolean.parseBoolean(String.valueOf(attributes.get("decode404"))));
.parseBoolean(String.valueOf(attributes.get("decode404"))));
Object fallback = attributes.get("fallback"); Object fallback = attributes.get("fallback");
if (fallback != null) { if (fallback != null) {
factoryBean.setFallback(fallback instanceof Class factoryBean.setFallback(fallback instanceof Class ? (Class<?>) fallback
? (Class<?>) fallback
: ClassUtils.resolveClassName(fallback.toString(), null)); : ClassUtils.resolveClassName(fallback.toString(), null));
} }
Object fallbackFactory = attributes.get("fallbackFactory"); Object fallbackFactory = attributes.get("fallbackFactory");
if (fallbackFactory != null) { if (fallbackFactory != null) {
factoryBean.setFallbackFactory(fallbackFactory instanceof Class factoryBean.setFallbackFactory(fallbackFactory instanceof Class ? (Class<?>) fallbackFactory
? (Class<?>) fallbackFactory : ClassUtils.resolveClassName(fallbackFactory.toString(), null));
: ClassUtils.resolveClassName(fallbackFactory.toString(),
null));
} }
return factoryBean.getObject(); return factoryBean.getObject();
}); });
@@ -263,9 +252,10 @@ class FeignClientsRegistrar
qualifiers = new String[] { contextId + "FeignClient" }; qualifiers = new String[] { contextId + "FeignClient" };
} }
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, qualifiers);
qualifiers);
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry); BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
registerOptionsBeanDefinition(registry, contextId);
} }
private void validate(Map<String, Object> attributes) { private void validate(Map<String, Object> attributes) {
@@ -292,8 +282,7 @@ class FeignClientsRegistrar
return getName(name); return getName(name);
} }
private String getContextId(ConfigurableBeanFactory beanFactory, private String getContextId(ConfigurableBeanFactory beanFactory, Map<String, Object> attributes) {
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);
@@ -313,20 +302,21 @@ class FeignClientsRegistrar
if (resolver == null) { if (resolver == null) {
return resolved; return resolved;
} }
return String.valueOf(resolver.evaluate(resolved, Object evaluateValue = resolver.evaluate(resolved, new BeanExpressionContext(beanFactory, null));
new BeanExpressionContext(beanFactory, null))); if (evaluateValue != null) {
return String.valueOf(evaluateValue);
}
return null;
} }
return value; return value;
} }
private String getUrl(ConfigurableBeanFactory beanFactory, private String getUrl(ConfigurableBeanFactory beanFactory, Map<String, Object> attributes) {
Map<String, Object> attributes) {
String url = resolve(beanFactory, (String) attributes.get("url")); String url = resolve(beanFactory, (String) attributes.get("url"));
return getUrl(url); return getUrl(url);
} }
private String getPath(ConfigurableBeanFactory beanFactory, private String getPath(ConfigurableBeanFactory beanFactory, Map<String, Object> attributes) {
Map<String, Object> attributes) {
String path = resolve(beanFactory, (String) attributes.get("path")); String path = resolve(beanFactory, (String) attributes.get("path"));
return getPath(path); return getPath(path);
} }
@@ -334,8 +324,7 @@ class FeignClientsRegistrar
protected ClassPathScanningCandidateComponentProvider getScanner() { protected ClassPathScanningCandidateComponentProvider getScanner() {
return new ClassPathScanningCandidateComponentProvider(false, this.environment) { return new ClassPathScanningCandidateComponentProvider(false, this.environment) {
@Override @Override
protected boolean isCandidateComponent( protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
AnnotatedBeanDefinition beanDefinition) {
boolean isCandidate = false; boolean isCandidate = false;
if (beanDefinition.getMetadata().isIndependent()) { if (beanDefinition.getMetadata().isIndependent()) {
if (!beanDefinition.getMetadata().isAnnotation()) { if (!beanDefinition.getMetadata().isAnnotation()) {
@@ -367,8 +356,7 @@ class FeignClientsRegistrar
} }
if (basePackages.isEmpty()) { if (basePackages.isEmpty()) {
basePackages.add( basePackages.add(ClassUtils.getPackageName(importingClassMetadata.getClassName()));
ClassUtils.getPackageName(importingClassMetadata.getClassName()));
} }
return basePackages; return basePackages;
} }
@@ -388,8 +376,7 @@ class FeignClientsRegistrar
if (client == null) { if (client == null) {
return null; return null;
} }
List<String> qualifierList = new ArrayList<>( List<String> qualifierList = new ArrayList<>(Arrays.asList((String[]) client.get("qualifiers")));
Arrays.asList((String[]) client.get("qualifiers")));
qualifierList.removeIf(qualifier -> !StringUtils.hasText(qualifier)); qualifierList.removeIf(qualifier -> !StringUtils.hasText(qualifier));
if (qualifierList.isEmpty() && getQualifier(client) != null) { if (qualifierList.isEmpty() && getQualifier(client) != null) {
qualifierList = Collections.singletonList(getQualifier(client)); qualifierList = Collections.singletonList(getQualifier(client));
@@ -415,18 +402,15 @@ class FeignClientsRegistrar
return value; return value;
} }
throw new IllegalStateException("Either 'name' or 'value' must be provided in @" throw new IllegalStateException(
+ FeignClient.class.getSimpleName()); "Either 'name' or 'value' must be provided in @" + FeignClient.class.getSimpleName());
} }
private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name, private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name, Object configuration) {
Object configuration) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(FeignClientSpecification.class);
BeanDefinitionBuilder builder = BeanDefinitionBuilder
.genericBeanDefinition(FeignClientSpecification.class);
builder.addConstructorArgValue(name); builder.addConstructorArgValue(name);
builder.addConstructorArgValue(configuration); builder.addConstructorArgValue(configuration);
registry.registerBeanDefinition( registry.registerBeanDefinition(name + "." + FeignClientSpecification.class.getSimpleName(),
name + "." + FeignClientSpecification.class.getSimpleName(),
builder.getBeanDefinition()); builder.getBeanDefinition());
} }
@@ -435,4 +419,28 @@ class FeignClientsRegistrar
this.environment = environment; this.environment = environment;
} }
/**
* This method is meant to create {@link Request.Options} beans definition with
* refreshScope.
* @param registry spring bean definition registry
* @param contextId name of feign client
*/
private void registerOptionsBeanDefinition(BeanDefinitionRegistry registry, String contextId) {
if (isClientRefreshEnabled()) {
String beanName = Request.Options.class.getCanonicalName() + "-" + contextId;
BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder
.genericBeanDefinition(OptionsFactoryBean.class);
definitionBuilder.setScope("refresh");
definitionBuilder.addPropertyValue("contextId", contextId);
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(definitionBuilder.getBeanDefinition(),
beanName);
definitionHolder = ScopedProxyUtils.createScopedProxy(definitionHolder, registry, true);
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);
}
}
private boolean isClientRefreshEnabled() {
return environment.getProperty("spring.cloud.openfeign.client.refresh-enabled", Boolean.class, false);
}
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -30,11 +30,12 @@ import org.springframework.lang.Nullable;
* @author Spencer Gibb * @author Spencer Gibb
* @author Dave Syer * @author Dave Syer
* @author Matt King * @author Matt King
* @author Jasbir Singh
*/ */
public class FeignContext extends NamedContextFactory<FeignClientSpecification> { public class FeignContext extends NamedContextFactory<FeignClientSpecification> {
public FeignContext() { public FeignContext() {
super(FeignClientsConfiguration.class, "feign", "feign.client.name"); super(FeignClientsConfiguration.class, "spring.cloud.openfeign", "spring.cloud.openfeign.client.name");
} }
@Nullable @Nullable
@@ -52,4 +53,8 @@ public class FeignContext extends NamedContextFactory<FeignClientSpecification>
return getContext(name).getBeansOfType(type); return getContext(name).getBeansOfType(type);
} }
public <T> T getInstance(String contextName, String beanName, Class<T> type) {
return getContext(contextName).getBean(beanName, type);
}
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2020-2020 the original author or authors. * Copyright 2020-2022 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.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2016-2020 the original author or authors. * Copyright 2016-2022 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.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 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.
@@ -34,7 +34,7 @@ public class HttpClient5DisabledConditions extends AnyNestedCondition {
} }
@ConditionalOnProperty(value = "feign.httpclient.hc5.enabled", havingValue = "false", @ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.hc5.enabled", havingValue = "false",
matchIfMissing = true) matchIfMissing = true)
static class HttpClient5Disabled { static class HttpClient5Disabled {
@@ -1,42 +0,0 @@
/*
* 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 {
}
}
@@ -1,101 +0,0 @@
/*
* 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 feign.hystrix.FallbackFactory;
import feign.hystrix.HystrixFeign;
import feign.hystrix.SetterFactory;
import org.springframework.util.StringUtils;
/**
* @author Spencer Gibb
* @author Erik Kringen
*/
@SuppressWarnings("unchecked")
class HystrixTargeter implements Targeter {
@Override
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign,
FeignContext context, Target.HardCodedTarget<T> target) {
if (!(feign instanceof feign.hystrix.HystrixFeign.Builder)) {
return feign.target(target);
}
feign.hystrix.HystrixFeign.Builder builder = (feign.hystrix.HystrixFeign.Builder) feign;
String name = StringUtils.isEmpty(factory.getContextId()) ? factory.getName()
: factory.getContextId();
SetterFactory setterFactory = getOptional(name, context, SetterFactory.class);
if (setterFactory != null) {
builder.setterFactory(setterFactory);
}
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 feign.target(target);
}
private <T> T targetWithFallbackFactory(String feignClientName, FeignContext context,
Target.HardCodedTarget<T> target, HystrixFeign.Builder builder,
Class<?> fallbackFactoryClass) {
FallbackFactory<? extends T> fallbackFactory = (FallbackFactory<? extends T>) getFromContext(
"fallbackFactory", feignClientName, context, fallbackFactoryClass,
FallbackFactory.class);
return builder.target(target, fallbackFactory);
}
private <T> T targetWithFallback(String feignClientName, FeignContext context,
Target.HardCodedTarget<T> target, HystrixFeign.Builder builder,
Class<?> fallback) {
T fallbackInstance = getFromContext("fallback", feignClientName, context,
fallback, target.type());
return 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 <T> T getOptional(String feignClientName, FeignContext context,
Class<T> beanType) {
return context.getInstance(feignClientName, beanType);
}
}
@@ -0,0 +1,86 @@
/*
* Copyright 2013-2022 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.util.Objects;
import java.util.concurrent.TimeUnit;
import feign.Request;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* This factory bean is meant to create {@link Request.Options} instance as per the
* applicable configurations.
*
* @author Jasbir Singh
*/
public class OptionsFactoryBean implements FactoryBean<Request.Options>, ApplicationContextAware {
private ApplicationContext applicationContext;
private String contextId;
private Request.Options options;
@Override
public Class<?> getObjectType() {
return Request.Options.class;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public Request.Options getObject() throws Exception {
if (options != null) {
return options;
}
options = new Request.Options();
FeignClientProperties properties = applicationContext.getBean(FeignClientProperties.class);
options = createOptionsWithApplicableValues(properties.getConfig().get(properties.getDefaultConfig()), options);
options = createOptionsWithApplicableValues(properties.getConfig().get(contextId), options);
return options;
}
public void setContextId(String contextId) {
this.contextId = contextId;
}
private Request.Options createOptionsWithApplicableValues(
FeignClientProperties.FeignClientConfiguration clientConfiguration, Request.Options options) {
if (Objects.isNull(clientConfiguration)) {
return options;
}
int connectTimeoutMillis = Objects.nonNull(clientConfiguration.getConnectTimeout())
? clientConfiguration.getConnectTimeout() : options.connectTimeoutMillis();
int readTimeoutMillis = Objects.nonNull(clientConfiguration.getReadTimeout())
? clientConfiguration.getReadTimeout() : options.readTimeoutMillis();
boolean followRedirects = Objects.nonNull(clientConfiguration.isFollowRedirects())
? clientConfiguration.isFollowRedirects() : options.isFollowRedirects();
return new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS, readTimeoutMillis,
TimeUnit.MILLISECONDS, followRedirects);
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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,9 @@ import feign.Target;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
*/ */
interface Targeter { public interface Targeter {
<T> T target(FeignClientFactoryBean factory, Feign.Builder feign, <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context,
FeignContext context, Target.HardCodedTarget<T> target); Target.HardCodedTarget<T> target);
} }
@@ -0,0 +1,67 @@
/*
* Copyright 2013-2022 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.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import feign.MethodMetadata;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.CookieValue;
import static feign.Util.checkState;
import static feign.Util.emptyToNull;
/**
* @{link CookieValue} annotation processor.
* @author Gong Yi
*
*/
public class CookieValueParameterProcessor implements AnnotatedParameterProcessor {
private static final Class<CookieValue> ANNOTATION = CookieValue.class;
@Override
public Class<? extends Annotation> getAnnotationType() {
return ANNOTATION;
}
@Override
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
int parameterIndex = context.getParameterIndex();
MethodMetadata data = context.getMethodMetadata();
CookieValue cookie = ANNOTATION.cast(annotation);
String name = cookie.value().trim();
checkState(emptyToNull(name) != null, "Cookie.name() was empty on parameter %s", parameterIndex);
context.setParameterName(name);
String cookieExpression = data.template().headers().getOrDefault(HttpHeaders.COOKIE, Arrays.asList("")).stream()
.findFirst().orElse("");
if (cookieExpression.length() == 0) {
cookieExpression = String.format("%s={%s}", name, name);
}
else {
cookieExpression += String.format("; %s={%s}", name, name);
}
data.template().removeHeader(HttpHeaders.COOKIE);
data.template().header(HttpHeaders.COOKIE, cookieExpression);
return true;
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -48,15 +48,13 @@ public class MatrixVariableParameterProcessor implements AnnotatedParameterProce
} }
@Override @Override
public boolean processArgument(AnnotatedParameterContext context, public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
Annotation annotation, Method method) {
int parameterIndex = context.getParameterIndex(); int parameterIndex = context.getParameterIndex();
Class<?> parameterType = method.getParameterTypes()[parameterIndex]; Class<?> parameterType = method.getParameterTypes()[parameterIndex];
MethodMetadata data = context.getMethodMetadata(); MethodMetadata data = context.getMethodMetadata();
String name = ANNOTATION.cast(annotation).value(); String name = ANNOTATION.cast(annotation).value();
checkState(emptyToNull(name) != null, checkState(emptyToNull(name) != null, "MatrixVariable annotation was empty on param %s.",
"MatrixVariable annotation was empty on param %s.",
context.getParameterIndex()); context.getParameterIndex());
context.setParameterName(name); context.setParameterName(name);
@@ -65,8 +63,7 @@ public class MatrixVariableParameterProcessor implements AnnotatedParameterProce
data.indexToExpander().put(parameterIndex, this::expandMap); data.indexToExpander().put(parameterIndex, this::expandMap);
} }
else { else {
data.indexToExpander().put(parameterIndex, data.indexToExpander().put(parameterIndex, object -> ";" + name + "=" + object.toString());
object -> ";" + name + "=" + object.toString());
} }
return true; return true;
@@ -76,8 +73,7 @@ public class MatrixVariableParameterProcessor implements AnnotatedParameterProce
Map<String, Object> paramMap = (Map) object; Map<String, Object> paramMap = (Map) object;
return paramMap.keySet().stream().filter(key -> paramMap.get(key) != null) 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());
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -34,6 +34,7 @@ import static feign.Util.emptyToNull;
* *
* @author Jakub Narloch * @author Jakub Narloch
* @author Abhijit Sarkar * @author Abhijit Sarkar
* @author Yanming Zhou
* @see AnnotatedParameterProcessor * @see AnnotatedParameterProcessor
*/ */
public class PathVariableParameterProcessor implements AnnotatedParameterProcessor { public class PathVariableParameterProcessor implements AnnotatedParameterProcessor {
@@ -46,18 +47,16 @@ public class PathVariableParameterProcessor implements AnnotatedParameterProcess
} }
@Override @Override
public boolean processArgument(AnnotatedParameterContext context, public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
Annotation annotation, Method method) {
String name = ANNOTATION.cast(annotation).value(); String name = ANNOTATION.cast(annotation).value();
checkState(emptyToNull(name) != null, checkState(emptyToNull(name) != null, "PathVariable annotation was empty on param %s.",
"PathVariable annotation was empty on param %s.",
context.getParameterIndex()); context.getParameterIndex());
context.setParameterName(name); context.setParameterName(name);
MethodMetadata data = context.getMethodMetadata(); MethodMetadata data = context.getMethodMetadata();
String varName = '{' + name + '}'; String varName = '{' + name + '}';
if (!data.template().url().contains(varName) String varNameRegex = ".*\\{" + name + "(:[^}]+)?\\}.*";
&& !searchMapValues(data.template().queries(), varName) if (!data.template().url().matches(varNameRegex) && !searchMapValues(data.template().queries(), varName)
&& !searchMapValues(data.template().headers(), varName)) { && !searchMapValues(data.template().headers(), varName)) {
data.formParams().add(name); data.formParams().add(name);
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -40,8 +40,7 @@ public class QueryMapParameterProcessor implements AnnotatedParameterProcessor {
} }
@Override @Override
public boolean processArgument(AnnotatedParameterContext context, public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
Annotation annotation, Method method) {
int paramIndex = context.getParameterIndex(); int paramIndex = context.getParameterIndex();
MethodMetadata metadata = context.getMethodMetadata(); MethodMetadata metadata = context.getMethodMetadata();
if (metadata.queryMapIndex() == null) { if (metadata.queryMapIndex() == null) {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -46,27 +46,23 @@ public class RequestHeaderParameterProcessor implements AnnotatedParameterProces
} }
@Override @Override
public boolean processArgument(AnnotatedParameterContext context, public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
Annotation annotation, Method method) {
int parameterIndex = context.getParameterIndex(); int parameterIndex = context.getParameterIndex();
Class<?> parameterType = method.getParameterTypes()[parameterIndex]; Class<?> parameterType = method.getParameterTypes()[parameterIndex];
MethodMetadata data = context.getMethodMetadata(); MethodMetadata data = context.getMethodMetadata();
if (Map.class.isAssignableFrom(parameterType)) { if (Map.class.isAssignableFrom(parameterType)) {
checkState(data.headerMapIndex() == null, checkState(data.headerMapIndex() == null, "Header map can only be present once.");
"Header map can only be present once.");
data.headerMapIndex(parameterIndex); data.headerMapIndex(parameterIndex);
return true; return true;
} }
String name = ANNOTATION.cast(annotation).value(); String name = ANNOTATION.cast(annotation).value();
checkState(emptyToNull(name) != null, checkState(emptyToNull(name) != null, "RequestHeader.value() was empty on parameter %s", parameterIndex);
"RequestHeader.value() was empty on parameter %s", parameterIndex);
context.setParameterName(name); context.setParameterName(name);
Collection<String> header = context.setTemplateParameter(name, Collection<String> header = context.setTemplateParameter(name, data.template().headers().get(name));
data.template().headers().get(name));
data.template().header(name, header); data.template().header(name, header);
return true; return true;
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -46,15 +46,13 @@ public class RequestParamParameterProcessor implements AnnotatedParameterProcess
} }
@Override @Override
public boolean processArgument(AnnotatedParameterContext context, public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
Annotation annotation, Method method) {
int parameterIndex = context.getParameterIndex(); int parameterIndex = context.getParameterIndex();
Class<?> parameterType = method.getParameterTypes()[parameterIndex]; Class<?> parameterType = method.getParameterTypes()[parameterIndex];
MethodMetadata data = context.getMethodMetadata(); MethodMetadata data = context.getMethodMetadata();
if (Map.class.isAssignableFrom(parameterType)) { if (Map.class.isAssignableFrom(parameterType)) {
checkState(data.queryMapIndex() == null, checkState(data.queryMapIndex() == null, "Query map can only be present once.");
"Query map can only be present once.");
data.queryMapIndex(parameterIndex); data.queryMapIndex(parameterIndex);
return true; return true;
@@ -62,12 +60,10 @@ public class RequestParamParameterProcessor implements AnnotatedParameterProcess
RequestParam requestParam = ANNOTATION.cast(annotation); RequestParam requestParam = ANNOTATION.cast(annotation);
String name = requestParam.value(); String name = requestParam.value();
checkState(emptyToNull(name) != null, checkState(emptyToNull(name) != null, "RequestParam.value() was empty on parameter %s", parameterIndex);
"RequestParam.value() was empty on parameter %s", parameterIndex);
context.setParameterName(name); context.setParameterName(name);
Collection<String> query = context.setTemplateParameter(name, Collection<String> query = context.setTemplateParameter(name, data.template().queries().get(name));
data.template().queries().get(name));
data.template().query(name, query); data.template().query(name, query);
return true; return true;
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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,19 +44,16 @@ public class RequestPartParameterProcessor implements AnnotatedParameterProcesso
} }
@Override @Override
public boolean processArgument(AnnotatedParameterContext context, public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
Annotation annotation, Method method) {
int parameterIndex = context.getParameterIndex(); int parameterIndex = context.getParameterIndex();
MethodMetadata data = context.getMethodMetadata(); MethodMetadata data = context.getMethodMetadata();
String name = ANNOTATION.cast(annotation).value(); String name = ANNOTATION.cast(annotation).value();
checkState(emptyToNull(name) != null, checkState(emptyToNull(name) != null, "RequestPart.value() was empty on parameter %s", parameterIndex);
"RequestPart.value() was empty on parameter %s", parameterIndex);
context.setParameterName(name); context.setParameterName(name);
data.formParams().add(name); data.formParams().add(name);
Collection<String> names = context.setTemplateParameter(name, Collection<String> names = context.setTemplateParameter(name, data.indexToName().get(parameterIndex));
data.indexToName().get(parameterIndex));
data.indexToName().put(parameterIndex, names); data.indexToName().put(parameterIndex, names);
return true; return true;
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2019 the original author or authors. * Copyright 2013-2022 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.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 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,11 +23,11 @@ import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import jakarta.annotation.PreDestroy;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.config.RequestConfig;
@@ -66,25 +66,19 @@ public class HttpClient5FeignConfiguration {
@Bean @Bean
@ConditionalOnMissingBean(HttpClientConnectionManager.class) @ConditionalOnMissingBean(HttpClientConnectionManager.class)
public HttpClientConnectionManager hc5ConnectionManager( public HttpClientConnectionManager hc5ConnectionManager(FeignHttpClientProperties httpClientProperties) {
FeignHttpClientProperties httpClientProperties) {
return PoolingHttpClientConnectionManagerBuilder.create() return PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(httpsSSLConnectionSocketFactory( .setSSLSocketFactory(httpsSSLConnectionSocketFactory(httpClientProperties.isDisableSslValidation()))
httpClientProperties.isDisableSslValidation()))
.setMaxConnTotal(httpClientProperties.getMaxConnections()) .setMaxConnTotal(httpClientProperties.getMaxConnections())
.setMaxConnPerRoute(httpClientProperties.getMaxConnectionsPerRoute()) .setMaxConnPerRoute(httpClientProperties.getMaxConnectionsPerRoute())
.setConnPoolPolicy(PoolReusePolicy.valueOf( .setConnPoolPolicy(PoolReusePolicy.valueOf(httpClientProperties.getHc5().getPoolReusePolicy().name()))
httpClientProperties.getHc5().getPoolReusePolicy().name())) .setPoolConcurrencyPolicy(
.setPoolConcurrencyPolicy(PoolConcurrencyPolicy.valueOf( PoolConcurrencyPolicy.valueOf(httpClientProperties.getHc5().getPoolConcurrencyPolicy().name()))
httpClientProperties.getHc5().getPoolConcurrencyPolicy().name()))
.setConnectionTimeToLive( .setConnectionTimeToLive(
TimeValue.of(httpClientProperties.getTimeToLive(), TimeValue.of(httpClientProperties.getTimeToLive(), httpClientProperties.getTimeToLiveUnit()))
httpClientProperties.getTimeToLiveUnit())) .setDefaultSocketConfig(
.setDefaultSocketConfig(SocketConfig.custom() SocketConfig.custom().setSoTimeout(Timeout.of(httpClientProperties.getHc5().getSocketTimeout(),
.setSoTimeout(Timeout.of( httpClientProperties.getHc5().getSocketTimeoutUnit())).build())
httpClientProperties.getHc5().getSocketTimeout(),
httpClientProperties.getHc5().getSocketTimeoutUnit()))
.build())
.build(); .build();
} }
@@ -93,14 +87,10 @@ public class HttpClient5FeignConfiguration {
FeignHttpClientProperties httpClientProperties) { FeignHttpClientProperties httpClientProperties) {
httpClient5 = HttpClients.custom().disableCookieManagement().useSystemProperties() httpClient5 = HttpClients.custom().disableCookieManagement().useSystemProperties()
.setConnectionManager(connectionManager).evictExpiredConnections() .setConnectionManager(connectionManager).evictExpiredConnections()
.setDefaultRequestConfig( .setDefaultRequestConfig(RequestConfig.custom()
RequestConfig.custom() .setConnectTimeout(
.setConnectTimeout(Timeout.of( Timeout.of(httpClientProperties.getConnectionTimeout(), TimeUnit.MILLISECONDS))
httpClientProperties.getConnectionTimeout(), .setRedirectsEnabled(httpClientProperties.isFollowRedirects()).build())
TimeUnit.MILLISECONDS))
.setRedirectsEnabled(
httpClientProperties.isFollowRedirects())
.build())
.build(); .build();
return httpClient5; return httpClient5;
} }
@@ -112,17 +102,14 @@ public class HttpClient5FeignConfiguration {
} }
} }
private LayeredConnectionSocketFactory httpsSSLConnectionSocketFactory( private LayeredConnectionSocketFactory httpsSSLConnectionSocketFactory(boolean isDisableSslValidation) {
boolean isDisableSslValidation) {
final SSLConnectionSocketFactoryBuilder sslConnectionSocketFactoryBuilder = SSLConnectionSocketFactoryBuilder final SSLConnectionSocketFactoryBuilder sslConnectionSocketFactoryBuilder = SSLConnectionSocketFactoryBuilder
.create().setTlsVersions(TLS.V_1_3, TLS.V_1_2); .create().setTlsVersions(TLS.V_1_3, TLS.V_1_2);
if (isDisableSslValidation) { if (isDisableSslValidation) {
try { try {
final SSLContext sslContext = SSLContext.getInstance("SSL"); final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, sslContext.init(null, new TrustManager[] { new DisabledValidationTrustManager() }, new SecureRandom());
new TrustManager[] { new DisabledValidationTrustManager() },
new SecureRandom());
sslConnectionSocketFactoryBuilder.setSslContext(sslContext); sslConnectionSocketFactoryBuilder.setSslContext(sslContext);
} }
catch (NoSuchAlgorithmException e) { catch (NoSuchAlgorithmException e) {
@@ -133,8 +120,7 @@ public class HttpClient5FeignConfiguration {
} }
} }
else { else {
sslConnectionSocketFactoryBuilder sslConnectionSocketFactoryBuilder.setSslContext(SSLContexts.createSystemDefault());
.setSslContext(SSLContexts.createSystemDefault());
} }
return sslConnectionSocketFactoryBuilder.build(); return sslConnectionSocketFactoryBuilder.build();
@@ -145,12 +131,10 @@ public class HttpClient5FeignConfiguration {
DisabledValidationTrustManager() { DisabledValidationTrustManager() {
} }
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
throws CertificateException {
} }
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
throws CertificateException {
} }
public X509Certificate[] getAcceptedIssuers() { public X509Certificate[] getAcceptedIssuers() {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -20,8 +20,7 @@ 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 jakarta.annotation.PreDestroy;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
@@ -53,8 +52,8 @@ public class HttpClientFeignConfiguration {
private static final Log LOG = LogFactory.getLog(HttpClientFeignConfiguration.class); private static final Log LOG = LogFactory.getLog(HttpClientFeignConfiguration.class);
private final Timer connectionManagerTimer = new Timer( private final Timer connectionManagerTimer = new Timer("FeignApacheHttpClientConfiguration.connectionManagerTimer",
"FeignApacheHttpClientConfiguration.connectionManagerTimer", true); true);
private CloseableHttpClient httpClient; private CloseableHttpClient httpClient;
@@ -66,11 +65,9 @@ public class HttpClientFeignConfiguration {
public HttpClientConnectionManager connectionManager( public HttpClientConnectionManager connectionManager(
ApacheHttpClientConnectionManagerFactory connectionManagerFactory, ApacheHttpClientConnectionManagerFactory connectionManagerFactory,
FeignHttpClientProperties httpClientProperties) { FeignHttpClientProperties httpClientProperties) {
final HttpClientConnectionManager connectionManager = connectionManagerFactory final HttpClientConnectionManager connectionManager = connectionManagerFactory.newConnectionManager(
.newConnectionManager(httpClientProperties.isDisableSslValidation(), httpClientProperties.isDisableSslValidation(), httpClientProperties.getMaxConnections(),
httpClientProperties.getMaxConnections(), httpClientProperties.getMaxConnectionsPerRoute(), httpClientProperties.getTimeToLive(),
httpClientProperties.getMaxConnectionsPerRoute(),
httpClientProperties.getTimeToLive(),
httpClientProperties.getTimeToLiveUnit(), this.registryBuilder); httpClientProperties.getTimeToLiveUnit(), this.registryBuilder);
this.connectionManagerTimer.schedule(new TimerTask() { this.connectionManagerTimer.schedule(new TimerTask() {
@Override @Override
@@ -82,37 +79,30 @@ public class HttpClientFeignConfiguration {
} }
@Bean @Bean
@ConditionalOnProperty(value = "feign.compression.response.enabled", @ConditionalOnProperty(value = "spring.cloud.openfeign.compression.response.enabled", havingValue = "true")
havingValue = "true") public CloseableHttpClient customHttpClient(HttpClientConnectionManager httpClientConnectionManager,
public CloseableHttpClient customHttpClient(
HttpClientConnectionManager httpClientConnectionManager,
FeignHttpClientProperties httpClientProperties) { FeignHttpClientProperties httpClientProperties) {
HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement() HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement().useSystemProperties();
.useSystemProperties(); this.httpClient = createClient(builder, httpClientConnectionManager, httpClientProperties);
this.httpClient = createClient(builder, httpClientConnectionManager,
httpClientProperties);
return this.httpClient; return this.httpClient;
} }
@Bean @Bean
@ConditionalOnProperty(value = "feign.compression.response.enabled", @ConditionalOnProperty(value = "spring.cloud.openfeign.compression.response.enabled", havingValue = "false",
havingValue = "false", matchIfMissing = true) matchIfMissing = true)
public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory, public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory,
HttpClientConnectionManager httpClientConnectionManager, HttpClientConnectionManager httpClientConnectionManager, FeignHttpClientProperties httpClientProperties) {
FeignHttpClientProperties httpClientProperties) { this.httpClient = createClient(httpClientFactory.createBuilder(), httpClientConnectionManager,
this.httpClient = createClient(httpClientFactory.createBuilder(), httpClientProperties);
httpClientConnectionManager, httpClientProperties);
return this.httpClient; return this.httpClient;
} }
private CloseableHttpClient createClient(HttpClientBuilder builder, private CloseableHttpClient createClient(HttpClientBuilder builder,
HttpClientConnectionManager httpClientConnectionManager, HttpClientConnectionManager httpClientConnectionManager, FeignHttpClientProperties httpClientProperties) {
FeignHttpClientProperties httpClientProperties) {
RequestConfig defaultRequestConfig = RequestConfig.custom() RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(httpClientProperties.getConnectionTimeout()) .setConnectTimeout(httpClientProperties.getConnectionTimeout())
.setRedirectsEnabled(httpClientProperties.isFollowRedirects()).build(); .setRedirectsEnabled(httpClientProperties.isFollowRedirects()).build();
CloseableHttpClient httpClient = builder CloseableHttpClient httpClient = builder.setDefaultRequestConfig(defaultRequestConfig)
.setDefaultRequestConfig(defaultRequestConfig)
.setConnectionManager(httpClientConnectionManager).build(); .setConnectionManager(httpClientConnectionManager).build();
return httpClient; return httpClient;
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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,10 +16,10 @@
package org.springframework.cloud.openfeign.clientconfig; package org.springframework.cloud.openfeign.clientconfig;
import java.time.Duration;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy; import jakarta.annotation.PreDestroy;
import okhttp3.ConnectionPool; import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
@@ -46,25 +46,23 @@ public class OkHttpFeignConfiguration {
@Bean @Bean
@ConditionalOnMissingBean(ConnectionPool.class) @ConditionalOnMissingBean(ConnectionPool.class)
public ConnectionPool httpClientConnectionPool( public ConnectionPool httpClientConnectionPool(FeignHttpClientProperties httpClientProperties,
FeignHttpClientProperties httpClientProperties,
OkHttpClientConnectionPoolFactory connectionPoolFactory) { OkHttpClientConnectionPoolFactory connectionPoolFactory) {
Integer maxTotalConnections = httpClientProperties.getMaxConnections(); int maxTotalConnections = httpClientProperties.getMaxConnections();
Long timeToLive = httpClientProperties.getTimeToLive(); long timeToLive = httpClientProperties.getTimeToLive();
TimeUnit ttlUnit = httpClientProperties.getTimeToLiveUnit(); TimeUnit ttlUnit = httpClientProperties.getTimeToLiveUnit();
return connectionPoolFactory.create(maxTotalConnections, timeToLive, ttlUnit); return connectionPoolFactory.create(maxTotalConnections, timeToLive, ttlUnit);
} }
@Bean @Bean
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, ConnectionPool connectionPool,
ConnectionPool connectionPool,
FeignHttpClientProperties httpClientProperties) { FeignHttpClientProperties httpClientProperties) {
Boolean followRedirects = httpClientProperties.isFollowRedirects(); boolean followRedirects = httpClientProperties.isFollowRedirects();
Integer connectTimeout = httpClientProperties.getConnectionTimeout(); int connectTimeout = httpClientProperties.getConnectionTimeout();
this.okHttpClient = httpClientFactory Duration reaTimeout = httpClientProperties.getOkHttp().getReadTimeout();
.createBuilder(httpClientProperties.isDisableSslValidation()) this.okHttpClient = httpClientFactory.createBuilder(httpClientProperties.isDisableSslValidation())
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS) .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects)
.followRedirects(followRedirects).connectionPool(connectionPool).build(); .readTimeout(reaTimeout).connectionPool(connectionPool).build();
return this.okHttpClient; return this.okHttpClient;
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -48,8 +48,7 @@ public abstract class BaseRequestInterceptor implements RequestInterceptor {
* @param name the header name * @param name the header name
* @param values the header values * @param values the header values
*/ */
protected void addHeader(RequestTemplate requestTemplate, String name, protected void addHeader(RequestTemplate requestTemplate, String name, String... values) {
String... values) {
if (!requestTemplate.headers().containsKey(name)) { if (!requestTemplate.headers().containsKey(name)) {
requestTemplate.header(name, values); requestTemplate.header(name, values);
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -39,8 +39,7 @@ import org.springframework.context.annotation.Configuration;
@EnableConfigurationProperties(FeignClientEncodingProperties.class) @EnableConfigurationProperties(FeignClientEncodingProperties.class)
@ConditionalOnClass(Feign.class) @ConditionalOnClass(Feign.class)
@ConditionalOnBean(Client.class) @ConditionalOnBean(Client.class)
@ConditionalOnProperty(value = "feign.compression.response.enabled", @ConditionalOnProperty(value = "spring.cloud.openfeign.compression.response.enabled", matchIfMissing = false)
matchIfMissing = false)
// The OK HTTP client uses "transparent" compression. // The OK HTTP client uses "transparent" compression.
// If the accept-encoding header is present it disable transparent compression // If the accept-encoding header is present it disable transparent compression
@ConditionalOnMissingBean(type = "okhttp3.OkHttpClient") @ConditionalOnMissingBean(type = "okhttp3.OkHttpClient")
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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,8 +33,7 @@ public class FeignAcceptGzipEncodingInterceptor extends BaseRequestInterceptor {
* Creates new instance of {@link FeignAcceptGzipEncodingInterceptor}. * Creates new instance of {@link FeignAcceptGzipEncodingInterceptor}.
* @param properties the encoding properties * @param properties the encoding properties
*/ */
protected FeignAcceptGzipEncodingInterceptor( protected FeignAcceptGzipEncodingInterceptor(FeignClientEncodingProperties properties) {
FeignClientEncodingProperties properties) {
super(properties); super(properties);
} }
@@ -44,8 +43,8 @@ public class FeignAcceptGzipEncodingInterceptor extends BaseRequestInterceptor {
@Override @Override
public void apply(RequestTemplate template) { public void apply(RequestTemplate template) {
addHeader(template, HttpEncoding.ACCEPT_ENCODING_HEADER, addHeader(template, HttpEncoding.ACCEPT_ENCODING_HEADER, HttpEncoding.GZIP_ENCODING,
HttpEncoding.GZIP_ENCODING, HttpEncoding.DEFLATE_ENCODING); HttpEncoding.DEFLATE_ENCODING);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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,14 +26,13 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
* *
* @author Jakub Narloch * @author Jakub Narloch
*/ */
@ConfigurationProperties("feign.compression.request") @ConfigurationProperties("spring.cloud.openfeign.compression.request")
public class FeignClientEncodingProperties { public class FeignClientEncodingProperties {
/** /**
* The list of supported mime types. * The list of supported mime types.
*/ */
private String[] mimeTypes = new String[] { "text/xml", "application/xml", private String[] mimeTypes = new String[] { "text/xml", "application/xml", "application/json" };
"application/json" };
/** /**
* The minimum threshold content size. * The minimum threshold content size.
@@ -77,9 +76,8 @@ public class FeignClientEncodingProperties {
@Override @Override
public String toString() { public String toString() {
return new StringBuilder("FeignClientEncodingProperties{").append("mimeTypes=") return new StringBuilder("FeignClientEncodingProperties{").append("mimeTypes=")
.append(Arrays.toString(this.mimeTypes)).append(", ") .append(Arrays.toString(this.mimeTypes)).append(", ").append("minRequestSize=")
.append("minRequestSize=").append(this.minRequestSize).append("}") .append(this.minRequestSize).append("}").toString();
.toString();
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -39,7 +39,7 @@ import org.springframework.context.annotation.Configuration;
// The OK HTTP client uses "transparent" compression. // The OK HTTP client uses "transparent" compression.
// If the content-encoding header is present it disable transparent compression // If the content-encoding header is present it disable transparent compression
@ConditionalOnMissingBean(type = "okhttp3.OkHttpClient") @ConditionalOnMissingBean(type = "okhttp3.OkHttpClient")
@ConditionalOnProperty("feign.compression.request.enabled") @ConditionalOnProperty("spring.cloud.openfeign.compression.request.enabled")
@AutoConfigureAfter(FeignAutoConfiguration.class) @AutoConfigureAfter(FeignAutoConfiguration.class)
public class FeignContentGzipEncodingAutoConfiguration { public class FeignContentGzipEncodingAutoConfiguration {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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,8 +33,7 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
* Creates new instance of {@link FeignContentGzipEncodingInterceptor}. * Creates new instance of {@link FeignContentGzipEncodingInterceptor}.
* @param properties the encoding properties * @param properties the encoding properties
*/ */
protected FeignContentGzipEncodingInterceptor( protected FeignContentGzipEncodingInterceptor(FeignClientEncodingProperties properties) {
FeignClientEncodingProperties properties) {
super(properties); super(properties);
} }
@@ -45,8 +44,8 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
public void apply(RequestTemplate template) { public void apply(RequestTemplate template) {
if (requiresCompression(template)) { if (requiresCompression(template)) {
addHeader(template, HttpEncoding.CONTENT_ENCODING_HEADER, addHeader(template, HttpEncoding.CONTENT_ENCODING_HEADER, HttpEncoding.GZIP_ENCODING,
HttpEncoding.GZIP_ENCODING, HttpEncoding.DEFLATE_ENCODING); HttpEncoding.DEFLATE_ENCODING);
} }
} }
@@ -84,7 +83,7 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
} }
/** /**
* Returns whether the content mime types matches the configures mime types. * Returns whether the content mime types matches the configured mime types.
* @param contentTypes the content types * @param contentTypes the content types
* @return true if any specified content type matches the request content types * @return true if any specified content type matches the request content types
*/ */
@@ -93,8 +92,7 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
return false; return false;
} }
if (getProperties().getMimeTypes() == null if (getProperties().getMimeTypes() == null || getProperties().getMimeTypes().length == 0) {
|| getProperties().getMimeTypes().length == 0) {
// no specific mime types has been set - matching everything // no specific mime types has been set - matching everything
return true; return true;
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2016-2021 the original author or authors. * Copyright 2016-2022 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,26 +16,18 @@
package org.springframework.cloud.openfeign.hateoas; package org.springframework.cloud.openfeign.hateoas;
import java.util.Collections;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 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.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.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.cloud.openfeign.support.HttpMessageConverterCustomizer;
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.config.HateoasConfiguration;
import org.springframework.hateoas.mediatype.hal.HalMediaTypeConfiguration; import org.springframework.hateoas.config.WebConverters;
import org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter;
import static org.springframework.hateoas.MediaTypes.HAL_JSON;
/** /**
* @author Hector Espert * @author Hector Espert
@@ -43,25 +35,15 @@ import static org.springframework.hateoas.MediaTypes.HAL_JSON;
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication @ConditionalOnWebApplication
@ConditionalOnClass(RepresentationModel.class) @ConditionalOnClass(WebConverters.class)
@AutoConfigureAfter({ JacksonAutoConfiguration.class, @AutoConfigureAfter({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class, HateoasConfiguration.class })
RepositoryRestMvcAutoConfiguration.class })
public class FeignHalAutoConfiguration { public class FeignHalAutoConfiguration {
@Bean @Bean
@ConditionalOnBean(HalMediaTypeConfiguration.class) @ConditionalOnBean(WebConverters.class)
@ConditionalOnMissingBean HttpMessageConverterCustomizer webConvertersCustomizer(WebConverters webConverters) {
public TypeConstrainedMappingJackson2HttpMessageConverter halJacksonHttpMessageConverter( return new WebConvertersCustomizer(webConverters);
ObjectProvider<ObjectMapper> objectMapper,
HalMediaTypeConfiguration halConfiguration) {
ObjectMapper mapper = objectMapper.getIfAvailable(ObjectMapper::new).copy();
halConfiguration.configureObjectMapper(mapper);
TypeConstrainedMappingJackson2HttpMessageConverter converter = new TypeConstrainedMappingJackson2HttpMessageConverter(
RepresentationModel.class);
converter.setSupportedMediaTypes(Collections.singletonList(HAL_JSON));
converter.setObjectMapper(mapper);
return converter;
} }
} }
@@ -0,0 +1,41 @@
/*
* Copyright 2016-2022 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.hateoas;
import java.util.List;
import org.springframework.cloud.openfeign.support.HttpMessageConverterCustomizer;
import org.springframework.hateoas.config.WebConverters;
import org.springframework.http.converter.HttpMessageConverter;
/**
* @author Olga Maciaszek-Sharma
*/
public class WebConvertersCustomizer implements HttpMessageConverterCustomizer {
private final WebConverters webConverters;
public WebConvertersCustomizer(WebConverters webConverters) {
this.webConverters = webConverters;
}
@Override
public void accept(List<HttpMessageConverter<?>> httpMessageConverters) {
webConverters.augmentClient(httpMessageConverters);
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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,43 +24,48 @@ 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.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional; 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 LoadBalancerClient}-based {@link Client} object
* object that uses {@link Client.Default} under the hood. * that uses {@link Client.Default} under the hood.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author changjin wei(魏昌进)
* @since 2.2.0 * @since 2.2.0
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
class DefaultFeignLoadBalancerConfiguration { class DefaultFeignLoadBalancerConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class) @Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(BlockingLoadBalancerClient loadBalancerClient) { public Client feignClient(LoadBalancerClient loadBalancerClient,
return new FeignBlockingLoadBalancerClient(new Client.Default(null, null), LoadBalancerClientFactory loadBalancerClientFactory,
loadBalancerClient); List<LoadBalancerFeignRequestTransformer> transformers) {
return new FeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient,
loadBalancerClientFactory, transformers);
} }
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
@ConditionalOnBean(LoadBalancedRetryFactory.class) @ConditionalOnBean(LoadBalancedRetryFactory.class)
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", @ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
havingValue = "true", matchIfMissing = true) matchIfMissing = true)
public Client feignRetryClient(BlockingLoadBalancerClient loadBalancerClient, public Client feignRetryClient(LoadBalancerClient loadBalancerClient,
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) { LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories); List<LoadBalancerFeignRequestTransformer> transformers) {
return new RetryableFeignBlockingLoadBalancerClient( return new RetryableFeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient,
new Client.Default(null, null), loadBalancerClient, loadBalancedRetryFactory, loadBalancerClientFactory, transformers);
loadBalancedRetryFactories.get(0));
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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,9 @@ package org.springframework.cloud.openfeign.loadbalancer;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import feign.Client; import feign.Client;
import feign.Request; import feign.Request;
@@ -27,58 +30,124 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient; import org.springframework.cloud.client.loadbalancer.CompletionContext;
import org.springframework.cloud.client.loadbalancer.DefaultRequest;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerLifecycle;
import org.springframework.cloud.client.loadbalancer.LoadBalancerLifecycleValidator;
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties;
import org.springframework.cloud.client.loadbalancer.RequestDataContext;
import org.springframework.cloud.client.loadbalancer.ResponseData;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import static org.springframework.cloud.openfeign.loadbalancer.LoadBalancerUtils.buildRequestData;
import static org.springframework.cloud.openfeign.loadbalancer.LoadBalancerUtils.executeWithLoadBalancerLifecycleProcessing;
/** /**
* A {@link Client} implementation that uses {@link BlockingLoadBalancerClient} to select * A {@link Client} implementation that uses {@link LoadBalancerClient} to select a
* a {@link ServiceInstance} to use while resolving the request host. * {@link ServiceInstance} to use while resolving the request host.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author changjin wei(魏昌进)
* @since 2.2.0 * @since 2.2.0
*/ */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class FeignBlockingLoadBalancerClient implements Client { public class FeignBlockingLoadBalancerClient implements Client {
private static final Log LOG = LogFactory private static final Log LOG = LogFactory.getLog(FeignBlockingLoadBalancerClient.class);
.getLog(FeignBlockingLoadBalancerClient.class);
private final Client delegate; private final Client delegate;
private final BlockingLoadBalancerClient loadBalancerClient; private final LoadBalancerClient loadBalancerClient;
public FeignBlockingLoadBalancerClient(Client delegate, private final LoadBalancerClientFactory loadBalancerClientFactory;
BlockingLoadBalancerClient loadBalancerClient) {
private final List<LoadBalancerFeignRequestTransformer> transformers;
/**
* @deprecated in favour of
* {@link FeignBlockingLoadBalancerClient#FeignBlockingLoadBalancerClient(Client, LoadBalancerClient, LoadBalancerClientFactory, List)}
*/
@Deprecated
public FeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancerProperties properties, LoadBalancerClientFactory loadBalancerClientFactory) {
this.delegate = delegate; this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient; this.loadBalancerClient = loadBalancerClient;
this.loadBalancerClientFactory = loadBalancerClientFactory;
this.transformers = Collections.emptyList();
}
/**
* @deprecated in favour of
* {@link FeignBlockingLoadBalancerClient#FeignBlockingLoadBalancerClient(Client, LoadBalancerClient, LoadBalancerClientFactory, List)}
*/
@Deprecated
public FeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancerClientFactory loadBalancerClientFactory) {
this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient;
this.loadBalancerClientFactory = loadBalancerClientFactory;
this.transformers = Collections.emptyList();
}
public FeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient;
this.loadBalancerClientFactory = loadBalancerClientFactory;
this.transformers = transformers;
} }
@Override @Override
public Response execute(Request request, Request.Options options) throws IOException { public Response execute(Request request, Request.Options options) throws IOException {
final URI originalUri = URI.create(request.url()); final URI originalUri = URI.create(request.url());
String serviceId = originalUri.getHost(); String serviceId = originalUri.getHost();
Assert.state(serviceId != null, Assert.state(serviceId != null, "Request URI does not contain a valid hostname: " + originalUri);
"Request URI does not contain a valid hostname: " + originalUri); String hint = getHint(serviceId);
ServiceInstance instance = loadBalancerClient.choose(serviceId); DefaultRequest<RequestDataContext> lbRequest = new DefaultRequest<>(
new RequestDataContext(buildRequestData(request), hint));
Set<LoadBalancerLifecycle> supportedLifecycleProcessors = LoadBalancerLifecycleValidator
.getSupportedLifecycleProcessors(
loadBalancerClientFactory.getInstances(serviceId, LoadBalancerLifecycle.class),
RequestDataContext.class, ResponseData.class, ServiceInstance.class);
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStart(lbRequest));
ServiceInstance instance = loadBalancerClient.choose(serviceId, lbRequest);
org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse = new DefaultResponse(
instance);
if (instance == null) { if (instance == null) {
String message = "Load balancer does not contain an instance for the service " String message = "Load balancer does not contain an instance for the service " + serviceId;
+ serviceId;
if (LOG.isWarnEnabled()) { if (LOG.isWarnEnabled()) {
LOG.warn(message); LOG.warn(message);
} }
return Response.builder().request(request) supportedLifecycleProcessors.forEach(lifecycle -> lifecycle
.status(HttpStatus.SERVICE_UNAVAILABLE.value()) .onComplete(new CompletionContext<ResponseData, ServiceInstance, RequestDataContext>(
CompletionContext.Status.DISCARD, lbRequest, lbResponse)));
return Response.builder().request(request).status(HttpStatus.SERVICE_UNAVAILABLE.value())
.body(message, StandardCharsets.UTF_8).build(); .body(message, StandardCharsets.UTF_8).build();
} }
String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri) String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri).toString();
.toString(); Request newRequest = buildRequest(request, reconstructedUrl, instance);
Request newRequest = buildRequest(request, reconstructedUrl); return executeWithLoadBalancerLifecycleProcessing(delegate, options, newRequest, lbRequest, lbResponse,
return delegate.execute(newRequest, options); supportedLifecycleProcessors);
} }
protected Request buildRequest(Request request, String reconstructedUrl) { protected Request buildRequest(Request request, String reconstructedUrl) {
return Request.create(request.httpMethod(), reconstructedUrl, request.headers(), return Request.create(request.httpMethod(), reconstructedUrl, request.headers(), request.body(),
request.body(), request.charset(), request.requestTemplate()); request.charset(), request.requestTemplate());
}
protected Request buildRequest(Request request, String reconstructedUrl, ServiceInstance instance) {
Request newRequest = buildRequest(request, reconstructedUrl);
if (transformers != null) {
for (LoadBalancerFeignRequestTransformer transformer : transformers) {
newRequest = transformer.transformRequest(newRequest, instance);
}
}
return newRequest;
} }
// Visible for Sleuth instrumentation // Visible for Sleuth instrumentation
@@ -86,4 +155,11 @@ public class FeignBlockingLoadBalancerClient implements Client {
return delegate; return delegate;
} }
private String getHint(String serviceId) {
LoadBalancerProperties properties = loadBalancerClientFactory.getProperties(serviceId);
String defaultHint = properties.getHint().getOrDefault("default", "default");
String hintPropertyValue = properties.getHint().get(serviceId);
return hintPropertyValue != null ? hintPropertyValue : defaultHint;
}
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 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,36 +24,34 @@ import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 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.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.config.BlockingLoadBalancerClientAutoConfiguration;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.openfeign.FeignAutoConfiguration; import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.ribbon.FeignRibbonClientAutoConfiguration;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties; import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
/** /**
* An autoconfiguration that instantiates {@link BlockingLoadBalancerClient}-based * An autoconfiguration that instantiates {@link LoadBalancerClient}-based implementations
* implementations of {@link Client}. In order to use this load-balancing mechanism, the * of {@link Client}.
* Ribbon-based implementation has to be disabled by setting
* <code>spring.cloud.loadbalancer.ribbon.enabled</code> to <code>true</code>.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh * @author Nguyen Ky Thanh
* @since 2.2.0 * @since 2.2.0
*/ */
@ConditionalOnClass(Feign.class) @ConditionalOnClass(Feign.class)
@ConditionalOnBean(BlockingLoadBalancerClient.class) @ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@AutoConfigureBefore(FeignAutoConfiguration.class) @AutoConfigureBefore(FeignAutoConfiguration.class)
@AutoConfigureAfter(FeignRibbonClientAutoConfiguration.class) @AutoConfigureAfter({ BlockingLoadBalancerClientAutoConfiguration.class, LoadBalancerAutoConfiguration.class })
@EnableConfigurationProperties(FeignHttpClientProperties.class) @EnableConfigurationProperties(FeignHttpClientProperties.class)
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
// Order is important here, last should be the default, first should be optional // Order is important here, last should be the default, first should be optional
// see // see
// 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 })
HttpClient5FeignLoadBalancerConfiguration.class,
DefaultFeignLoadBalancerConfiguration.class })
public class FeignLoadBalancerAutoConfiguration { public class FeignLoadBalancerAutoConfiguration {
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 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,50 +26,55 @@ 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.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.openfeign.clientconfig.HttpClient5FeignConfiguration; import org.springframework.cloud.openfeign.clientconfig.HttpClient5FeignConfiguration;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional; 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 LoadBalancerClient}-based {@link Client} object
* object that uses {@link ApacheHttp5Client} under the hood. * that uses {@link ApacheHttp5Client} under the hood.
* *
* @author Nguyen Ky Thanh * @author Nguyen Ky Thanh
* @author changjin wei(魏昌进)
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttp5Client.class) @ConditionalOnClass(ApacheHttp5Client.class)
@ConditionalOnBean(BlockingLoadBalancerClient.class) @ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@ConditionalOnProperty(value = "feign.httpclient.hc5.enabled", havingValue = "true") @ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.hc5.enabled", havingValue = "true")
@Import(HttpClient5FeignConfiguration.class) @Import(HttpClient5FeignConfiguration.class)
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
class HttpClient5FeignLoadBalancerConfiguration { class HttpClient5FeignLoadBalancerConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class) @Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(BlockingLoadBalancerClient loadBalancerClient, public Client feignClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient5,
HttpClient httpClient5) { LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
Client delegate = new ApacheHttp5Client(httpClient5); Client delegate = new ApacheHttp5Client(httpClient5);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient); return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancerClientFactory,
transformers);
} }
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
@ConditionalOnBean(LoadBalancedRetryFactory.class) @ConditionalOnBean(LoadBalancedRetryFactory.class)
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", @ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
havingValue = "true", matchIfMissing = true) matchIfMissing = true)
public Client feignRetryClient(BlockingLoadBalancerClient loadBalancerClient, public Client feignRetryClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient5,
HttpClient httpClient5, LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) { List<LoadBalancerFeignRequestTransformer> transformers) {
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories);
Client delegate = new ApacheHttp5Client(httpClient5); Client delegate = new ApacheHttp5Client(httpClient5);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
loadBalancedRetryFactories.get(0)); loadBalancerClientFactory, transformers);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 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,54 +26,59 @@ 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.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.openfeign.HttpClient5DisabledConditions; import org.springframework.cloud.openfeign.HttpClient5DisabledConditions;
import org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration; import org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Conditional;
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 LoadBalancerClient}-based {@link Client} object
* object that uses {@link ApacheHttpClient} under the hood. * that uses {@link ApacheHttpClient} under the hood.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh * @author Nguyen Ky Thanh
* @author changjin wei(魏昌进)
* @since 2.2.0 * @since 2.2.0
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttpClient.class) @ConditionalOnClass(ApacheHttpClient.class)
@ConditionalOnBean(BlockingLoadBalancerClient.class) @ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true) @ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.enabled", matchIfMissing = true)
@Conditional(HttpClient5DisabledConditions.class) @Conditional(HttpClient5DisabledConditions.class)
@Import(HttpClientFeignConfiguration.class) @Import(HttpClientFeignConfiguration.class)
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
class HttpClientFeignLoadBalancerConfiguration { class HttpClientFeignLoadBalancerConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class) @Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(BlockingLoadBalancerClient loadBalancerClient, public Client feignClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient,
HttpClient httpClient) { LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
ApacheHttpClient delegate = new ApacheHttpClient(httpClient); ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient); return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancerClientFactory,
transformers);
} }
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
@ConditionalOnBean(LoadBalancedRetryFactory.class) @ConditionalOnBean(LoadBalancedRetryFactory.class)
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", @ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
havingValue = "true", matchIfMissing = true) matchIfMissing = true)
public Client feignRetryClient(BlockingLoadBalancerClient loadBalancerClient, public Client feignRetryClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient,
HttpClient httpClient, LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) { List<LoadBalancerFeignRequestTransformer> transformers) {
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories);
ApacheHttpClient delegate = new ApacheHttpClient(httpClient); ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
loadBalancedRetryFactories.get(0)); loadBalancerClientFactory, transformers);
} }
} }
@@ -0,0 +1,47 @@
/*
* Copyright 2013-2022 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 feign.Request;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.core.annotation.Order;
/**
* Allows applications to transform the load-balanced {@link Request} given the chosen
* {@link org.springframework.cloud.client.ServiceInstance}.
*
* @author changjin wei(魏昌进)
*/
@Order(LoadBalancerFeignRequestTransformer.DEFAULT_ORDER)
public interface LoadBalancerFeignRequestTransformer {
/**
* Order for the {@link LoadBalancerFeignRequestTransformer}.
*/
int DEFAULT_ORDER = 0;
/**
* Allows transforming load-balanced requests based on the provided
* {@link ServiceInstance}.
* @param request Original request.
* @param instance ServiceInstance returned from LoadBalancer.
* @return New request or original request
*/
Request transformRequest(Request request, ServiceInstance instance);
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -28,18 +28,14 @@ import org.springframework.cloud.client.loadbalancer.RetryableStatusCodeExceptio
* *
* @author Ryan Baxter * @author Ryan Baxter
*/ */
public class LoadBalancerResponseStatusCodeException public class LoadBalancerResponseStatusCodeException extends RetryableStatusCodeException {
extends RetryableStatusCodeException {
private final Response response; private final Response response;
public LoadBalancerResponseStatusCodeException(String serviceId, Response response, public LoadBalancerResponseStatusCodeException(String serviceId, Response response, byte[] body, URI uri) {
byte[] body, URI uri) {
super(serviceId, response.status(), response, uri); super(serviceId, response.status(), response, uri);
this.response = Response.builder() this.response = Response.builder().body(new ByteArrayInputStream(body), body.length).headers(response.headers())
.body(new ByteArrayInputStream(body), body.length) .reason(response.reason()).status(response.status()).request(response.request()).build();
.headers(response.headers()).reason(response.reason())
.status(response.status()).request(response.request()).build();
} }
@Override @Override
@@ -0,0 +1,95 @@
/*
* Copyright 2013-2022 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.HashMap;
import java.util.Set;
import feign.Client;
import feign.Request;
import feign.Response;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.CompletionContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancerLifecycle;
import org.springframework.cloud.client.loadbalancer.RequestData;
import org.springframework.cloud.client.loadbalancer.ResponseData;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatusCode;
/**
* @author Olga Maciaszek-Sharma
*
* A utility class for handling {@link LoadBalancerLifecycle} calls.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
final class LoadBalancerUtils {
private LoadBalancerUtils() {
throw new IllegalStateException("Can't instantiate a utility class");
}
static Response executeWithLoadBalancerLifecycleProcessing(Client feignClient, Request.Options options,
Request feignRequest, org.springframework.cloud.client.loadbalancer.Request lbRequest,
org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse,
Set<LoadBalancerLifecycle> supportedLifecycleProcessors, boolean loadBalanced) throws IOException {
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStartRequest(lbRequest, lbResponse));
try {
Response response = feignClient.execute(feignRequest, options);
if (loadBalanced) {
supportedLifecycleProcessors.forEach(
lifecycle -> lifecycle.onComplete(new CompletionContext<>(CompletionContext.Status.SUCCESS,
lbRequest, lbResponse, buildResponseData(response))));
}
return response;
}
catch (Exception exception) {
if (loadBalanced) {
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onComplete(
new CompletionContext<>(CompletionContext.Status.FAILED, exception, lbRequest, lbResponse)));
}
throw exception;
}
}
static ResponseData buildResponseData(Response response) {
HttpHeaders responseHeaders = new HttpHeaders();
response.headers().forEach((key, value) -> responseHeaders.put(key, new ArrayList<>(value)));
return new ResponseData(HttpStatusCode.valueOf(response.status()), responseHeaders, null,
buildRequestData(response.request()));
}
static RequestData buildRequestData(Request request) {
HttpHeaders requestHeaders = new HttpHeaders();
request.headers().forEach((key, value) -> requestHeaders.put(key, new ArrayList<>(value)));
return new RequestData(HttpMethod.resolve(request.httpMethod().name()), URI.create(request.url()),
requestHeaders, null, new HashMap<>());
}
static Response executeWithLoadBalancerLifecycleProcessing(Client feignClient, Request.Options options,
Request feignRequest, org.springframework.cloud.client.loadbalancer.Request lbRequest,
org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse,
Set<LoadBalancerLifecycle> supportedLifecycleProcessors) throws IOException {
return executeWithLoadBalancerLifecycleProcessing(feignClient, options, feignRequest, lbRequest, lbResponse,
supportedLifecycleProcessors, true);
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -25,51 +25,56 @@ 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.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
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.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 LoadBalancerClient}-based {@link Client} object
* object that uses {@link OkHttpClient} under the hood. * that uses {@link OkHttpClient} under the hood.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author changjin wei(魏昌进)
* @since 2.2.0 * @since 2.2.0
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OkHttpClient.class) @ConditionalOnClass(OkHttpClient.class)
@ConditionalOnProperty("feign.okhttp.enabled") @ConditionalOnProperty("spring.cloud.openfeign.okhttp.enabled")
@ConditionalOnBean(BlockingLoadBalancerClient.class) @ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@Import(OkHttpFeignConfiguration.class) @Import(OkHttpFeignConfiguration.class)
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
class OkHttpFeignLoadBalancerConfiguration { class OkHttpFeignLoadBalancerConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class) @Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(okhttp3.OkHttpClient okHttpClient, public Client feignClient(okhttp3.OkHttpClient okHttpClient, LoadBalancerClient loadBalancerClient,
BlockingLoadBalancerClient loadBalancerClient) { LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
OkHttpClient delegate = new OkHttpClient(okHttpClient); OkHttpClient delegate = new OkHttpClient(okHttpClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient); return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancerClientFactory,
transformers);
} }
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate") @ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
@ConditionalOnBean(LoadBalancedRetryFactory.class) @ConditionalOnBean(LoadBalancedRetryFactory.class)
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", @ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
havingValue = "true", matchIfMissing = true) matchIfMissing = true)
public Client feignRetryClient(BlockingLoadBalancerClient loadBalancerClient, public Client feignRetryClient(LoadBalancerClient loadBalancerClient, okhttp3.OkHttpClient okHttpClient,
okhttp3.OkHttpClient okHttpClient, LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) { List<LoadBalancerFeignRequestTransformer> transformers) {
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories);
OkHttpClient delegate = new OkHttpClient(okHttpClient); OkHttpClient delegate = new OkHttpClient(okHttpClient);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
loadBalancedRetryFactories.get(0)); loadBalancerClientFactory, transformers);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -47,8 +47,7 @@ public class OnRetryNotEnabledCondition extends AnyNestedCondition {
} }
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", @ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "false")
havingValue = "false")
static class OnLoadBalancerRetryEnabledCondition { static class OnLoadBalancerRetryEnabledCondition {
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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,9 +20,11 @@ import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import feign.Client; import feign.Client;
import feign.Request; import feign.Request;
@@ -31,12 +33,21 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.CompletionContext;
import org.springframework.cloud.client.loadbalancer.DefaultRequest;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy; import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRecoveryCallback; import org.springframework.cloud.client.loadbalancer.LoadBalancedRecoveryCallback;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerLifecycle;
import org.springframework.cloud.client.loadbalancer.LoadBalancerLifecycleValidator;
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties;
import org.springframework.cloud.client.loadbalancer.ResponseData;
import org.springframework.cloud.client.loadbalancer.RetryableRequestContext;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest; import org.springframework.http.HttpRequest;
@@ -45,78 +56,147 @@ import org.springframework.retry.backoff.BackOffPolicy;
import org.springframework.retry.backoff.NoBackOffPolicy; import org.springframework.retry.backoff.NoBackOffPolicy;
import org.springframework.retry.policy.NeverRetryPolicy; import org.springframework.retry.policy.NeverRetryPolicy;
import org.springframework.retry.support.RetryTemplate; import org.springframework.retry.support.RetryTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils; import org.springframework.util.StreamUtils;
import static org.springframework.cloud.openfeign.loadbalancer.LoadBalancerUtils.buildRequestData;
/** /**
* A {@link Client} implementation that provides Spring Retry support for requests * A {@link Client} implementation that provides Spring Retry support for requests
* load-balanced with Spring Cloud LoadBalancer. * load-balanced with Spring Cloud LoadBalancer.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author changjin wei(魏昌进)
* @since 2.2.6 * @since 2.2.6
*/ */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class RetryableFeignBlockingLoadBalancerClient implements Client { public class RetryableFeignBlockingLoadBalancerClient implements Client {
private static final Log LOG = LogFactory private static final Log LOG = LogFactory.getLog(RetryableFeignBlockingLoadBalancerClient.class);
.getLog(FeignBlockingLoadBalancerClient.class);
private final Client delegate; private final Client delegate;
private final BlockingLoadBalancerClient loadBalancerClient; private final LoadBalancerClient loadBalancerClient;
private final LoadBalancedRetryFactory loadBalancedRetryFactory; private final LoadBalancedRetryFactory loadBalancedRetryFactory;
public RetryableFeignBlockingLoadBalancerClient(Client delegate, private final LoadBalancerClientFactory loadBalancerClientFactory;
BlockingLoadBalancerClient loadBalancerClient,
LoadBalancedRetryFactory loadBalancedRetryFactory) { private final List<LoadBalancerFeignRequestTransformer> transformers;
/**
* @deprecated in favour of
* {@link RetryableFeignBlockingLoadBalancerClient#RetryableFeignBlockingLoadBalancerClient(Client, LoadBalancerClient, LoadBalancedRetryFactory, LoadBalancerClientFactory, List)}
*/
@Deprecated
public RetryableFeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties,
LoadBalancerClientFactory loadBalancerClientFactory) {
this.delegate = delegate; this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient; this.loadBalancerClient = loadBalancerClient;
this.loadBalancedRetryFactory = loadBalancedRetryFactory; this.loadBalancedRetryFactory = loadBalancedRetryFactory;
this.loadBalancerClientFactory = loadBalancerClientFactory;
this.transformers = Collections.emptyList();
}
/**
* @deprecated in favour of
* {@link RetryableFeignBlockingLoadBalancerClient#RetryableFeignBlockingLoadBalancerClient(Client, LoadBalancerClient, LoadBalancedRetryFactory, LoadBalancerClientFactory, List)}
*/
@Deprecated
public RetryableFeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory) {
this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient;
this.loadBalancedRetryFactory = loadBalancedRetryFactory;
this.loadBalancerClientFactory = loadBalancerClientFactory;
this.transformers = Collections.emptyList();
}
public RetryableFeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient;
this.loadBalancedRetryFactory = loadBalancedRetryFactory;
this.loadBalancerClientFactory = loadBalancerClientFactory;
this.transformers = transformers;
} }
@Override @Override
public Response execute(Request request, Request.Options options) throws IOException { public Response execute(Request request, Request.Options options) throws IOException {
final URI originalUri = URI.create(request.url()); final URI originalUri = URI.create(request.url());
String serviceId = originalUri.getHost(); String serviceId = originalUri.getHost();
final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory Assert.state(serviceId != null, "Request URI does not contain a valid hostname: " + originalUri);
.createRetryPolicy(serviceId, loadBalancerClient); final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory.createRetryPolicy(serviceId,
loadBalancerClient);
RetryTemplate retryTemplate = buildRetryTemplate(serviceId, request, retryPolicy); RetryTemplate retryTemplate = buildRetryTemplate(serviceId, request, retryPolicy);
return retryTemplate.execute(context -> { return retryTemplate.execute(context -> {
Request feignRequest = null; Request feignRequest = null;
ServiceInstance retrievedServiceInstance = null;
Set<LoadBalancerLifecycle> supportedLifecycleProcessors = LoadBalancerLifecycleValidator
.getSupportedLifecycleProcessors(
loadBalancerClientFactory.getInstances(serviceId, LoadBalancerLifecycle.class),
RetryableRequestContext.class, ResponseData.class, ServiceInstance.class);
String hint = getHint(serviceId);
DefaultRequest<RetryableRequestContext> lbRequest = new DefaultRequest<>(
new RetryableRequestContext(null, buildRequestData(request), hint));
// On retries the policy will choose the server and set it in the context // On retries the policy will choose the server and set it in the context
// and extract the server and update the request being made // and extract the server and update the request being made
if (context instanceof LoadBalancedRetryContext) { if (context instanceof LoadBalancedRetryContext) {
ServiceInstance serviceInstance = ((LoadBalancedRetryContext) context) LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context;
.getServiceInstance(); ServiceInstance serviceInstance = lbContext.getServiceInstance();
if (serviceInstance != null) { if (serviceInstance == null) {
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug(String.format( LOG.debug("Service instance retrieved from LoadBalancedRetryContext: was null. "
"Using service instance from LoadBalancedRetryContext: %s", + "Reattempting service instance selection");
serviceInstance));
} }
String reconstructedUrl = loadBalancerClient ServiceInstance previousServiceInstance = lbContext.getPreviousServiceInstance();
.reconstructURI(serviceInstance, originalUri).toString(); lbRequest.getContext().setPreviousServiceInstance(previousServiceInstance);
feignRequest = buildRequest(request, reconstructedUrl); supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStart(lbRequest));
retrievedServiceInstance = loadBalancerClient.choose(serviceId, lbRequest);
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Selected service instance: %s", retrievedServiceInstance));
} }
lbContext.setServiceInstance(retrievedServiceInstance);
} }
if (feignRequest == null) {
if (retrievedServiceInstance == null) {
if (LOG.isWarnEnabled()) { if (LOG.isWarnEnabled()) {
LOG.warn( LOG.warn("Service instance was not resolved, executing the original request");
"Service instance was not resolved, executing the original request");
} }
org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse = new DefaultResponse(
retrievedServiceInstance);
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle
.onComplete(new CompletionContext<ResponseData, ServiceInstance, RetryableRequestContext>(
CompletionContext.Status.DISCARD, lbRequest, lbResponse)));
feignRequest = request; feignRequest = request;
} }
Response response = delegate.execute(feignRequest, options); else {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Using service instance from LoadBalancedRetryContext: %s",
retrievedServiceInstance));
}
String reconstructedUrl = loadBalancerClient.reconstructURI(retrievedServiceInstance, originalUri)
.toString();
feignRequest = buildRequest(request, reconstructedUrl, retrievedServiceInstance);
}
}
org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse = new DefaultResponse(
retrievedServiceInstance);
Response response = LoadBalancerUtils.executeWithLoadBalancerLifecycleProcessing(delegate, options,
feignRequest, lbRequest, lbResponse, supportedLifecycleProcessors,
retrievedServiceInstance != null);
int responseStatus = response.status(); int responseStatus = response.status();
if (retryPolicy != null && retryPolicy.retryableStatusCode(responseStatus)) { if (retryPolicy != null && retryPolicy.retryableStatusCode(responseStatus)) {
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug( LOG.debug(String.format("Retrying on status code: %d", responseStatus));
String.format("Retrying on status code: %d", responseStatus));
} }
byte[] byteArray = response.body() == null ? new byte[] {} byte[] byteArray = response.body() == null ? new byte[] {}
: StreamUtils.copyToByteArray(response.body().asInputStream()); : StreamUtils.copyToByteArray(response.body().asInputStream());
response.close(); response.close();
throw new LoadBalancerResponseStatusCodeException(serviceId, response, throw new LoadBalancerResponseStatusCodeException(serviceId, response, byteArray,
byteArray, URI.create(request.url())); URI.create(request.url()));
} }
return response; return response;
}, new LoadBalancedRecoveryCallback<Response, Response>() { }, new LoadBalancedRecoveryCallback<Response, Response>() {
@@ -128,26 +208,31 @@ public class RetryableFeignBlockingLoadBalancerClient implements Client {
} }
protected Request buildRequest(Request request, String reconstructedUrl) { protected Request buildRequest(Request request, String reconstructedUrl) {
return Request.create(request.httpMethod(), reconstructedUrl, request.headers(), return Request.create(request.httpMethod(), reconstructedUrl, request.headers(), request.body(),
request.body(), request.charset(), request.requestTemplate()); request.charset(), request.requestTemplate());
} }
private RetryTemplate buildRetryTemplate(String serviceId, Request request, protected Request buildRequest(Request request, String reconstructedUrl, ServiceInstance instance) {
LoadBalancedRetryPolicy retryPolicy) { Request newRequest = buildRequest(request, reconstructedUrl);
if (transformers != null) {
for (LoadBalancerFeignRequestTransformer transformer : transformers) {
newRequest = transformer.transformRequest(newRequest, instance);
}
}
return newRequest;
}
private RetryTemplate buildRetryTemplate(String serviceId, Request request, LoadBalancedRetryPolicy retryPolicy) {
RetryTemplate retryTemplate = new RetryTemplate(); RetryTemplate retryTemplate = new RetryTemplate();
BackOffPolicy backOffPolicy = this.loadBalancedRetryFactory BackOffPolicy backOffPolicy = this.loadBalancedRetryFactory.createBackOffPolicy(serviceId);
.createBackOffPolicy(serviceId); retryTemplate.setBackOffPolicy(backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
retryTemplate.setBackOffPolicy( RetryListener[] retryListeners = this.loadBalancedRetryFactory.createRetryListeners(serviceId);
backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
RetryListener[] retryListeners = this.loadBalancedRetryFactory
.createRetryListeners(serviceId);
if (retryListeners != null && retryListeners.length != 0) { if (retryListeners != null && retryListeners.length != 0) {
retryTemplate.setListeners(retryListeners); retryTemplate.setListeners(retryListeners);
} }
retryTemplate.setRetryPolicy(retryPolicy == null ? new NeverRetryPolicy() retryTemplate.setRetryPolicy(retryPolicy == null ? new NeverRetryPolicy()
: new InterceptorRetryPolicy(toHttpRequest(request), retryPolicy, : new InterceptorRetryPolicy(toHttpRequest(request), retryPolicy, loadBalancerClient, serviceId));
loadBalancerClient, serviceId));
return retryTemplate; return retryTemplate;
} }
@@ -187,4 +272,11 @@ public class RetryableFeignBlockingLoadBalancerClient implements Client {
}; };
} }
private String getHint(String serviceId) {
LoadBalancerProperties properties = loadBalancerClientFactory.getProperties(serviceId);
String defaultHint = properties.getHint().getOrDefault("default", "default");
String hintPropertyValue = properties.getHint().get(serviceId);
return hintPropertyValue != null ? hintPropertyValue : defaultHint;
}
} }
@@ -1,72 +0,0 @@
/*
* 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.ribbon;
import java.util.Map;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ILoadBalancer;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.util.ConcurrentReferenceHashMap;
/**
* Factory for SpringLoadBalancer instances that caches the entries created.
*
* @author Spencer Gibb
* @author Dave Syer
* @author Ryan Baxter
* @author Gang Li
*/
public class CachingSpringLoadBalancerFactory {
protected final SpringClientFactory factory;
protected LoadBalancedRetryFactory loadBalancedRetryFactory = null;
private volatile Map<String, FeignLoadBalancer> cache = new ConcurrentReferenceHashMap<>();
public CachingSpringLoadBalancerFactory(SpringClientFactory factory) {
this.factory = factory;
}
public CachingSpringLoadBalancerFactory(SpringClientFactory factory,
LoadBalancedRetryFactory loadBalancedRetryPolicyFactory) {
this.factory = factory;
this.loadBalancedRetryFactory = loadBalancedRetryPolicyFactory;
}
public FeignLoadBalancer create(String clientName) {
FeignLoadBalancer client = this.cache.get(clientName);
if (client != null) {
return client;
}
IClientConfig config = this.factory.getClientConfig(clientName);
ILoadBalancer lb = this.factory.getLoadBalancer(clientName);
ServerIntrospector serverIntrospector = this.factory.getInstance(clientName,
ServerIntrospector.class);
client = this.loadBalancedRetryFactory != null
? new RetryableFeignLoadBalancer(lb, config, serverIntrospector,
this.loadBalancedRetryFactory)
: new FeignLoadBalancer(lb, config, serverIntrospector);
this.cache.put(clientName, client);
return client;
}
}
@@ -1,40 +0,0 @@
/*
* 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.ribbon;
import feign.Client;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Spencer Gibb
*/
@Configuration(proxyBeanMethods = false)
class DefaultFeignLoadBalancedConfiguration {
@Bean
@ConditionalOnMissingBean
public Client feignClient(CachingSpringLoadBalancerFactory cachingFactory,
SpringClientFactory clientFactory) {
return new LoadBalancerFeignClient(new Client.Default(null, null), cachingFactory,
clientFactory);
}
}
@@ -1,251 +0,0 @@
/*
* 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.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.netflix.client.AbstractLoadBalancerAwareClient;
import com.netflix.client.ClientRequest;
import com.netflix.client.IResponse;
import com.netflix.client.RequestSpecificRetryHandler;
import com.netflix.client.RetryHandler;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import feign.Client;
import feign.Request;
import feign.Response;
import org.springframework.cloud.netflix.ribbon.RibbonProperties;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecureConnectionIfNeeded;
/**
* @author Dave Syer
* @author Spencer Gibb
* @author Ryan Baxter
* @author Tim Ysewyn
* @author Olga Maciaszek-Sharma
*/
public class FeignLoadBalancer extends
AbstractLoadBalancerAwareClient<FeignLoadBalancer.RibbonRequest, FeignLoadBalancer.RibbonResponse> {
private final RibbonProperties ribbon;
protected int connectTimeout;
protected int readTimeout;
protected IClientConfig clientConfig;
protected ServerIntrospector serverIntrospector;
protected boolean followRedirects;
public FeignLoadBalancer(ILoadBalancer lb, IClientConfig clientConfig,
ServerIntrospector serverIntrospector) {
super(lb, clientConfig);
setRetryHandler(RetryHandler.DEFAULT);
this.clientConfig = clientConfig;
this.ribbon = RibbonProperties.from(clientConfig);
RibbonProperties ribbon = this.ribbon;
connectTimeout = ribbon.getConnectTimeout();
readTimeout = ribbon.getReadTimeout();
this.serverIntrospector = serverIntrospector;
followRedirects = ribbon.isFollowRedirects();
}
@Override
public RibbonResponse execute(RibbonRequest request, IClientConfig configOverride)
throws IOException {
Request.Options options;
if (configOverride != null) {
RibbonProperties override = RibbonProperties.from(configOverride);
options = new Request.Options(override.connectTimeout(connectTimeout),
TimeUnit.MILLISECONDS, override.readTimeout(readTimeout),
TimeUnit.MILLISECONDS, override.isFollowRedirects(followRedirects));
}
else {
options = new Request.Options(connectTimeout, TimeUnit.MILLISECONDS,
readTimeout, TimeUnit.MILLISECONDS, followRedirects);
}
Response response = request.client().execute(request.toRequest(), options);
return new RibbonResponse(request.getUri(), response);
}
@Override
public RequestSpecificRetryHandler getRequestSpecificRetryHandler(
RibbonRequest request, IClientConfig requestConfig) {
if (ribbon.isOkToRetryOnAllOperations()) {
return new RequestSpecificRetryHandler(true, true, getRetryHandler(),
requestConfig);
}
if (!request.toRequest().httpMethod().name().equals("GET")) {
return new RequestSpecificRetryHandler(true, false, getRetryHandler(),
requestConfig);
}
else {
return new RequestSpecificRetryHandler(true, true, getRetryHandler(),
requestConfig);
}
}
@Override
public URI reconstructURIWithServer(Server server, URI original) {
URI uri = updateToSecureConnectionIfNeeded(original, clientConfig,
serverIntrospector, server);
return super.reconstructURIWithServer(server, uri);
}
protected static class RibbonRequest extends ClientRequest implements Cloneable {
private final Request request;
private final Client client;
protected RibbonRequest(Client client, Request request, URI uri) {
this.client = client;
setUri(uri);
this.request = toRequest(request);
}
private Request toRequest(Request request) {
Map<String, Collection<String>> headers = new LinkedHashMap<>(
request.headers());
return Request.create(request.httpMethod(), getUri().toASCIIString(), headers,
request.body(), request.charset(), request.requestTemplate());
}
Request toRequest() {
return toRequest(request);
}
Client client() {
return client;
}
HttpRequest toHttpRequest() {
return new HttpRequest() {
@Override
public HttpMethod getMethod() {
return HttpMethod
.resolve(RibbonRequest.this.toRequest().httpMethod().name());
}
@Override
public String getMethodValue() {
return getMethod().name();
}
@Override
public URI getURI() {
return RibbonRequest.this.getUri();
}
@Override
public HttpHeaders getHeaders() {
Map<String, List<String>> headers = new HashMap<>();
Map<String, Collection<String>> feignHeaders = RibbonRequest.this
.toRequest().headers();
for (String key : feignHeaders.keySet()) {
headers.put(key, new ArrayList<>(feignHeaders.get(key)));
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(headers);
return httpHeaders;
}
};
}
public Request getRequest() {
return request;
}
public Client getClient() {
return client;
}
@Override
public Object clone() {
return new RibbonRequest(client, request, getUri());
}
}
protected static class RibbonResponse implements IResponse {
private final URI uri;
private final Response response;
protected RibbonResponse(URI uri, Response response) {
this.uri = uri;
this.response = response;
}
@Override
public Object getPayload() {
return response.body();
}
@Override
public boolean hasPayload() {
return response.body() != null;
}
@Override
public boolean isSuccess() {
return response.status() == 200;
}
@Override
public URI getRequestedURI() {
return uri;
}
@Override
public Map<String, Collection<String>> getHeaders() {
return response.headers();
}
Response toResponse() {
return response;
}
@Override
public void close() throws IOException {
if (response != null && response.body() != null) {
response.body().close();
}
}
}
}
@@ -1,129 +0,0 @@
/*
* 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.ribbon;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy;
import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser;
import org.springframework.http.HttpRequest;
import org.springframework.retry.RetryContext;
/**
* @author Ryan Baxter
*/
public class FeignRetryPolicy extends InterceptorRetryPolicy {
private HttpRequest request;
private String serviceId;
public FeignRetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy,
ServiceInstanceChooser serviceInstanceChooser, String serviceName) {
super(request, policy, serviceInstanceChooser, serviceName);
this.request = request;
this.serviceId = serviceName;
}
@Override
public boolean canRetry(RetryContext context) {
/*
* In InterceptorRetryPolicy.canRetry we ask the LoadBalancer to choose a server
* if one is not set in the retry context and then return true. RetryTemplat calls
* the canRetry method of the policy even on its first execution. So the fact that
* we didnt have a service instance set in the RetryContext signaled that it was
* the first execution and we should return true.
*
* In the Feign scenario, Feign as actually already queried the load balancer for
* a service instance and we set that service instance in the context when we call
* the open method of the policy. So in the Feign case we just return true if the
* retry count is 0 indicating we haven't yet made a failed request.
*/
if (context.getRetryCount() == 0) {
return true;
}
return super.canRetry(context);
}
@Override
public RetryContext open(RetryContext parent) {
/*
* With Feign (unlike Ribbon) the request already has the URI for the service
* instance we are going to make the request to, so extract that information and
* set the service instance in the context. In the Ribbon scenario the URI in the
* request object still has the service id so we choose and set the service
* instance later on.
*/
LoadBalancedRetryContext context = new LoadBalancedRetryContext(parent,
this.request);
context.setServiceInstance(
new FeignRetryPolicyServiceInstance(this.serviceId, this.request));
return context;
}
class FeignRetryPolicyServiceInstance implements ServiceInstance {
private String serviceId;
private HttpRequest request;
private Map<String, String> metadata;
FeignRetryPolicyServiceInstance(String serviceId, HttpRequest request) {
this.serviceId = serviceId;
this.request = request;
this.metadata = new HashMap<>();
}
@Override
public String getServiceId() {
return this.serviceId;
}
@Override
public String getHost() {
return this.request.getURI().getHost();
}
@Override
public int getPort() {
return this.request.getURI().getPort();
}
@Override
public boolean isSecure() {
return "https".equals(this.request.getURI().getScheme());
}
@Override
public URI getUri() {
return this.request.getURI();
}
@Override
public Map<String, String> getMetadata() {
return this.metadata;
}
}
}
@@ -1,85 +0,0 @@
/*
* 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 com.netflix.loadbalancer.ILoadBalancer;
import feign.Feign;
import feign.Request;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
/**
* Autoconfiguration to be activated if Feign is in use and needs to be use Ribbon as a
* load balancer.
*
* @author Dave Syer
* @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh
*/
@ConditionalOnClass({ ILoadBalancer.class, Feign.class })
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.ribbon.enabled",
matchIfMissing = true)
@Configuration(proxyBeanMethods = false)
@AutoConfigureBefore(FeignAutoConfiguration.class)
@EnableConfigurationProperties({ FeignHttpClientProperties.class })
// Order is important here, last should be the default, first should be optional
// see
// https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653
@Import({ HttpClientFeignLoadBalancedConfiguration.class,
OkHttpFeignLoadBalancedConfiguration.class,
HttpClient5FeignLoadBalancedConfiguration.class,
DefaultFeignLoadBalancedConfiguration.class })
public class FeignRibbonClientAutoConfiguration {
@Bean
@Primary
@ConditionalOnMissingBean
@ConditionalOnMissingClass("org.springframework.retry.support.RetryTemplate")
public CachingSpringLoadBalancerFactory cachingLBClientFactory(
SpringClientFactory factory) {
return new CachingSpringLoadBalancerFactory(factory);
}
@Bean
@Primary
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
public CachingSpringLoadBalancerFactory retryabeCachingLBClientFactory(
SpringClientFactory factory, LoadBalancedRetryFactory retryFactory) {
return new CachingSpringLoadBalancerFactory(factory, retryFactory);
}
@Bean
@ConditionalOnMissingBean
public Request.Options feignRequestOptions() {
return LoadBalancerFeignClient.DEFAULT_OPTIONS;
}
}
@@ -1,52 +0,0 @@
/*
* 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,54 +0,0 @@
/*
* 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.httpclient.ApacheHttpClient;
import org.apache.http.client.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.HttpClient5DisabledConditions;
import org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* @author Spencer Gibb
* @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttpClient.class)
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
@Conditional(HttpClient5DisabledConditions.class)
@Import(HttpClientFeignConfiguration.class)
class HttpClientFeignLoadBalancedConfiguration {
@Bean
@ConditionalOnMissingBean(Client.class)
public Client feignClient(CachingSpringLoadBalancerFactory cachingFactory,
SpringClientFactory clientFactory, HttpClient httpClient) {
ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
return new LoadBalancerFeignClient(delegate, cachingFactory, clientFactory);
}
}
@@ -1,146 +0,0 @@
/*
* 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.io.IOException;
import java.net.URI;
import com.netflix.client.ClientException;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.client.config.IClientConfig;
import feign.Client;
import feign.Request;
import feign.Response;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
/**
* @author Dave Syer
* @author Olga Maciaszek-Sharma
*
*/
public class LoadBalancerFeignClient implements Client {
static final Request.Options DEFAULT_OPTIONS = new Request.Options();
private final Client delegate;
private CachingSpringLoadBalancerFactory lbClientFactory;
private SpringClientFactory clientFactory;
public LoadBalancerFeignClient(Client delegate,
CachingSpringLoadBalancerFactory lbClientFactory,
SpringClientFactory clientFactory) {
this.delegate = delegate;
this.lbClientFactory = lbClientFactory;
this.clientFactory = clientFactory;
}
static URI cleanUrl(String originalUrl, String host) {
String newUrl = originalUrl;
if (originalUrl.startsWith("https://")) {
newUrl = originalUrl.substring(0, 8)
+ originalUrl.substring(8 + host.length());
}
else if (originalUrl.startsWith("http")) {
newUrl = originalUrl.substring(0, 7)
+ originalUrl.substring(7 + host.length());
}
StringBuffer buffer = new StringBuffer(newUrl);
if ((newUrl.startsWith("https://") && newUrl.length() == 8)
|| (newUrl.startsWith("http://") && newUrl.length() == 7)) {
buffer.append("/");
}
return URI.create(buffer.toString());
}
@Override
public Response execute(Request request, Request.Options options) throws IOException {
try {
URI asUri = URI.create(request.url());
String clientName = asUri.getHost();
URI uriWithoutHost = cleanUrl(request.url(), clientName);
FeignLoadBalancer.RibbonRequest ribbonRequest = new FeignLoadBalancer.RibbonRequest(
this.delegate, request, uriWithoutHost);
IClientConfig requestConfig = getClientConfig(options, clientName);
return lbClient(clientName)
.executeWithLoadBalancer(ribbonRequest, requestConfig).toResponse();
}
catch (ClientException e) {
IOException io = findIOException(e);
if (io != null) {
throw io;
}
throw new RuntimeException(e);
}
}
IClientConfig getClientConfig(Request.Options options, String clientName) {
IClientConfig requestConfig;
if (options == DEFAULT_OPTIONS) {
requestConfig = this.clientFactory.getClientConfig(clientName);
}
else {
requestConfig = new FeignOptionsClientConfig(options);
}
return requestConfig;
}
protected IOException findIOException(Throwable t) {
if (t == null) {
return null;
}
if (t instanceof IOException) {
return (IOException) t;
}
return findIOException(t.getCause());
}
public Client getDelegate() {
return this.delegate;
}
private FeignLoadBalancer lbClient(String clientName) {
return this.lbClientFactory.create(clientName);
}
static class FeignOptionsClientConfig extends DefaultClientConfigImpl {
FeignOptionsClientConfig(Request.Options options) {
setProperty(CommonClientConfigKey.ConnectTimeout,
options.connectTimeoutMillis());
setProperty(CommonClientConfigKey.ReadTimeout, options.readTimeoutMillis());
setProperty(CommonClientConfigKey.FollowRedirects,
options.isFollowRedirects());
}
@Override
public void loadProperties(String clientName) {
}
@Override
public void loadDefaultValues() {
}
}
}
@@ -1,49 +0,0 @@
/*
* 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.ribbon;
import feign.Client;
import feign.okhttp.OkHttpClient;
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.OkHttpFeignConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* @author Spencer Gibb
* @author Olga Maciaszek-Sharma
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OkHttpClient.class)
@ConditionalOnProperty("feign.okhttp.enabled")
@Import(OkHttpFeignConfiguration.class)
class OkHttpFeignLoadBalancedConfiguration {
@Bean
@ConditionalOnMissingBean(Client.class)
public Client feignClient(CachingSpringLoadBalancerFactory cachingFactory,
SpringClientFactory clientFactory, okhttp3.OkHttpClient okHttpClient) {
OkHttpClient delegate = new OkHttpClient(okHttpClient);
return new LoadBalancerFeignClient(delegate, cachingFactory, clientFactory);
}
}
@@ -1,141 +0,0 @@
/*
* 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.ribbon;
import java.io.IOException;
import java.net.URI;
import com.netflix.client.DefaultLoadBalancerRetryHandler;
import com.netflix.client.RequestSpecificRetryHandler;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import feign.Request;
import feign.Response;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRecoveryCallback;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy;
import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.RibbonProperties;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
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 FeignLoadBalancer} that leverages Spring Retry to retry failed requests.
*
* @author Ryan Baxter
* @author Gang Li
*/
public class RetryableFeignLoadBalancer extends FeignLoadBalancer
implements ServiceInstanceChooser {
private final LoadBalancedRetryFactory loadBalancedRetryFactory;
public RetryableFeignLoadBalancer(ILoadBalancer lb, IClientConfig clientConfig,
ServerIntrospector serverIntrospector,
LoadBalancedRetryFactory loadBalancedRetryFactory) {
super(lb, clientConfig, serverIntrospector);
this.loadBalancedRetryFactory = loadBalancedRetryFactory;
this.setRetryHandler(new DefaultLoadBalancerRetryHandler(clientConfig));
}
@Override
public RibbonResponse execute(final RibbonRequest request,
IClientConfig configOverride) throws IOException {
final Request.Options options;
if (configOverride != null) {
RibbonProperties ribbon = RibbonProperties.from(configOverride);
options = new Request.Options(ribbon.connectTimeout(this.connectTimeout),
ribbon.readTimeout(this.readTimeout));
}
else {
options = new Request.Options(this.connectTimeout, this.readTimeout);
}
final LoadBalancedRetryPolicy retryPolicy = this.loadBalancedRetryFactory
.createRetryPolicy(this.getClientName(), this);
RetryTemplate retryTemplate = new RetryTemplate();
BackOffPolicy backOffPolicy = this.loadBalancedRetryFactory
.createBackOffPolicy(this.getClientName());
retryTemplate.setBackOffPolicy(
backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
RetryListener[] retryListeners = this.loadBalancedRetryFactory
.createRetryListeners(this.getClientName());
if (retryListeners != null && retryListeners.length != 0) {
retryTemplate.setListeners(retryListeners);
}
retryTemplate.setRetryPolicy(retryPolicy == null ? new NeverRetryPolicy()
: new FeignRetryPolicy(request.toHttpRequest(), retryPolicy, this,
this.getClientName()));
return retryTemplate.execute(retryContext -> {
Request feignRequest = null;
// on retries the policy will choose the server and set it in the context
// extract the server and update the request being made
if (retryContext instanceof LoadBalancedRetryContext) {
ServiceInstance service = ((LoadBalancedRetryContext) retryContext)
.getServiceInstance();
if (service != null) {
feignRequest = ((RibbonRequest) request
.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);
}, new LoadBalancedRecoveryCallback<RibbonResponse, Response>() {
@Override
protected RibbonResponse createResponse(Response response, URI uri) {
return new RibbonResponse(uri, response);
}
});
}
@Override
public RequestSpecificRetryHandler getRequestSpecificRetryHandler(
FeignLoadBalancer.RibbonRequest request, IClientConfig requestConfig) {
return new RequestSpecificRetryHandler(false, false, this.getRetryHandler(),
requestConfig);
}
@Override
public ServiceInstance choose(String serviceId) {
return new RibbonLoadBalancerClient.RibbonServer(serviceId,
this.getLoadBalancer().chooseServer(serviceId));
}
}
@@ -1,49 +0,0 @@
/*
* 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.ribbon;
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 RibbonResponseStatusCodeException extends RetryableStatusCodeException {
private final Response response;
public RibbonResponseStatusCodeException(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;
}
}
@@ -0,0 +1,183 @@
/*
* Copyright 2015-2022 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.security;
import java.util.Arrays;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.http.AccessTokenRequiredException;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException;
import org.springframework.security.oauth2.client.token.AccessTokenProvider;
import org.springframework.security.oauth2.client.token.AccessTokenProviderChain;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
/**
* Pre-defined custom RequestInterceptor for Feign Requests. It uses the
* {@link OAuth2ClientContext OAuth2ClientContext} provided from the environment and
* construct a new header on the request before it is made by Feign.
*
* @author Joao Pedro Evangelista
* @author Tim Ysewyn
* @since 3.0.0
*/
@Deprecated // spring-security-oauth2 reached EOL
public class OAuth2FeignRequestInterceptor implements RequestInterceptor {
/**
* The name of the token.
*/
public static final String BEARER = "Bearer";
/**
* The name of the header.
*/
public static final String AUTHORIZATION = "Authorization";
private final OAuth2ClientContext oAuth2ClientContext;
private final OAuth2ProtectedResourceDetails resource;
private final String tokenType;
private final String header;
private AccessTokenProvider accessTokenProvider = new AccessTokenProviderChain(Arrays.<AccessTokenProvider>asList(
new AuthorizationCodeAccessTokenProvider(), new ImplicitAccessTokenProvider(),
new ResourceOwnerPasswordAccessTokenProvider(), new ClientCredentialsAccessTokenProvider()));
/**
* Default constructor which uses the provided OAuth2ClientContext and Bearer tokens
* within Authorization header.
* @param oAuth2ClientContext provided context
* @param resource type of resource to be accessed
*/
public OAuth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext,
OAuth2ProtectedResourceDetails resource) {
this(oAuth2ClientContext, resource, BEARER, AUTHORIZATION);
}
/**
* Fully customizable constructor for changing token type and header name, in cases of
* Bearer and Authorization is not the default such as "bearer", "authorization".
* @param oAuth2ClientContext current oAuth2 Context
* @param resource type of resource to be accessed
* @param tokenType type of token e.g. "token", "Bearer"
* @param header name of the header e.g. "Authorization", "authorization"
*/
public OAuth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext,
OAuth2ProtectedResourceDetails resource, String tokenType, String header) {
this.oAuth2ClientContext = oAuth2ClientContext;
this.resource = resource;
this.tokenType = tokenType;
this.header = header;
}
/**
* Create a template with the header of provided name and extracted extract.
*
* @see RequestInterceptor#apply(RequestTemplate)
*/
@Override
public void apply(RequestTemplate template) {
template.header(header); // Clears out the header, no "clear" method available.
template.header(header, extract(tokenType));
}
/**
* Extracts the token extract id the access token exists or returning an empty extract
* if there is no one on the context it may occasionally causes Unauthorized response
* since the token extract is empty.
* @param tokenType type name of token
* @return token value from context if it exists otherwise empty String
*/
protected String extract(String tokenType) {
OAuth2AccessToken accessToken = getToken();
return String.format("%s %s", tokenType, accessToken.getValue());
}
/**
* Extract the access token within the request or try to acquire a new one by
* delegating it to {@link #acquireAccessToken()}.
* @return valid token
*/
public OAuth2AccessToken getToken() {
OAuth2AccessToken accessToken = oAuth2ClientContext.getAccessToken();
if (accessToken == null || accessToken.isExpired()) {
try {
accessToken = acquireAccessToken();
}
catch (UserRedirectRequiredException e) {
oAuth2ClientContext.setAccessToken(null);
String stateKey = e.getStateKey();
if (stateKey != null) {
Object stateToPreserve = e.getStateToPreserve();
if (stateToPreserve == null) {
stateToPreserve = "NONE";
}
oAuth2ClientContext.setPreservedState(stateKey, stateToPreserve);
}
throw e;
}
}
return accessToken;
}
/**
* Try to acquire the token using a access token provider.
* @return valid access token
* @throws UserRedirectRequiredException in case the user needs to be redirected to an
* approval page or login page
*/
protected OAuth2AccessToken acquireAccessToken() throws UserRedirectRequiredException {
AccessTokenRequest tokenRequest = oAuth2ClientContext.getAccessTokenRequest();
if (tokenRequest == null) {
throw new AccessTokenRequiredException(
"Cannot find valid context on request for resource '" + resource.getId() + "'.", resource);
}
String stateKey = tokenRequest.getStateKey();
if (stateKey != null) {
tokenRequest.setPreservedState(oAuth2ClientContext.removePreservedState(stateKey));
}
OAuth2AccessToken existingToken = oAuth2ClientContext.getAccessToken();
if (existingToken != null) {
oAuth2ClientContext.setAccessToken(existingToken);
}
OAuth2AccessToken obtainableAccessToken;
obtainableAccessToken = accessTokenProvider.obtainAccessToken(resource, tokenRequest);
if (obtainableAccessToken == null || obtainableAccessToken.getValue() == null) {
throw new IllegalStateException(
" Access token provider returned a null token, which is illegal according to the contract.");
}
oAuth2ClientContext.setAccessToken(obtainableAccessToken);
return obtainableAccessToken;
}
public void setAccessTokenProvider(AccessTokenProvider accessTokenProvider) {
this.accessTokenProvider = accessTokenProvider;
}
}
@@ -0,0 +1,81 @@
/*
* Copyright 2015-2022 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.security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.AccessTokenProvider;
import org.springframework.security.oauth2.client.token.AccessTokenProviderChain;
import org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider;
/**
* Allows to customize pre-defined {@link OAuth2FeignRequestInterceptor} using configurer
* beans of class {@link OAuth2FeignRequestInterceptorConfigurer}. Each configurer
* instance can add {@link AccessTokenProvider} new {@link ClientHttpRequestInterceptor}
* instances.
*
* @author Wojciech Mąka
* @since 3.1.1
*/
public class OAuth2FeignRequestInterceptorBuilder {
private AccessTokenProvider accessTokenProvider;
private final List<ClientHttpRequestInterceptor> accessTokenProviderInterceptors = new ArrayList<>();
public OAuth2FeignRequestInterceptorBuilder() {
accessTokenProvider = new AccessTokenProviderChain(Arrays.<AccessTokenProvider>asList(
new AuthorizationCodeAccessTokenProvider(), new ImplicitAccessTokenProvider(),
new ResourceOwnerPasswordAccessTokenProvider(), new ClientCredentialsAccessTokenProvider()));
}
public OAuth2FeignRequestInterceptorBuilder withAccessTokenProviderInterceptors(
ClientHttpRequestInterceptor... interceptors) {
accessTokenProviderInterceptors.addAll(Arrays.asList(interceptors));
return this;
}
OAuth2FeignRequestInterceptor build(OAuth2ClientContext oAuth2ClientContext,
OAuth2ProtectedResourceDetails resource) {
if (OAuth2AccessTokenSupport.class.isAssignableFrom(accessTokenProvider.getClass())) {
((OAuth2AccessTokenSupport) accessTokenProvider).setInterceptors(accessTokenProviderInterceptors);
}
final OAuth2FeignRequestInterceptor feignRequestInterceptor = new OAuth2FeignRequestInterceptor(
oAuth2ClientContext, resource);
feignRequestInterceptor.setAccessTokenProvider(accessTokenProvider);
return feignRequestInterceptor;
}
public static OAuth2FeignRequestInterceptor buildWithConfigurers(OAuth2ClientContext oAuth2ClientContext,
OAuth2ProtectedResourceDetails resource, List<OAuth2FeignRequestInterceptorConfigurer> buildConfigurers) {
final OAuth2FeignRequestInterceptorBuilder builder = new OAuth2FeignRequestInterceptorBuilder();
for (OAuth2FeignRequestInterceptorConfigurer configurer : buildConfigurers) {
configurer.customize(builder);
}
return builder.build(oAuth2ClientContext, resource);
}
}
@@ -0,0 +1,35 @@
/*
* Copyright 2015-2022 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.security;
import org.springframework.security.oauth2.client.token.AccessTokenProvider;
/**
* Interface for configurer beans working with
* {@link OAuth2FeignRequestInterceptorBuilder} in order to provide custom interceptors
* for {@link AccessTokenProvider} managed internally by
* {@link OAuth2FeignRequestInterceptor}.
*
* @author Wojciech Mąka
* @since 3.1.1
*/
@FunctionalInterface
public interface OAuth2FeignRequestInterceptorConfigurer {
void customize(OAuth2FeignRequestInterceptorBuilder requestInterceptorBuilder);
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -29,7 +29,6 @@ import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import static feign.form.ContentProcessor.CRLF; import static feign.form.ContentProcessor.CRLF;
import static feign.form.util.PojoUtil.isUserPojo;
/** /**
* @author Darren Foong * @author Darren Foong
@@ -45,12 +44,10 @@ public abstract class AbstractFormWriter extends AbstractWriter {
@Override @Override
public void write(Output output, String key, Object object) throws EncodeException { public void write(Output output, String key, Object object) throws EncodeException {
try { try {
String string = new StringBuilder() String string = new StringBuilder().append("Content-Disposition: form-data; name=\"").append(key)
.append("Content-Disposition: form-data; name=\"").append(key) .append('"').append(CRLF).append("Content-Type: ").append(getContentType()).append("; charset=")
.append('"').append(CRLF).append("Content-Type: ") .append(output.getCharset().name()).append(CRLF).append(CRLF).append(writeAsString(object))
.append(getContentType()).append("; charset=") .toString();
.append(output.getCharset().name()).append(CRLF).append(CRLF)
.append(writeAsString(object)).toString();
output.write(string); output.write(string);
} }
@@ -1,85 +0,0 @@
/*
* 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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.zip.GZIPInputStream;
import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import org.springframework.cloud.openfeign.encoding.HttpEncoding;
/**
* When response is compressed as gzip, this decompresses and uses {@link SpringDecoder}
* to decode.
*
* @author Jaesik Kim
*/
public class DefaultGzipDecoder implements Decoder {
private Decoder decoder;
public DefaultGzipDecoder(Decoder decoder) {
this.decoder = decoder;
}
@Override
public Object decode(final Response response, Type type)
throws IOException, FeignException {
Collection<String> encoding = response.headers()
.containsKey(HttpEncoding.CONTENT_ENCODING_HEADER)
? response.headers().get(HttpEncoding.CONTENT_ENCODING_HEADER)
: null;
if (encoding != null) {
if (encoding.contains(HttpEncoding.GZIP_ENCODING)) {
String decompressedBody = decompress(response);
if (decompressedBody != null) {
Response decompressedResponse = response.toBuilder()
.body(decompressedBody.getBytes()).build();
return decoder.decode(decompressedResponse, type);
}
}
}
return decoder.decode(response, type);
}
private String decompress(Response response) throws IOException {
if (response.body() == null) {
return null;
}
try (GZIPInputStream gzipInputStream = new GZIPInputStream(
response.body().asInputStream());
BufferedReader reader = new BufferedReader(
new InputStreamReader(gzipInputStream, StandardCharsets.UTF_8))) {
String outputString = "";
String line;
while ((line = reader.readLine()) != null) {
outputString += line;
}
return outputString;
}
}
}
@@ -1,59 +0,0 @@
/*
* 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.codec.Decoder;
import feign.optionals.OptionalDecoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Configures Default Gzip Decoder.
*
* @author Jaesik Kim
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty("feign.compression.response.enabled")
// The OK HTTP client uses "transparent" compression.
// If the accept-encoding header is present, it disables transparent compression
@ConditionalOnMissingBean(type = "okhttp3.OkHttpClient")
@AutoConfigureAfter(FeignAutoConfiguration.class)
public class DefaultGzipDecoderConfiguration {
private ObjectFactory<HttpMessageConverters> messageConverters;
public DefaultGzipDecoderConfiguration(
ObjectFactory<HttpMessageConverters> messageConverters) {
this.messageConverters = messageConverters;
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty("feign.compression.response.useGzipDecoder")
public Decoder defaultGzipDecoder() {
return new OptionalDecoder(new ResponseEntityDecoder(
new DefaultGzipDecoder(new SpringDecoder(messageConverters))));
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2013-2022 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.function.Consumer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectProvider;
/**
* @author Olga Maciaszek-Sharma
*/
class EmptyObjectProvider<T> implements ObjectProvider<T> {
@Override
public T getObject(Object... args) throws BeansException {
return null;
}
@Override
public T getIfAvailable() throws BeansException {
return null;
}
@Override
public T getIfUnique() throws BeansException {
return null;
}
@Override
public T getObject() throws BeansException {
return null;
}
@Override
public void forEach(Consumer action) {
// do nothing
}
}
@@ -1,79 +0,0 @@
/*
* 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 com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixThreadPoolKey;
/**
* Convenience class for implementing feign fallbacks that return {@link HystrixCommand}.
* Also useful for return types of {@link rx.Observable} and
* {@link java.util.concurrent.Future}. For those return types, just call
* {@link FallbackCommand#observe()} or {@link FallbackCommand#queue()} respectively.
*
* @param <T> result type
* @author Spencer Gibb
*/
public class FallbackCommand<T> extends HystrixCommand<T> {
private T result;
public FallbackCommand(T result) {
this(result, "fallback");
}
protected FallbackCommand(T result, String groupname) {
super(HystrixCommandGroupKey.Factory.asKey(groupname));
this.result = result;
}
public FallbackCommand(T result, HystrixCommandGroupKey group) {
super(group);
this.result = result;
}
public FallbackCommand(T result, HystrixCommandGroupKey group,
int executionIsolationThreadTimeoutInMilliseconds) {
super(group, executionIsolationThreadTimeoutInMilliseconds);
this.result = result;
}
public FallbackCommand(T result, HystrixCommandGroupKey group,
HystrixThreadPoolKey threadPool) {
super(group, threadPool);
this.result = result;
}
public FallbackCommand(T result, HystrixCommandGroupKey group,
HystrixThreadPoolKey threadPool,
int executionIsolationThreadTimeoutInMilliseconds) {
super(group, threadPool, executionIsolationThreadTimeoutInMilliseconds);
this.result = result;
}
public FallbackCommand(T result, Setter setter) {
super(setter);
this.result = result;
}
@Override
protected T run() throws Exception {
return this.result;
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 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,7 +24,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @since 2.2.8 * @since 2.2.8
*/ */
@ConfigurationProperties("feign.encoder") @ConfigurationProperties("spring.cloud.openfeign.encoder")
public class FeignEncoderProperties { public class FeignEncoderProperties {
/** /**
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 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,15 +16,19 @@
package org.springframework.cloud.openfeign.support; package org.springframework.cloud.openfeign.support;
import java.time.Duration;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import feign.okhttp.OkHttpClient;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
/** /**
* @author Ryan Baxter * @author Ryan Baxter
* @author Nguyen Ky Thanh * @author Nguyen Ky Thanh
* @author Olga Maciaszek-Sharma
*/ */
@ConfigurationProperties(prefix = "feign.httpclient") @ConfigurationProperties(prefix = "spring.cloud.openfeign.httpclient")
public class FeignHttpClientProperties { public class FeignHttpClientProperties {
/** /**
@@ -88,8 +92,13 @@ public class FeignHttpClientProperties {
*/ */
private Hc5Properties hc5 = new Hc5Properties(); private Hc5Properties hc5 = new Hc5Properties();
/**
* Additional {@link OkHttpClient}-specific properties.
*/
private OkHttp okHttp = new OkHttp();
public int getConnectionTimerRepeat() { public int getConnectionTimerRepeat() {
return this.connectionTimerRepeat; return connectionTimerRepeat;
} }
public void setConnectionTimerRepeat(int connectionTimerRepeat) { public void setConnectionTimerRepeat(int connectionTimerRepeat) {
@@ -97,7 +106,7 @@ public class FeignHttpClientProperties {
} }
public boolean isDisableSslValidation() { public boolean isDisableSslValidation() {
return this.disableSslValidation; return disableSslValidation;
} }
public void setDisableSslValidation(boolean disableSslValidation) { public void setDisableSslValidation(boolean disableSslValidation) {
@@ -105,7 +114,7 @@ public class FeignHttpClientProperties {
} }
public int getMaxConnections() { public int getMaxConnections() {
return this.maxConnections; return maxConnections;
} }
public void setMaxConnections(int maxConnections) { public void setMaxConnections(int maxConnections) {
@@ -113,7 +122,7 @@ public class FeignHttpClientProperties {
} }
public int getMaxConnectionsPerRoute() { public int getMaxConnectionsPerRoute() {
return this.maxConnectionsPerRoute; return maxConnectionsPerRoute;
} }
public void setMaxConnectionsPerRoute(int maxConnectionsPerRoute) { public void setMaxConnectionsPerRoute(int maxConnectionsPerRoute) {
@@ -121,7 +130,7 @@ public class FeignHttpClientProperties {
} }
public long getTimeToLive() { public long getTimeToLive() {
return this.timeToLive; return timeToLive;
} }
public void setTimeToLive(long timeToLive) { public void setTimeToLive(long timeToLive) {
@@ -129,7 +138,7 @@ public class FeignHttpClientProperties {
} }
public TimeUnit getTimeToLiveUnit() { public TimeUnit getTimeToLiveUnit() {
return this.timeToLiveUnit; return timeToLiveUnit;
} }
public void setTimeToLiveUnit(TimeUnit timeToLiveUnit) { public void setTimeToLiveUnit(TimeUnit timeToLiveUnit) {
@@ -137,7 +146,7 @@ public class FeignHttpClientProperties {
} }
public boolean isFollowRedirects() { public boolean isFollowRedirects() {
return this.followRedirects; return followRedirects;
} }
public void setFollowRedirects(boolean followRedirects) { public void setFollowRedirects(boolean followRedirects) {
@@ -145,7 +154,7 @@ public class FeignHttpClientProperties {
} }
public int getConnectionTimeout() { public int getConnectionTimeout() {
return this.connectionTimeout; return connectionTimeout;
} }
public void setConnectionTimeout(int connectionTimeout) { public void setConnectionTimeout(int connectionTimeout) {
@@ -160,6 +169,14 @@ public class FeignHttpClientProperties {
this.hc5 = hc5; this.hc5 = hc5;
} }
public OkHttp getOkHttp() {
return okHttp;
}
public void setOkHttp(OkHttp okHttp) {
this.okHttp = okHttp;
}
public static class Hc5Properties { public static class Hc5Properties {
/** /**
@@ -203,11 +220,10 @@ public class FeignHttpClientProperties {
private TimeUnit socketTimeoutUnit = DEFAULT_SOCKET_TIMEOUT_UNIT; private TimeUnit socketTimeoutUnit = DEFAULT_SOCKET_TIMEOUT_UNIT;
public PoolConcurrencyPolicy getPoolConcurrencyPolicy() { public PoolConcurrencyPolicy getPoolConcurrencyPolicy() {
return this.poolConcurrencyPolicy; return poolConcurrencyPolicy;
} }
public void setPoolConcurrencyPolicy( public void setPoolConcurrencyPolicy(PoolConcurrencyPolicy poolConcurrencyPolicy) {
PoolConcurrencyPolicy poolConcurrencyPolicy) {
this.poolConcurrencyPolicy = poolConcurrencyPolicy; this.poolConcurrencyPolicy = poolConcurrencyPolicy;
} }
@@ -273,4 +289,24 @@ public class FeignHttpClientProperties {
} }
/**
* {@link OkHttpClient}-specific properties.
*/
public static class OkHttp {
/**
* {@link OkHttpClient} read timeout; defaults to 60 seconds.
*/
private Duration readTimeout = Duration.ofSeconds(60);
public Duration getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
}
}
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.
@@ -54,10 +54,8 @@ public final class FeignUtils {
return headers; return headers;
} }
static Collection<String> addTemplateParameter(Collection<String> possiblyNull, static Collection<String> addTemplateParameter(Collection<String> possiblyNull, String paramName) {
String paramName) { Collection<String> params = ofNullable(possiblyNull).map(ArrayList::new).orElse(new ArrayList<>());
Collection<String> params = ofNullable(possiblyNull).map(ArrayList::new)
.orElse(new ArrayList<>());
params.add(String.format("{%s}", paramName)); params.add(String.format("{%s}", paramName));
return params; return params;
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2016-2022 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.
@@ -14,25 +14,20 @@
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.cloud.openfeign.hystrix.security.app; package org.springframework.cloud.openfeign.support;
import java.util.concurrent.Callable; import java.util.List;
import java.util.function.Consumer;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import org.springframework.http.converter.HttpMessageConverter;
public class CustomConcurrenyStrategy extends HystrixConcurrencyStrategy { /**
* Allows customising {@link HttpMessageConverter} objects passed via {@link Consumer}
private boolean hookCalled; * parameter.
*
@Override * @author Olga Maciaszek-Sharma
public <T> Callable<T> wrapCallable(Callable<T> callable) { * @since 3.1.0
this.hookCalled = true; */
public interface HttpMessageConverterCustomizer extends Consumer<List<HttpMessageConverter<?>>> {
return super.wrapCallable(callable);
}
public boolean isHookCalled() {
return this.hookCalled;
}
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 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.

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