Compare commits

...
732 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
buildmaster 1005749eb5 Update SNAPSHOT to 2.2.9.RELEASE 2021-07-06 14:52:01 +00:00
Olga MaciaszekSharma 6de9fdd3e1 Merge remote-tracking branch 'origin/2.2.x' 2021-07-05 13:19:39 +02:00
Michal Domagala df1f982046 Fix for RetryableFeignBlockingLoadBalancerClient closes stream (#569) 2021-07-05 13:03:06 +02:00
Michal Domagala baf7cf95f2 Simplify Log.info logic (#556) 2021-07-05 12:43:59 +02:00
Olga MaciaszekSharma 45861dd657 Merge remote-tracking branch 'origin/2.2.x'. Refactor. 2021-07-05 12:09:23 +02:00
Olga MaciaszekSharma 00ea88c67f Fix typo. Refactor. 2021-07-05 11:55:41 +02:00
Olga MaciaszekSharma d897b18e16 Add missing author tags. Refactor. 2021-07-05 11:26:06 +02:00
Can Bezmen 8c08204c78 Issue #549
* Fixed: Form URL Encoded bug fixed.

Fixes gh-549.
2021-07-05 11:19:29 +02:00
Olga MaciaszekSharma 1f5bdd4224 Merge remote-tracking branch 'origin/2.2.x' 2021-06-10 16:08:39 +02:00
Olga MaciaszekSharma 2f43715f6f Change log level. Fixes gh-552. 2021-06-10 16:04:17 +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
Nick Smith 421df91a80 Filters out null matrix parameters 2021-05-24 15:58:27 +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 MaciaszekSharma ec1f2ad5bb Refactor FeignHalConfiguration to use HalMediaTypeConfiguration under the hood. Fixes gh-541. 2021-05-12 13:51:43 +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 5baa8c8ed5 Remove master references. 2021-04-26 19:24:36 +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
buildmaster 0684ee4bc2 Bumping versions to 2.2.9.BUILD-SNAPSHOT after release 2021-04-21 17:11:52 +00:00
buildmaster 0b34d89adc Going back to snapshots 2021-04-21 17:11:52 +00:00
buildmaster c33bc490cd Update SNAPSHOT to 2.2.8.RELEASE 2021-04-21 17:10:24 +00:00
Olga MaciaszekSharma d738b3b224 Upgrade Feign to 10.12. Fixes gh-530. 2021-04-21 10:23:38 +02:00
buildmaster 0c1d281970 Bumping versions 2021-04-20 21:33:18 +00:00
Olga MaciaszekSharma 26fb4deb18 Merge remote-tracking branch 'origin/2.2.x' 2021-04-20 17:28:31 +02:00
Olga MaciaszekSharma 0bf0426f60 Update GH actions setup. 2021-04-20 16:50:36 +02:00
Leandro Quiroga 9f9ce39789 Fix typo. 2021-04-20 16:50:18 +02:00
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 4d0caec7ee Fix checkstyle and formatting. 2021-04-13 15:17:00 +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 92f7ba9901 Fix GH actions setup 2021-04-13 15:08:27 +02:00
Olga MaciaszekSharma b2c208ba5f Fix GH actions setup 2021-04-13 15:08:00 +02:00
Olga MaciaszekSharma e2a54c1359 Fix GH actions setup 2021-04-13 15:04:10 +02:00
Olga MaciaszekSharma cdfd3695c2 Add GH actions build icon. 2021-04-13 15:03:23 +02:00
Olga MaciaszekSharma a5412cc872 Merge remote-tracking branch 'origin/2.2.x' 2021-04-13 14:54:18 +02:00
Olga MaciaszekSharma 59216f2f82 Switch to building the project with GH actions. 2021-04-13 14:53:48 +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
Sam Kruglov 4d827623f0 Add FeignClientBuilder.Builder#customize(FeignBuilderCustomizer) (#499) (#515) 2021-04-13 12:57:35 +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
Olga MaciaszekSharma 5e494aa196 Add more logging. Fixes gh-517. 2021-04-12 14:29:45 +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
Thanh e3439f38bc Add Apache HC5 client option (#498) 2021-03-11 14:14:34 +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
Hyeonmin Park 2a23b6d304 Support Pageable, Sort annotated as SpringQueryMap to use with RequestBody (#502) 2021-03-10 17:30: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 Maciaszek-Sharma 6b436c4133 Set followRedirects via properties. (#500) 2021-03-03 11:20:48 +01:00
Olga MaciaszekSharma 4b962e6170 Merge 2.2.x 2021-03-01 15:37:25 +01:00
Olga MaciaszekSharma b4fb3fe7b4 Refactor. 2021-03-01 15:35:49 +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 b8129f52b7 Use delegate in RetryableFeignLoadBalancer when url present. Fixes gh-494. 2021-03-01 15:19:20 +01:00
Olga MaciaszekSharma dcc45128b9 Merge remote-tracking branch 'origin/2.2.x' 2021-02-26 18:28:56 +01:00
Krishna Kumar Mishra a2b798c31a mentioning Spring Cloud OpenFeign instead of Sleuth (#497) 2021-02-26 18:28:12 +01:00
Olga MaciaszekSharma 4217a0c542 Merge remote-tracking branch 'origin/2.2.x' 2021-02-26 18:17:53 +01:00
Olga Maciaszek-Sharma 11fd7dc43e Use Feign naming convention for circuit names. (#496)
Fixes gh-484.
2021-02-26 18:09:29 +01:00
Olga 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 cf20710cad Improve charset determination (#491) 2021-02-25 09:42:18 +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 c92849e28e Allow using multiple qualifiers for feign clients. (#485)
* Allow using multiple qualifiers for feign clients. Fixes gh-471.
2021-02-18 13:28:18 +01:00
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
Tim Peeters a205afb88d Fixes #482 No bean found of type Targeter. (#483) 2021-02-16 16:28:39 +01:00
buildmaster 37e1c2fd11 Bumping versions to 2.2.8.BUILD-SNAPSHOT after release 2021-02-11 14:15:44 +00:00
buildmaster ce7a55a484 Going back to snapshots 2021-02-11 14:15:44 +00:00
buildmaster 10c6992935 Update SNAPSHOT to 2.2.7.RELEASE 2021-02-11 14:14:19 +00:00
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
Hyeonmin Park d87375e835 Encode Pageable.Sort with percent encoded comma. Fixes gh-440. (#467)
* Encode Pageable.Sort with percent encoded comma. Fixes gh-440.

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

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

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

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

* Fixes after review.
2021-01-18 11:11:32 +01:00
Olga Maciaszek-Sharma 14eb8a7bb1 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/src/main/asciidoc/_configprops.adoc
2021-01-14 16:02:02 +01:00
Olga Maciaszek-Sharma 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 a79d82584e Update docs. 2021-01-14 15:50:47 +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
Olga Maciaszek-Sharma ae3e3efb26 Add license link to README. 2021-01-14 15:21:21 +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 e32b10b60f Added support for Spring Cloud CircuitBreaker
fixes gh-279
2020-12-15 18:15:49 +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 89fb98daf7 Upgrade protobuf-java. 2020-12-01 17:30:13 +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 1a7917e2bb Add information about decodeSlash property to docs. 2020-12-01 17:08:43 +01:00
Olga Maciaszek-Sharma 49d3830276 Remove unnecessary keyword from recently modified class. 2020-12-01 17:02:09 +01:00
Ram Anaswara d419826ca0 Fix for Path variables with / are not url encoded
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractIntegrationTests.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java
2020-12-01 16:53:39 +01:00
Olga Maciaszek-Sharma 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 64d3f05e70 Allow overriding creating requests. Fixes gh-423. 2020-11-30 19:12:14 +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
Olga Maciaszek-Sharma 4d021fd3f8 Do not throw exceptions from @PreDestroy methods. Fixes gh-435. 2020-11-30 18:21:44 +01:00
matt62king a8bcda0b5b add customizer for feign builder (#289).
Fixes gh-436.

* add customizer for feign builder

* support @Order for customizers

* switch to annotation aware comparator for @Order support

* remove intermediate instances

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

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

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

The error reason is that `SubClient` is registered twice

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

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

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

* delete unused code

(cherry picked from commit 4df865d1d6)

* add file header

* Apply review

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

* Fixes gh-391 sentence reworded

* Fixes gh-391 fixed spelling

* Fixes gh-391 fixed code format

* Fixes gh-391 fixed sentence

* Fixes gh-391 fixed code

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

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

* Thread sleep was repalced with more verbose TimeUnit sleep

* Fixed more names of the clients.
2020-10-29 15:58:38 +01:00
Olga Maciaszek-Sharma 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 bc6c3b7bf2 Sort request interceptors. (#419) 2020-10-28 18:36:46 +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 f410385237 Upgrade jackson to 2.11.3. 2020-10-28 17:46:44 +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 a5ab3383c9 Rename new class. 2020-10-02 15:25:18 +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 dd518a812b Add support for load-balanced retries. (#408) 2020-10-01 20:20:24 +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 c3dcb1f376 Remove maven compiler plugin version to use the one provided by Boot instead. 2020-09-17 14:49:03 +02:00
Olga Maciaszek-Sharma 27e2775c5f Upgrade protobuf-java. 2020-09-17 14:30:54 +02:00
Olga Maciaszek-Sharma 83ef242406 Upgrade vavr. 2020-09-17 14:20:29 +02:00
Olga Maciaszek-Sharma 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 6534950ed2 Upgrade jakson. 2020-09-17 12:57:47 +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 e83593651c Clean up test. 2020-09-16 12:50:57 +02:00
Olga Maciaszek-Sharma 4cbf6da17b Adjust test to changes in commons. 2020-09-16 12:38:22 +02:00
liuzeyanga 5fea4f3b35 change "Sprig Cloud" to  "Spring Cloud" 2020-09-16 11:53:59 +02:00
buildmaster 36c06c97a6 Bumping versions to 2.2.6.BUILD-SNAPSHOT after release 2020-08-28 20:04:40 +00:00
buildmaster d6b021eaa4 Going back to snapshots 2020-08-28 20:04:40 +00:00
buildmaster c2430c0e29 Update SNAPSHOT to 2.2.5.RELEASE 2020-08-28 20:02:41 +00: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 b66e08fda8 Fix the docs. 2020-08-13 14:37:55 +02:00
spencergibb 84819e1328 Bumps s-c-build to 2.3.2.BUILD-SNAPSHOT 2020-08-03 13:21:35 -04:00
spencergibb b6422db8e9 ignores .sdkmanrc 2020-08-03 13:21:17 -04: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 4bf010e810 Ignore InvalidMediaTypeException when verifying if Multipart content. Fixes gh-363. (#388) 2020-08-03 10:02:05 +02:00
buildmaster bd671efed9 Bumping versions to 2.2.5.BUILD-SNAPSHOT after release 2020-07-31 20:53:35 +00:00
buildmaster bfd473cb8f Going back to snapshots 2020-07-31 20:53:35 +00:00
buildmaster 2f5d63a061 Update SNAPSHOT to 2.2.4.RELEASE 2020-07-31 20:51:47 +00:00
Olga Maciaszek-Sharma 62aa76fb97 Merge remote-tracking branch 'origin/2.2.x' 2020-07-30 16:24:25 +02:00
Olga Maciaszek-Sharma 14929cbfee Revert "Fix double @RequestMapping with empty value (#245)"
This reverts commit 0afb60a72a.

# Conflicts:
#	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/SpringMvcContractTests.java
2020-07-30 16:18: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 d3da7e16e8 Add CollectionFormat support (#371)
* Add CollectionFormat support. Fixes gh-146.

* Minor refactoring.

* Fix docs.
2020-07-17 15:05:21 +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 4e89dd1523 Annotate @FeignClient with @Inherited. Fixes gh-322. (#370) 2020-07-14 17:38:02 +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 63ba4d40ff Fix checkstyle. 2020-07-14 16:02:28 +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 06862ab090 Add test for @MockBean. Fixes gh-343. 2020-07-14 15:19:58 +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
Olga Maciaszek-Sharma 72784920d8 Fix read timeout (#369)
* Fix setting readTimeout and connectionTimeout separately from each other. Fixes gh-324.

* Refactor (remove superfluous keywords) and reformat.
2020-07-13 17:19:18 +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 bf13ae95c9 Remove superfluous conditional. Fixes gh-323. (#350) 2020-06-05 18:26:34 +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 af06086c30 Fix docs. 2020-06-05 16:28:25 +02:00
Marcin Grzejszczak 5497f5a37c Migrated to docs.spring.io & updated sc-build 2020-06-04 15:50:09 +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 12084de3a9 Fix docs. Fixes gh-340. 2020-06-04 14:54:38 +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
chang-chao 84cf97b391 update doc on default retrying behavior 2020-06-04 13:17:58 +02: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 3002643ee7 Bumping versions to 2.2.4.BUILD-SNAPSHOT after release 2020-05-28 17:53:50 +00:00
buildmaster b1ec55cb01 Going back to snapshots 2020-05-28 17:53:50 +00:00
buildmaster f0e0e7ea64 Update SNAPSHOT to 2.2.3.RELEASE 2020-05-28 17:52:11 +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
Olga Maciaszek-Sharma 7311e4abc8 Update README. 2020-05-27 20:14:00 +02:00
Olga Maciaszek-Sharma ad776a43b5 Add info on reactive-feign to docs. Fixes gh-313. 2020-05-27 20:13:33 +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
Olga Maciaszek-Sharma c85853ac9d Merge remote-tracking branch 'origin/2.2.x' into 2.2.x 2020-05-14 12:14:42 +02:00
Olga Maciaszek-Sharma 21986f5e92 Upgrade Feign. Fixes gh-333. 2020-05-14 12:14:31 +02:00
spencergibb f857cca5b3 Merge branch '2.2.x' 2020-05-13 15:29:43 -04:00
spencergibb 1929dae2d2 Adds FactoryBean.OBJECT_TYPE_ATTRIBUTE to registered feign clients.
Fixes gh-337
2020-05-13 15:27:12 -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 fc9b47c3b3 Merge branch 'cbezmen-2.2.x' into 2.2.x 2020-05-11 13:34:46 +02:00
Olga Maciaszek-Sharma e7932a6aae Merge branch '2.2.x' of https://github.com/cbezmen/spring-cloud-openfeign into cbezmen-2.2.x
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsConfiguration.java
2020-05-11 13:34:03 +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 25a988e1bf Add documentation for gh-132. 2020-05-11 13:25:39 +02:00
matt62king af103e0137 Ignore parent config option 2.2.x (#326)
* added support to disable feign parent configurations, fixes gh-132

* added feign context test

* added feign context test class

* fix documentation on feign client

* removed inherit parent setting from annotation gh-132

* fix cherry pick commits gh-132

* add unit test gh-132

* add unit test gh-132
2020-05-11 13:10:58 +02:00
Can Bezmen 06a55b8bcd Review changes. 2020-05-08 21:11:27 +03:00
Can Bezmen 090c85c7ed Documentation added. 2020-05-07 19:26:25 +03:00
Can Bezmen 88633c7f54 Change type of exception 2020-04-29 18:18:41 +03:00
Can Bezmen bb499ea823 Revert some code for code coverage and change test to mockito 2020-04-29 18:04:20 +03:00
Can Bezmen 0e1a579de5 Error log added for serialization and throw exception before serializing other sort objects 2020-04-29 16:18:22 +03:00
Can Bezmen b538d7f88c Checkstyle bug for license fixed. 2020-04-29 10:08:37 +03:00
Can Bezmen 525bb603f7 Fix sort problem for serialize and deserialize. Unit test added. 2020-04-29 08:52:13 +03:00
Can Bezmen ea3fb86690 Sort Support for feign pagination 2020-04-29 08:31:54 +03:00
Olga Maciaszek-Sharma 9a335536bc Update copyright comments dates. 2020-04-21 16:59:54 +02:00
Olga Maciaszek-Sharma f6cf14f257 Update copyright comments dates. 2020-04-21 16:48:35 +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
Darren Foong 59ba6b1bc6 Allow @RequestPart user-defined POJOs (#314)
* Add Pojo and failing test to FeignClientTests

* Add SpringPojoFormEncoder

* Fix configuration

* Update Pojo

* Implement multipartPojo

* Does not work if Pojo has one field: this is crazy

* Disable expansion for multipart/form-data

* Remove Pojo

* Tidy code

* Add testSinglePojoRequestPart

* Update testMultiplePojoRequestPart

* Update testMultiplePojoRequestPart

* Add testRequestPartWithListOfPojosAndListOfMultipartFiles

* Fix Checkstyle errors

* Update license year and authors

* Tidy isApplicable

* Refactor isApplicable

* Rename classes and methods

* Change variable names

* Rename PojoFormWriter to AbstractFormWriter

* Rename method

* Use ObjectProvider

* Change constructor of SpringEncoder to move SpringPojoFormEncoder to FeignClientsConfiguration

* Rename variables

* Remove unused variable

* Extract springEncoder() method

* Restore previous constructor

* Extract isMultipartFormData() method
2020-04-14 16:28:03 +02:00
Ryan Baxter 8f421ced21 Merge remote-tracking branch 'origin/2.2.x' 2020-04-13 16:59:00 -04:00
rvervaekandrvvaeke dd91dcdf8d Use property 'number' in JSON Page representation instead of 'page' (#320)
Fixes gh-237

Co-authored-by: rvvaeke <ruben.vervaeke@liantis.be>
2020-04-13 16:58:15 -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
Olga Maciaszek-Sharma 397130a935 Add information on SimpleDiscoveryClient. Fixes gh-295. 2020-03-27 13:02:07 +01:00
nekkiy f49db7233a 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 12:00:16 +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
Michael Cramer c281800ccd add support for an FeignErrorDecoderFactory in 2.2.x (#310)
* add support for an FeignErrorDecoderFactory
this factory will be used if no ErrorDecoder was found. This factory allows to create a ErrorDecoder based on the type. This fixes #308

* add assertions to make it more readable

* add test for checking to not overwrite an existing ErrorDecoder when provided in the configuration

* add test for checking to not overwrite an existing ErrorDecoder when provided in the configuration

* add test for checking to not overwrite an existing ErrorDecoder when provided in the configuration
2020-03-24 17:12:29 +01:00
Olga Maciaszek-Sharma 1de832e472 Fix typo. 2020-03-20 20:10:45 +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 db2e84ef06 Add test for passing @MatrixVariable without specified name. Add documentation for @MatrixVariable support. Fixes gh-307. 2020-03-20 19:58:47 +01:00
Spencer Gibb cd1cead7fd bumps build to 2.3.0.BUILD-SNAPSHOT 2020-03-19 12:00:35 -04:00
Spencer Gibb 1ad9a8a24f bumps build to 2.2.4.BUILD-SNAPSHOT 2020-03-18 18:16:24 -04:00
Spencer Gibb 06769c4705 Updates docs branches 2020-03-06 12:53:34 -05:00
Spencer Gibb f3c3b9073b ignores .flattened-pom.xml 2020-03-06 12:53:34 -05:00
Spencer Gibb df5d1d5079 removes .flattened-pom.xml 2020-03-06 12:53:34 -05:00
buildmaster 8666006bf4 Bumping versions to 2.2.3.BUILD-SNAPSHOT after release 2020-03-04 16:30:43 +00:00
buildmaster b5c8e6619e Going back to snapshots 2020-03-04 16:30:43 +00:00
buildmaster 6f09ae0824 Update SNAPSHOT to 2.2.2.RELEASE 2020-03-04 16:28:48 +00: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
Olga Maciaszek-Sharma c82b577d00 Upgrade feign to 10.7.4. (#292) 2020-02-05 14:37:35 +01:00
Ryan Baxter a2e968465a Merge remote-tracking branch 'origin/2.2.x' 2020-01-29 11:00:53 -05:00
Ryan Baxter eca40256d8 Merge remote-tracking branch 'origin/2.1.x' into 2.2.x 2020-01-29 11:00:20 -05:00
Ryan Baxter a85294a835 Add documentation about early initialization errors. Fixes #221 2020-01-29 10:57:58 -05:00
Ryan Baxter 6b656195ce Merge remote-tracking branch 'origin/2.2.x' 2020-01-29 10:39:48 -05:00
Ryan Baxter db778b5c74 Merge remote-tracking branch 'origin/2.1.x' into 2.2.x 2020-01-29 10:38:31 -05:00
Ryan Baxter 73a75fd8b2 Add appendix.adoc. Fixes #255 2020-01-29 10:38:13 -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
Aaron Whiteside 892e65e303 Fix GH-201: Multiple @RequestPart not Working (#258)
Summary of changes follows:

- Delegate ALL requestBody encoding where Content-Type is multipart/form-data to the SpringFormEncoder.
- Introduce RequestPartParameterProcessor to deal with @RequestPart annotations, adds parameters to MethodMetadata.formParams().
- Wrap HttpMessageConversionException in EncodeException.
- Add tests to verify expected behaviour.

However there still exists a gap in functionality where any user defined pojo will be serialized as a Map<String,String>, as there is currently no way for SpringFormEncoder to know about the Content-Type of the individual parts beyond MultipartFile, boxed primitive types (which are treated as text/plain) and other built-in types inherited from FormEncoder.
2020-01-23 15:02:21 +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
buildmaster 422dda0a75 Bumping versions 2020-01-21 14:06:45 +00:00
Olga Maciaszek-Sharma 3eabb0237e Add comment. 2020-01-20 17:32:19 +01:00
Olga Maciaszek-Sharma ada2cb7913 Revert "Add public delegate modifiers in order to avoid reflection in SC Sleuth."
This reverts commit 05b58e087e.
2020-01-20 17:31:13 +01:00
Olga Maciaszek-Sharma 05b58e087e Add public delegate modifiers in order to avoid reflection in SC Sleuth. 2020-01-20 17:00:56 +01:00
Olga Maciaszek-Sharma 80ecc9ac09 Make constructor public. Required for SC Sleuth gh-1528. 2020-01-20 14:28:30 +01:00
buildmaster bee97b8611 Bumping versions 2020-01-19 11:37:13 +00: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
matt62king 01d05227c8 Define custom AnnotatedParameterProcessors while keeping defaults, Fixes gh-111 (#268) 2020-01-13 21:32:17 -05:00
Aaron Whiteside 90400b9e43 Support for configuring the ExceptionPropagationPolicy (#261)
Can be configured via properties or as a `@Bean`.

Fixes GH-243
2020-01-13 20:02:40 -05:00
Michael Stummvoll b1e38db1e2 Update Javadoc for FeignClient.configuration() (#227)
Referring to @Configuration is a bit confusing. The referred class does not need the annotation, and actually using it could cause issues due the class additionally getting picked up by the component scan.
2020-01-13 15:56:47 -05:00
Olga Maciaszek-Sharma d77337bc79 Merge branch '2.1.x'
# Conflicts:
#	docs/pom.xml
#	pom.xml
#	spring-cloud-openfeign-core/pom.xml
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringEncoderTests.java
#	spring-cloud-openfeign-dependencies/pom.xml
#	spring-cloud-starter-openfeign/pom.xml
2020-01-09 18:04:04 +01:00
Olga Maciaszek-SharmaandAhmad Mozafarnia 80d2067134 Merge fix 255 to 21x (#273)
* Fix bug in SpringEncoder (#225)

This commit fixes a bug in the SpringEncoder that causes the bodyType to
be ignored and not passed to generic message converters.

Fixes gh-225

* Fix after cherry-pick.

* Add Ahmad Mozafarnia to authors.

* Refactor tests.

Co-authored-by: Ahmad Mozafarnia <ahmad.mozafarnia@gmail.com>
2020-01-09 17:59:15 +01:00
Olga Maciaszek-SharmaandAhmad Mozafarnia 887ceefa60 Merge fix gh 225 (#272)
* Fix bug in SpringEncoder (#225)

This commit fixes a bug in the SpringEncoder that causes the bodyType to
be ignored and not passed to generic message converters.

Fixes gh-225

* Refactor changes based on Olga Maciaszek's review

* Add Ahmad Mozafarnia to authors.

Co-authored-by: Ahmad Mozafarnia <ahmad.mozafarnia@gmail.com>
2020-01-09 15:16:51 +01:00
buildmaster 2b364367cb Bumping versions 2020-01-08 11:37:49 +00:00
Olga Maciaszek-Sharma 8aa4729537 Upgrade to 10.7.0. (#270) 2020-01-07 16:12:14 +01:00
buildmaster 41e9b55869 Bumping versions 2020-01-02 11:38:31 +00:00
matt62king 8a25b8bd63 Support matrix variable (#260)
* support for matrix variable

* support for matrix variable Fixes gh-117

* unit tests for matrix variable

* Correct JavaDoc fixes gh-117
2020-01-01 19:54:55 +01:00
buildmaster 774017db85 Bumping versions 2019-12-21 11:38:25 +00:00
buildmaster d1b50ec2ae Bumping versions to 2.2.2.BUILD-SNAPSHOT after release 2019-12-20 12:51:11 +00:00
buildmaster bde804c6a4 Going back to snapshots 2019-12-20 12:51:11 +00:00
buildmaster 0888d9ce8d Update SNAPSHOT to 2.2.1.RELEASE 2019-12-20 12:50:14 +00:00
buildmaster 1bc7542dc5 Bumping versions 2019-12-19 11:37:41 +00:00
kingj 68689182be Changing DefaultGzipDecoder's charset to UTF-8 (#250) 2019-12-16 10:29:21 -05:00
Olga Maciaszek-Sharma d5c176c5f4 Use delegate if absolute url provided. (#264)
Fixes gh-259
Fixes gh-257
2019-12-16 16:02:00 +01:00
buildmaster 38733043ae Bumping versions 2019-11-27 11:37:31 +00:00
buildmaster 1b21e3b639 Bumping versions 2019-11-26 11:37:19 +00:00
buildmaster 14e6806c1c Bumping versions to 2.2.1.BUILD-SNAPSHOT after release 2019-11-26 10:14:04 +00:00
buildmaster dd95dae352 Going back to snapshots 2019-11-26 10:14:04 +00:00
buildmaster c1c211efdb Update SNAPSHOT to 2.2.0.RELEASE 2019-11-26 10:13:18 +00:00
buildmaster ea69c30496 Bumping versions 2019-11-20 11:37:38 +00:00
Ryan Baxter f71b419d8d Update issue templates 2019-11-19 19:46:56 -05:00
Ryan Baxter 35bbb32e03 Create SECURITY.md 2019-11-19 19:46:21 -05:00
buildmaster f97cbb9a73 Bumping versions to 2.1.5.BUILD-SNAPSHOT after release 2019-11-18 15:11:21 +00:00
buildmaster de39e67e18 Going back to snapshots 2019-11-18 15:11:21 +00:00
buildmaster 78037a1161 Update SNAPSHOT to 2.1.4.RELEASE 2019-11-18 15:10:50 +00:00
Ryan Baxter 1ce5ca1ba8 Add proxyBeanMethods = false to configuration. Fixes #233 2019-11-14 12:42:43 -05:00
Ryan Baxter 59b34b23e9 Merge remote-tracking branch 'origin/2.1.x' 2019-11-13 10:42:48 -05:00
Ryan Baxter f01c46ab2e Use the context id if present in the HystrixTargeter (#247)
* Use the context id if present in the HystrixTargeter.  Fixes #173

* Remove resource class from circleci
2019-11-13 10:41:57 -05:00
buildmaster 6dc78c99c2 Going back to snapshots 2019-11-08 21:54:34 +00:00
buildmaster 3046af2b42 Update SNAPSHOT to 2.2.0.RC2 2019-11-08 21:54:01 +00:00
buildmaster 8973f4286b Bumping versions 2019-11-07 14:59:19 +00:00
Marcin Grzejszczak ef5f9d6858 Added maven flatten plugin 2019-11-07 14:37:32 +01:00
Olga Maciaszek-Sharma f661105e63 Fix gh 177 add sc loadbalancer support (#239)
* Add FeignBlockingLoadBalancerClient, configurations for default, apache
httpclient and okhttp setup. Add autoconfiguration. Init fix for gh-177.

* Fix SC loadbalancer dependencies.

* Fix generating Feign response when instance not found.

* Fix configuration.

* Add tests for FeignBlockingLoadBalancerClient and FeignLoadBalancerAutoConfiguration.

* Fix checkstyle and formatting.

* Refactor, add docs and javadocs.

* Fix author name.

* Fix docs after code review.
2019-11-06 19:06:39 +01:00
kingj bc10583bf3 Adding gzip support for Spring Decoder (#230)
* Adding gzip support for Spring Decoder

* Restoring test config

* Switch to medium resource class in circleci. (#231)

* Adding gzip support for Spring Decoder

* Restoring test config

* Creating extra property for Gzip Decoder

* Fixing requested changes and updating doc

* Missed one change request

* Removing some properties
2019-11-04 17:53:50 +01:00
buildmaster cb1ea20f3f Going back to snapshots 2019-10-24 20:48:10 +00:00
buildmaster 6bfc684967 Update SNAPSHOT to 2.2.0.RC1 2019-10-24 20:47:44 +00:00
Olga Maciaszek-Sharma 63a9245f13 Switch to medium resource class in circleci. (#231) 2019-10-16 18:38:29 +02:00
buildmaster 64d63cbb39 Going back to snapshots 2019-10-03 19:31:32 +00:00
buildmaster d963ebd0f0 Update SNAPSHOT to 2.2.0.M3 2019-10-03 19:31:06 +00:00
Robert Resch 1e1562b24a FeignClientBuilder.Builder should always return the generic builder (#215)
* FeignClientBuilder should always return the generic builder

* Test also FeignClientBuilder.Builder ContextId
2019-09-26 17:00:54 +02:00
buildmaster 7eb7067752 Bumping versions 2019-09-26 11:37:31 +00:00
李家奉 bc4bfb5b7a Fix FeignClientBuilder fallback (#197)
* fix FeignClientBuilder fallback

* Fix FeignClientBuilder fallback

* Fix FeignClientBuilder fallback

* Update FeignClientBuilderTests.java

* Update FeignClientBuilderTests.java

* Update FeignClientBuilderTests.java
2019-09-26 13:11:27 +02:00
Olga Maciaszek-Sharma 94977691b8 Merge remote-tracking branch 'origin/master' 2019-09-18 14:01:50 +02:00
Olga Maciaszek-Sharma b2791605b7 Upgrade feign-core to 10.4.0. Fixes gh-220. 2019-09-18 14:01:34 +02:00
Ryan Baxter 3e5d7f84aa Merge remote-tracking branch 'origin/2.1.x' 2019-09-17 17:18:23 -04:00
Ryan Baxter eecc51e695 Upgrade to OpenFeign 10.4.0. Fixes #220 2019-09-17 17:18:05 -04:00
Olga Maciaszek-Sharma 9dfc820306 Merge branch '2.1.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
2019-09-17 15:49:25 +02:00
Olga Maciaszek-Sharma c3fc93268c Remove spring.provides. 2019-09-17 15:47:39 +02:00
buildmaster ecfd1b4cee Bumping versions 2019-09-17 11:37:46 +00:00
Marcin Grzejszczak 5ce9fcf9f8 Added configprops; fixes gh-218 2019-09-10 15:29:19 +02:00
buildmaster 4e6c1b2d04 Bumping versions to 2.1.4.BUILD-SNAPSHOT after release 2019-09-09 19:16:42 +00:00
buildmaster d8cdade30f Going back to snapshots 2019-09-09 19:16:42 +00:00
buildmaster b16904f15e Update SNAPSHOT to 2.1.3.RELEASE 2019-09-09 19:15:23 +00:00
Olga Maciaszek-Sharma 21a2a59461 Remove unnecessary property. 2019-08-30 17:03:08 +02:00
Olga Maciaszek-Sharma 39dfa0ef7f Merge branch '2.1.x'
# Conflicts:
#	spring-cloud-openfeign-core/pom.xml
2019-08-30 16:57:50 +02:00
Olga Maciaszek-Sharma 96ae8479aa Remove unused jersey dependency. Add dependency version for okhttp. 2019-08-30 16:34:25 +02:00
Marcin Grzejszczak 37fd2d4448 Hardcoded the jersey-apache-client4 version 2019-08-30 09:30:00 +02:00
Ryan Baxter 6493eab98a Merge branch 'nertzy-docs-fully-qualify-http-client-bean-names' 2019-08-22 11:23:33 -04:00
Ryan Baxter caacee575c Polish 2019-08-22 11:23:05 -04:00
Ryan Baxter 8abbf0a343 Merge branch 'docs-fully-qualify-http-client-bean-names' of https://github.com/nertzy/spring-cloud-openfeign into nertzy-docs-fully-qualify-http-client-bean-names 2019-08-22 11:20:08 -04:00
buildmaster c32b8568cf Going back to snapshots 2019-08-14 15:04:54 +00:00
buildmaster 654479a696 Update SNAPSHOT to 2.2.0.M2 2019-08-14 15:03:56 +00:00
Spencer Gibb 35b9de7f6e Updates to support latest hateoas changes. 2019-08-01 13:11:43 -04:00
buildmaster 2294dee616 Bumping versions 2019-07-30 11:38:32 +00:00
Glosur 2cdc1aceeb Fix serialization of Pageable.unpaged 2019-07-29 16:49:19 +02:00
Marcin Grzejszczak dabbfb7220 Merge pull request #202 from Glosur/fix-unpaged-serialization
Fix serialization of Pageable.unpaged
2019-07-29 16:43:51 +02:00
Marcin Grzejszczak 3e069b41af Added symbolic link of index.adoc 2019-07-29 14:43:19 +02:00
Marcin Grzejszczak 9cf06153a8 Added symbolic link of index.adoc 2019-07-29 14:43:13 +02:00
Glosur ead4c47fcb Fix serialization of Pageable.unpaged 2019-07-28 21:55:30 +00:00
Ryan Baxter eda905684d Merge remote-tracking branch 'origin/2.1.x' 2019-07-24 11:12:53 -04:00
Ryan Baxter 2c73498398 Adding feign-mock to our dependency management 2019-07-24 11:11:25 -04:00
buildmaster ebd80b5115 Bumping versions 2019-07-23 10:51:04 +00:00
buildmaster 866d20d976 Going back to snapshots 2019-07-03 18:11:32 +00:00
buildmaster 0d891d284a Update SNAPSHOT to 2.2.0.M1 2019-07-03 18:10:51 +00:00
Spencer Gibb 27380898a8 Updates to 2.1.3.BUILD-SNAPSHOT and build to 2.1.7 2019-06-21 12:26:25 -04:00
buildmaster d5031f8618 Bumping versions to 2.1.4.BUILD-SNAPSHOT after release 2019-06-20 17:08:40 +00:00
buildmaster b5539198e6 Going back to snapshots 2019-06-20 17:08:40 +00:00
buildmaster 36d63a1b9f Update SNAPSHOT to 2.1.2.RELEASE 2019-06-20 17:07:59 +00:00
Ryan Baxter 9b8a3c6c1b Merge remote-tracking branch 'origin/2.1.x' 2019-06-13 20:06:00 -04:00
hectorespert 2e8a5833a9 Fix GH-127 add support for HATEOAS (#140)
* Fix gh-127, HATEOAS support

* Fix gh-127, HATEOAS support tests

* Add DefaultCurieProvider for HAL Jackson http converter
2019-06-13 20:04:25 -04:00
buildmaster c4284683ad Bumping versions to 2.1.3.BUILD-SNAPSHOT after release 2019-06-11 19:20:31 +00:00
buildmaster 21805a9989 Going back to snapshots 2019-06-11 19:20:30 +00:00
buildmaster b1a8917796 Update SNAPSHOT to 2.1.2.RELEASE 2019-06-11 19:19:38 +00:00
Zhan Bin f76a81fe6b Improve pageable parameter names. (#181)
Improve pageable parameter names by reusing spring boot properties.
2019-06-05 14:32:06 -04:00
Jánoky László Viktor 3a60921794 Overridable QueryMapEncoder (#183)
Added the possibility to override the default QueryMapEncoder by defining a custom one in the ApplicationContext.
2019-06-03 11:12:52 -04:00
Ryan Baxter e531539e77 Fixing formatting 2019-05-21 16:26:00 -04:00
Ryan Baxter 7afd62dd32 Merge branch 'master' of github.com:spring-cloud/spring-cloud-openfeign 2019-05-21 15:43:45 -04:00
Ryan Baxter 2e21175087 Formatting 2019-05-21 15:43:33 -04:00
Ryan Baxter 10dda1601e Remove test, as the framework now catches this case at startup. 2019-05-21 15:43:14 -04:00
Olga Maciaszek-Sharma 84b0d0ca40 Merge branch '2.1.x' 2019-05-17 10:54:28 +02:00
Olga Maciaszek-Sharma 15be7111ec Upgrade openfeign to 10.2.3 and feign-form to 3.8.0. (#185)
Fixes gh-143.
2019-05-17 10:53:05 +02:00
Olga Maciaszek-Sharma 50c799a4a0 Add sagan .adoc files. 2019-04-30 15:38:42 +02:00
Olga Maciaszek-Sharma aba2abba8a Merge branch '2.1.x'
# Conflicts:
#	pom.xml
#	spring-cloud-openfeign-dependencies/pom.xml
2019-04-02 18:00:43 +02:00
Olga Maciaszek-Sharma 35ec2913d9 Fix handling adding multiple parametrs for key. Fixes gh-171. (#172) 2019-04-02 17:55:20 +02:00
Ryan Baxter f6fee55411 Merge branch 'spring-operator-polish-urls-remaining-master' 2019-03-28 16:14:55 -04:00
Ryan Baxter 4092cb10cc Fixing tests 2019-03-28 16:14:38 -04:00
Ryan Baxter 0169a3c3f3 Merge branch 'polish-urls-remaining-master' of https://github.com/spring-operator/spring-cloud-openfeign into spring-operator-polish-urls-remaining-master 2019-03-28 16:08:17 -04:00
Ryan Baxter e04056be09 Merge branch 'spring-operator-polish-urls-remaining-2.1.x' into 2.1.x 2019-03-28 15:57:43 -04:00
Ryan Baxter 05893e57e7 Fixing test failures 2019-03-28 15:57:28 -04:00
Ryan Baxter 8e0fc92c48 Merge branch 'polish-urls-remaining-2.1.x' of https://github.com/spring-operator/spring-cloud-openfeign into spring-operator-polish-urls-remaining-2.1.x 2019-03-28 14:04:30 -04:00
Spring Operator 09f9382a51 URL Cleanup (#163)
This commit updates URLs to prefer the https protocol. Redirects are not followed to avoid accidentally expanding intentionally shortened URLs (i.e. if using a URL shortener).

# Fixed URLs

## Fixed But Review Recommended
These URLs were fixed, but the https status was not OK. However, the https status was the same as the http request or http redirected to an https URL, so they were migrated. Your review is recommended.

* [ ] http://www.puppycrawl.com/dtds/suppressions_1_1.dtd (404) with 1 occurrences migrated to:
  https://www.puppycrawl.com/dtds/suppressions_1_1.dtd ([https](https://www.puppycrawl.com/dtds/suppressions_1_1.dtd) result 404).

## Fixed Success
These URLs were switched to an https URL with a 2xx status. While the status was successful, your review is still recommended.

* [ ] http://maven.apache.org/xsd/maven-4.0.0.xsd with 5 occurrences migrated to:
  https://maven.apache.org/xsd/maven-4.0.0.xsd ([https](https://maven.apache.org/xsd/maven-4.0.0.xsd) result 200).

# Ignored
These URLs were intentionally ignored.

* http://maven.apache.org/POM/4.0.0 with 10 occurrences
* http://www.w3.org/2001/XMLSchema-instance with 5 occurrences
2019-03-28 12:52:33 -04:00
Spring Operator 1347724cdf URL Cleanup
This commit updates URLs to prefer the https protocol. Redirects are not followed to avoid accidentally expanding intentionally shortened URLs (i.e. if using a URL shortener).

# Fixed URLs

## Fixed But Review Recommended
These URLs were fixed, but the https status was not OK. However, the https status was the same as the http request or http redirected to an https URL, so they were migrated. Your review is recommended.

* [ ] http://foo.com:8000/ (ConnectTimeoutException) with 2 occurrences migrated to:
  https://foo.com:8000/ ([https](https://foo.com:8000/) result ConnectTimeoutException).
* [ ] http://foo.com:8000/abc/bcd.json (ConnectTimeoutException) with 1 occurrences migrated to:
  https://foo.com:8000/abc/bcd.json ([https](https://foo.com:8000/abc/bcd.json) result ConnectTimeoutException).
* [ ] http://compose.docker.io/ (UnknownHostException) with 1 occurrences migrated to:
  https://compose.docker.io/ ([https](https://compose.docker.io/) result UnknownHostException).
* [ ] http://tp/abc/bcd.json (UnknownHostException) with 1 occurrences migrated to:
  https://tp/abc/bcd.json ([https](https://tp/abc/bcd.json) result UnknownHostException).

## Fixed Success
These URLs were switched to an https URL with a 2xx status. While the status was successful, your review is still recommended.

* [ ] http://EditorConfig.org with 1 occurrences migrated to:
  https://EditorConfig.org ([https](https://EditorConfig.org) result 200).
* [ ] http://asciidoctor.org with 1 occurrences migrated to:
  https://asciidoctor.org ([https](https://asciidoctor.org) result 200).
* [ ] http://example.com with 2 occurrences migrated to:
  https://example.com ([https](https://example.com) result 200).
* [ ] http://github.com/ with 1 occurrences migrated to:
  https://github.com/ ([https](https://github.com/) result 200).
* [ ] http://projects.spring.io/spring-cloud/ with 1 occurrences migrated to:
  https://projects.spring.io/spring-cloud/ ([https](https://projects.spring.io/spring-cloud/) result 200).
* [ ] http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html with 2 occurrences migrated to:
  https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html ([https](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) result 200).
* [ ] http://plugins.jetbrains.com/plugin/6546 with 2 occurrences migrated to:
  https://plugins.jetbrains.com/plugin/6546 ([https](https://plugins.jetbrains.com/plugin/6546) result 301).
* [ ] http://raw.github.com/ with 1 occurrences migrated to:
  https://raw.github.com/ ([https](https://raw.github.com/) result 301).
* [ ] http://service.com with 1 occurrences migrated to:
  https://service.com ([https](https://service.com) result 301).
* [ ] http://eclipse.org with 1 occurrences migrated to:
  https://eclipse.org ([https](https://eclipse.org) result 302).
* [ ] http://eclipse.org/m2e/ with 2 occurrences migrated to:
  https://eclipse.org/m2e/ ([https](https://eclipse.org/m2e/) result 302).
* [ ] http://www.springsource.com/developer/sts with 1 occurrences migrated to:
  https://www.springsource.com/developer/sts ([https](https://www.springsource.com/developer/sts) result 302).

# Ignored
These URLs were intentionally ignored.

* http://PROD-SVC with 2 occurrences
* http://Url/ with 1 occurrences
* http://bad_hostname with 1 occurrences
* http://bar with 1 occurrences
* http://bar/ with 1 occurrences
* http://foo with 19 occurrences
* http://foo/ with 4 occurrences
* http://foo/?name=%7bcookie with 1 occurrences
* http://foo:7777/ with 1 occurrences
* http://good-name with 2 occurrences
* http://listener with 6 occurrences
* http://localhost with 11 occurrences
* http://localhost:8080/ with 1 occurrences
* http://localhost:8081/ with 1 occurrences
2019-03-26 03:45:19 -05:00
Ryan Baxter fff4975c1e Fixing test 2019-03-25 20:09:14 -04:00
Ryan Baxter ac45facf04 Updating dependencies 2019-03-25 19:22:39 -04:00
Spring Operator 5a54a612cf URL Cleanup (#158)
This commit updates URLs to prefer the https protocol. Redirects are not followed to avoid accidentally expanding intentionally shortened URLs (i.e. if using a URL shortener).

# Fixed URLs

## Fixed Success
These URLs were switched to an https URL with a 2xx status. While the status was successful, your review is still recommended.

* [ ] http://www.apache.org/licenses/ with 1 occurrences migrated to:
  https://www.apache.org/licenses/ ([https](https://www.apache.org/licenses/) result 200).
* [ ] http://www.apache.org/licenses/LICENSE-2.0 with 114 occurrences migrated to:
  https://www.apache.org/licenses/LICENSE-2.0 ([https](https://www.apache.org/licenses/LICENSE-2.0) result 200).
2019-03-25 09:32:27 -04:00
Spring Operator 75faca6c17 URL Cleanup (#157)
This commit updates URLs to prefer the https protocol. Redirects are not followed to avoid accidentally expanding intentionally shortened URLs (i.e. if using a URL shortener).

# Fixed URLs

## Fixed Success
These URLs were switched to an https URL with a 2xx status. While the status was successful, your review is still recommended.

* [ ] http://www.apache.org/licenses/ with 1 occurrences migrated to:
  https://www.apache.org/licenses/ ([https](https://www.apache.org/licenses/) result 200).
* [ ] http://www.apache.org/licenses/LICENSE-2.0 with 114 occurrences migrated to:
  https://www.apache.org/licenses/LICENSE-2.0 ([https](https://www.apache.org/licenses/LICENSE-2.0) result 200).
2019-03-21 16:35:12 -04:00
Spring Operator a81c53a55c URL Cleanup
This commit updates URLs to prefer the https protocol. Redirects are not followed to avoid accidentally expanding intentionally shortened URLs (i.e. if using a URL shortener).

# Fixed URLs

## Fixed But Review Recommended
These URLs were fixed, but the https status was not OK. However, the https status was the same as the http request or http redirected to an https URL, so they were migrated. Your review is recommended.

* [ ] http://foo.com:8000/ (ConnectTimeoutException) with 2 occurrences migrated to:
  https://foo.com:8000/ ([https](https://foo.com:8000/) result ConnectTimeoutException).
* [ ] http://foo.com:8000/abc/bcd.json (ConnectTimeoutException) with 1 occurrences migrated to:
  https://foo.com:8000/abc/bcd.json ([https](https://foo.com:8000/abc/bcd.json) result ConnectTimeoutException).
* [ ] http://PROD-SVC (UnknownHostException) with 2 occurrences migrated to:
  https://PROD-SVC ([https](https://PROD-SVC) result UnknownHostException).
* [ ] http://Url/ (UnknownHostException) with 1 occurrences migrated to:
  https://Url/ ([https](https://Url/) result UnknownHostException).
* [ ] http://bad_hostname (UnknownHostException) with 1 occurrences migrated to:
  https://bad_hostname ([https](https://bad_hostname) result UnknownHostException).
* [ ] http://bar (UnknownHostException) with 1 occurrences migrated to:
  https://bar ([https](https://bar) result UnknownHostException).
* [ ] http://bar/ (UnknownHostException) with 1 occurrences migrated to:
  https://bar/ ([https](https://bar/) result UnknownHostException).
* [ ] http://compose.docker.io/ (UnknownHostException) with 1 occurrences migrated to:
  https://compose.docker.io/ ([https](https://compose.docker.io/) result UnknownHostException).
* [ ] http://foo (UnknownHostException) with 19 occurrences migrated to:
  https://foo ([https](https://foo) result UnknownHostException).
* [ ] http://foo/ (UnknownHostException) with 4 occurrences migrated to:
  https://foo/ ([https](https://foo/) result UnknownHostException).
* [ ] http://foo/?name=%7bcookie (UnknownHostException) with 1 occurrences migrated to:
  https://foo/?name=%7bcookie ([https](https://foo/?name=%7bcookie) result UnknownHostException).
* [ ] http://foo:7777/ (UnknownHostException) with 1 occurrences migrated to:
  https://foo:7777/ ([https](https://foo:7777/) result UnknownHostException).
* [ ] http://good-name (UnknownHostException) with 2 occurrences migrated to:
  https://good-name ([https](https://good-name) result UnknownHostException).
* [ ] http://listener (UnknownHostException) with 6 occurrences migrated to:
  https://listener ([https](https://listener) result UnknownHostException).
* [ ] http://tp/abc/bcd.json (UnknownHostException) with 1 occurrences migrated to:
  https://tp/abc/bcd.json ([https](https://tp/abc/bcd.json) result UnknownHostException).
* [ ] http://www.puppycrawl.com/dtds/suppressions_1_1.dtd (404) with 1 occurrences migrated to:
  https://www.puppycrawl.com/dtds/suppressions_1_1.dtd ([https](https://www.puppycrawl.com/dtds/suppressions_1_1.dtd) result 404).

## Fixed Success
These URLs were switched to an https URL with a 2xx status. While the status was successful, your review is still recommended.

* [ ] http://EditorConfig.org with 1 occurrences migrated to:
  https://EditorConfig.org ([https](https://EditorConfig.org) result 200).
* [ ] http://asciidoctor.org with 1 occurrences migrated to:
  https://asciidoctor.org ([https](https://asciidoctor.org) result 200).
* [ ] http://example.com with 2 occurrences migrated to:
  https://example.com ([https](https://example.com) result 200).
* [ ] http://github.com/ with 1 occurrences migrated to:
  https://github.com/ ([https](https://github.com/) result 200).
* [ ] http://projects.spring.io/spring-cloud/ with 1 occurrences migrated to:
  https://projects.spring.io/spring-cloud/ ([https](https://projects.spring.io/spring-cloud/) result 200).
* [ ] http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html with 2 occurrences migrated to:
  https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html ([https](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) result 200).
* [ ] http://plugins.jetbrains.com/plugin/6546 with 2 occurrences migrated to:
  https://plugins.jetbrains.com/plugin/6546 ([https](https://plugins.jetbrains.com/plugin/6546) result 301).
* [ ] http://raw.github.com/ with 1 occurrences migrated to:
  https://raw.github.com/ ([https](https://raw.github.com/) result 301).
* [ ] http://service.com with 1 occurrences migrated to:
  https://service.com ([https](https://service.com) result 301).
* [ ] http://eclipse.org with 1 occurrences migrated to:
  https://eclipse.org ([https](https://eclipse.org) result 302).
* [ ] http://eclipse.org/m2e/ with 2 occurrences migrated to:
  https://eclipse.org/m2e/ ([https](https://eclipse.org/m2e/) result 302).
* [ ] http://www.springsource.com/developer/sts with 1 occurrences migrated to:
  https://www.springsource.com/developer/sts ([https](https://www.springsource.com/developer/sts) result 302).

# Ignored
These URLs were intentionally ignored.

* http://localhost with 11 occurrences
* http://localhost:8080/ with 1 occurrences
* http://localhost:8081/ with 1 occurrences
2019-03-20 15:47:23 -05:00
Spring Operator 43c53739cf URL Cleanup (#153)
This commit updates URLs to prefer the https protocol. Redirects are not followed to avoid accidentally expanding intentionally shortened URLs (i.e. if using a URL shortener).

# Fixed URLs

## Fixed But Review Recommended
These URLs were fixed, but the https status was not OK. However, the https status was the same as the http request or http redirected to an https URL, so they were migrated. Your review is recommended.

* http://www.puppycrawl.com/dtds/suppressions_1_1.dtd (404) with 1 occurrences migrated to:
  https://www.puppycrawl.com/dtds/suppressions_1_1.dtd ([https](https://www.puppycrawl.com/dtds/suppressions_1_1.dtd) result 404).

## Fixed Success
These URLs were switched to an https URL with a 2xx status. While the status was successful, your review is still recommended.

* http://maven.apache.org/xsd/maven-4.0.0.xsd with 5 occurrences migrated to:
  https://maven.apache.org/xsd/maven-4.0.0.xsd ([https](https://maven.apache.org/xsd/maven-4.0.0.xsd) result 200).

# Ignored
These URLs were intentionally ignored.

* http://maven.apache.org/POM/4.0.0 with 10 occurrences
* http://www.w3.org/2001/XMLSchema-instance with 5 occurrences
2019-03-20 10:29:58 -04:00
Spring Operator 115e87b6ce URL Cleanup (#144)
This commit updates URLs to prefer the https protocol. Redirects are not followed to avoid accidentally expanding intentionally shortened URLs (i.e. if using a URL shortener).

# Fixed URLs

## Fixed Success 
These URLs were switched to an https URL with a 2xx status. While the status was successful, your review is still recommended.

* http://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch migrated to:  
  https://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch ([https](https://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch) result 200).
* http://stackoverflow.com/questions/29300806/a-bash-script-to-check-if-a-string-is-present-in-a-comma-separated-list-of-strin migrated to:  
  https://stackoverflow.com/questions/29300806/a-bash-script-to-check-if-a-string-is-present-in-a-comma-separated-list-of-strin ([https](https://stackoverflow.com/questions/29300806/a-bash-script-to-check-if-a-string-is-present-in-a-comma-separated-list-of-strin) result 200).
* http://www.apache.org/licenses/LICENSE-2.0 migrated to:  
  https://www.apache.org/licenses/LICENSE-2.0 ([https](https://www.apache.org/licenses/LICENSE-2.0) result 200).

# Ignored
These URLs were intentionally ignored.

* http://maven.apache.org/POM/4.0.0
* http://maven.apache.org/xsd/maven-4.0.0.xsd
* http://www.w3.org/2001/XMLSchema-instance
2019-03-11 19:08:45 -04:00
Marcin Grzejszczak 33fa5b1b6b Bumped openfeign to 2.2.0 2019-03-08 11:56:51 +01:00
Marcin Grzejszczak 2633db6bde Polish 2019-03-07 18:23:08 +01:00
Marcin Grzejszczak 2c824ff39c HTTP to HTTPS 2019-03-07 13:52:20 +01:00
buildmaster 6f9e1f63dc Bumping versions to 2.1.2.BUILD-SNAPSHOT after release 2019-03-05 17:48:02 +00:00
buildmaster 7a6c0a42f6 Going back to snapshots 2019-03-05 17:48:02 +00:00
buildmaster d73c61f0f0 Update SNAPSHOT to 2.1.1.RELEASE 2019-03-05 17:47:11 +00:00
Spencer Gibb d01bcdf29c Adds support for Iterable but not Collection parameters.
This was removed as part of #48.

fixes gh-135
2019-03-04 17:48:23 -05:00
Marcin Grzejszczak 47f2850751 ConditionalOnClass on a method should not use a class 2019-02-27 14:48:33 +01:00
Ryan Baxter 702e1c7340 Merge branch 'Tcharl-1604' 2019-02-26 20:24:33 -05:00
Ryan Baxter 4ac6429152 Polishing checkstyle 2019-02-26 20:24:00 -05:00
charliemordant 6e0e63644b checkstyle rules applied to pageable support 2019-02-17 12:43:30 +01:00
charliemordant f8352de786 merge conflicts 2019-02-10 18:16:29 +01:00
Marcin Grzejszczak c8c7452848 Added checkstyle 2019-02-05 18:46:31 +01:00
Olga Maciaszek-Sharma 1f37891ffe Fixes gh-107 (#113)
* Fixes gh-107

* Remove unnecessary assignment.
2019-01-29 20:15:32 +01:00
charliemordant 505a83e6a4 registers PageJacksonModule in FeignClientConfiguration 2019-01-28 13:05:26 +01:00
charliemordant 76dbc7d21f Merge branch 'master' of github.com:spring-cloud/spring-cloud-openfeign into 1604 2019-01-28 09:29:26 +01:00
buildmaster b176e3a958 Bumping versions 2019-01-25 13:32:33 +00:00
buildmaster eb7e4d3082 Bumping versions to 2.1.1.BUILD-SNAPSHOT after release 2019-01-22 18:34:21 +00:00
buildmaster c76b02b8a3 Going back to snapshots 2019-01-22 18:34:20 +00:00
buildmaster c1418bafee Update SNAPSHOT to 2.1.0.RELEASE 2019-01-22 18:33:41 +00:00
Frank Pavageau 67fa03dcd9 Upgrade feign-form to 3.5.0 (#106)
The earlier versions are not compatible with Feign 10.1.0 when using the
form encoder.

Fixes #105
2019-01-18 16:09:46 -05:00
Spencer Gibb 5804d12511 Bumps spring cloud build to 2.1.2.BUILD-SNAPSHOT 2019-01-12 13:05:02 -05:00
charliemordant 23ec2a1c43 License headers 2019-01-07 17:20:44 +01:00
Ryan Baxter d148672e13 Merge remote-tracking branch 'origin/2.0.x' 2019-01-07 09:51:04 -05:00
Ryan Baxter a693c30930 Add null check for retry policy. Fixes #101 2019-01-07 09:49:36 -05:00
Piotr Smolarski e227808b9d Support Multiple Clients Using The Same Service (#90)
* Use serviceId as url target if present.

Fixes gh-67

* Code review fixes and improvements

* Fix test

* Add contextId to override bean name of feign client and its configuration.

* Add documentation

* Add contextId example to documentation
2019-01-07 09:35:48 -05:00
charliemordant 642d3e6961 Spring data pageable support 2018-12-30 01:47:55 +01:00
buildmaster 3051c4c1fd Going back to snapshots 2018-12-20 21:12:44 +00:00
buildmaster fb6676d634 Update SNAPSHOT to 2.1.0.RC3 2018-12-20 21:11:11 +00:00
Ryan Baxter c1bbb9cbb3 Updating API usage for Boot 2.1.x. 2018-12-18 16:18:06 -05:00
Spencer Gibb e65f78f06b Merge branch '2.0.x' 2018-12-18 14:49:49 -05:00
Ryan Baxter 4e7e187323 Fix bug where host contains protocol characters (#97)
Fixes #94
2018-12-18 14:48:31 -05:00
Olga Maciaszek-Sharma a1a45125ea Upgrade openfeign to 10.1.0 (#95)
Upgrade to OpenFeign 10.1.0
2018-12-13 18:03:35 +01:00
Ryan Baxter b00abe7b68 Fixing docs 2018-12-12 12:22:46 -05:00
buildmaster b9cb792820 Going back to snapshots 2018-12-11 21:52:28 +00:00
buildmaster a38ebe40c8 Update SNAPSHOT to 2.1.0.RC2 2018-12-11 21:51:44 +00:00
buildmaster a064530141 Going back to snapshots 2018-12-11 16:38:12 +00:00
buildmaster 61afb5dcd6 Update SNAPSHOT to 2.1.0.RC1 2018-12-11 16:37:40 +00:00
Ryan Baxter 20017afdca Merge remote-tracking branch 'origin/2.0.x' 2018-12-11 10:04:16 -05:00
wzslw 88a6682f46 Update pom.xml (#88)
Remove duplicate dependency
2018-12-11 10:02:58 -05:00
Ryan Baxter f267c2255b Merge remote-tracking branch 'origin/2.0.x' 2018-12-11 09:12:30 -05:00
Ryan Baxter dd7b869a12 Uncommenting assert 2018-12-10 12:30:03 -05:00
Momo d46fb3a92e Add support for feign's QueryMap annotation for Object mapping (#79)
* Add QueryMapParameterProcessor

* Add license to QueryMapParameterProcessor

* Use SpringQueryMap instead of QueryMap. Add test.

* Add documentation and license to SpringQueryMap

* SpringQueryMap docs

* Fix typos
2018-12-06 21:26:36 +01:00
buildmaster cc2fe823c3 Going back to snapshots 2018-11-18 09:42:08 +00:00
buildmaster 5ddd771ed5 Bumping versions to 2.0.3.BUILD-SNAPSHOT after release 2018-10-23 18:11:07 +00:00
buildmaster 9f9c41ab59 Going back to snapshots 2018-10-23 18:11:06 +00:00
buildmaster 4dd68ca2f2 Update SNAPSHOT to 2.0.2.RELEASE 2018-10-23 18:08:54 +00:00
Grant Hutchins ca55e95c8f Docs: Fully qualify names for HTTP client beans
This addresses the ambiguity around whether to provide a Bean of feign.okhttp.OkHttpClient or okhttp3.OkHttpClient
2018-10-10 14:25:59 -05:00
Ryan Baxter af094d0bfc Remove rogue content in docs 2018-10-02 16:41:14 -04:00
250 changed files with 20789 additions and 8929 deletions
-39
View File
@@ -1,39 +0,0 @@
version: 2
jobs:
build:
docker:
- image: springcloud/pipeline-base
environment:
_JAVA_OPTIONS: "-Xms1024m -Xmx2048m"
TERM: dumb
branches:
ignore:
- gh-pages # list of branches to ignore
resource_class: large
steps:
- checkout
- restore_cache:
key: sc-openfeign-{{ .Branch }}
- run:
name: "Download dependencies"
command: ./mvnw -s .settings.xml -U --fail-never dependency:go-offline || true
- save_cache:
key: sc-openfeign-{{ .Branch }}
paths:
- ~/.m2
- run:
name: "Running build"
command: ./mvnw -s .settings.xml clean org.jacoco:jacoco-maven-plugin:prepare-agent install -U -P sonar -nsu --batch-mode -Dmaven.test.redirectTestOutputToFile=true -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- run:
name: "Aggregate test results"
when: always
command: |
mkdir -p $CIRCLE_TEST_REPORTS/junit/
find . -type f -regex ".*/target/.*-reports/.*" -exec cp {} $CIRCLE_TEST_REPORTS/junit/ \;
bash <(curl -s https://codecov.io/bash)
- store_artifacts:
path: /junit/
destination: artifacts
- store_test_results:
path: /junit/
destination: testartifacts
+14
View File
@@ -0,0 +1,14 @@
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
[*]
indent_style = tab
indent_size = 4
end_of_line = lf
insert_final_newline = true
[*.yml]
indent_style = space
indent_size = 2
+6 -6
View File
@@ -3,7 +3,7 @@
Spring Cloud is released under the non-restrictive Apache 2.0 license, Spring Cloud is released under the non-restrictive Apache 2.0 license,
and follows a very standard Github development process, using Github and follows a very standard Github development process, using Github
tracker for issues and merging pull requests into master. If you want tracker for issues and merging pull requests into main. If you want
to contribute even something trivial please do not hesitate, but to contribute even something trivial please do not hesitate, but
follow the guidelines below. follow the guidelines below.
@@ -17,7 +17,7 @@ given the ability to merge pull requests.
## Code of Conduct ## Code of Conduct
This project adheres to the Contributor Covenant [code of This project adheres to the Contributor Covenant [code of
conduct](https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report conduct](https://github.com/spring-cloud/spring-cloud-build/blob/main/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report
unacceptable behavior to spring-code-of-conduct@pivotal.io. unacceptable behavior to spring-code-of-conduct@pivotal.io.
## Code Conventions and Housekeeping ## Code Conventions and Housekeeping
@@ -27,8 +27,8 @@ added after the original pull request but before a merge.
* Use the Spring Framework code format conventions. If you use Eclipse * Use the Spring Framework code format conventions. If you use Eclipse
you can import formatter settings using the you can import formatter settings using the
`eclipse-code-formatter.xml` file from the `eclipse-code-formatter.xml` file from the
[Spring Cloud Build](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml) project. If using IntelliJ, you can use the [Spring Cloud Build](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/spring-cloud-dependencies-parent/eclipse-code-formatter.xml) project. If using IntelliJ, you can use the
[Eclipse Code Formatter Plugin](http://plugins.jetbrains.com/plugin/6546) to import the same file. [Eclipse Code Formatter Plugin](https://plugins.jetbrains.com/plugin/6546) to import the same file.
* Make sure all new `.java` files to have a simple Javadoc class comment with at least an * Make sure all new `.java` files to have a simple Javadoc class comment with at least an
`@author` tag identifying you, and preferably at least a paragraph on what the class is `@author` tag identifying you, and preferably at least a paragraph on what the class is
for. for.
@@ -38,8 +38,8 @@ added after the original pull request but before a merge.
than cosmetic changes). than cosmetic changes).
* Add some Javadocs and, if you change the namespace, some XSD doc elements. * Add some Javadocs and, if you change the namespace, some XSD doc elements.
* A few unit tests would help a lot as well -- someone has to do it. * A few unit tests would help a lot as well -- someone has to do it.
* If no-one else is using your branch, please rebase it against the current master (or * If no-one else is using your branch, please rebase it against the current main (or
other target branch in the main project). other target branch in the main project).
* When writing a commit message please follow [these conventions](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html), * When writing a commit message please follow [these conventions](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html),
if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit
message (where XXXX is the issue number). message (where XXXX is the issue number).
+17
View File
@@ -0,0 +1,17 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
Please provide details of the problem, including the version of Spring Cloud that you
are using.
**Sample**
If possible, please provide a test case or sample application that reproduces
the problem. This makes it much easier for us to diagnose the problem and to verify that
we have fixed it.
+20
View File
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+33
View File
@@ -0,0 +1,33 @@
# This workflow will build a Java project with Maven
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Build
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
java: ["17"]
steps:
- uses: actions/checkout@v2
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v2
with:
distribution: 'zulu'
java-version: ${{ matrix.java }}
cache: 'maven'
- name: Build with Maven
run: ./mvnw clean install -B -U -P sonar
- uses: codecov/codecov-action@v1
with:
fail_ci_if_error: true
+3
View File
@@ -18,3 +18,6 @@ _site/
.shelf .shelf
*.swp *.swp
*.swo *.swo
.vscode/
.flattened-pom.xml
+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
+65 -63
View File
@@ -1,66 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<settings> <settings>
<servers> <servers>
<server> <server>
<id>repo.spring.io</id> <id>repo.spring.io</id>
<username>${env.CI_DEPLOY_USERNAME}</username> <username>${env.CI_DEPLOY_USERNAME}</username>
<password>${env.CI_DEPLOY_PASSWORD}</password> <password>${env.CI_DEPLOY_PASSWORD}</password>
</server> </server>
</servers> </servers>
<profiles> <profiles>
<profile> <profile>
<!-- <!--
N.B. this profile is only here to support users and IDEs that do not use Maven 3.3. N.B. this profile is only here to support users and IDEs that do not use Maven 3.3.
It isn't needed on the command line if you use the wrapper script (mvnw) or if you use It isn't needed on the command line if you use the wrapper script (mvnw) or if you use
a native Maven with the right version. Eclipse users should points their Maven tooling to a native Maven with the right version. Eclipse users should points their Maven tooling to
this settings file, or copy the profile into their ~/.m2/settings.xml. this settings file, or copy the profile into their ~/.m2/settings.xml.
--> -->
<id>spring</id> <id>spring</id>
<activation><activeByDefault>true</activeByDefault></activation> <activation>
<repositories> <activeByDefault>true</activeByDefault>
<repository> </activation>
<id>spring-snapshots</id> <repositories>
<name>Spring Snapshots</name> <repository>
<url>http://repo.spring.io/libs-snapshot-local</url> <id>spring-snapshots</id>
<snapshots> <name>Spring Snapshots</name>
<enabled>true</enabled> <url>https://repo.spring.io/libs-snapshot-local</url>
</snapshots> <snapshots>
</repository> <enabled>true</enabled>
<repository> </snapshots>
<id>spring-milestones</id> </repository>
<name>Spring Milestones</name> <repository>
<url>http://repo.spring.io/libs-milestone-local</url> <id>spring-milestones</id>
<snapshots> <name>Spring Milestones</name>
<enabled>false</enabled> <url>https://repo.spring.io/libs-milestone-local</url>
</snapshots> <snapshots>
</repository> <enabled>false</enabled>
<repository> </snapshots>
<id>spring-releases</id> </repository>
<name>Spring Releases</name> <repository>
<url>http://repo.spring.io/release</url> <id>spring-releases</id>
<snapshots> <name>Spring Releases</name>
<enabled>false</enabled> <url>https://repo.spring.io/release</url>
</snapshots> <snapshots>
</repository> <enabled>false</enabled>
</repositories> </snapshots>
<pluginRepositories> </repository>
<pluginRepository> </repositories>
<id>spring-snapshots</id> <pluginRepositories>
<name>Spring Snapshots</name> <pluginRepository>
<url>http://repo.spring.io/libs-snapshot-local</url> <id>spring-snapshots</id>
<snapshots> <name>Spring Snapshots</name>
<enabled>true</enabled> <url>https://repo.spring.io/libs-snapshot-local</url>
</snapshots> <snapshots>
</pluginRepository> <enabled>true</enabled>
<pluginRepository> </snapshots>
<id>spring-milestones</id> </pluginRepository>
<name>Spring Milestones</name> <pluginRepository>
<url>http://repo.spring.io/libs-milestone-local</url> <id>spring-milestones</id>
<snapshots> <name>Spring Milestones</name>
<enabled>false</enabled> <url>https://repo.spring.io/libs-milestone-local</url>
</snapshots> <snapshots>
</pluginRepository> <enabled>false</enabled>
</pluginRepositories> </snapshots>
</profile> </pluginRepository>
</profiles> </pluginRepositories>
</profile>
</profiles>
</settings> </settings>
View File
+2 -2
View File
@@ -1,7 +1,7 @@
Apache License Apache License
Version 2.0, January 2004 Version 2.0, January 2004
http://www.apache.org/licenses/ https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
@@ -193,7 +193,7 @@
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
+233 -27
View File
@@ -1,11 +1,35 @@
// Do not edit this file (e.g. go instead to src/main/asciidoc) ////
DO NOT EDIT THIS FILE. IT WAS GENERATED.
Manual changes to this file will be lost when it is generated again.
Edit the files in the src/main/asciidoc/ directory instead.
////
image:https://circleci.com/gh/spring-cloud/spring-cloud-openfeign.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-openfeign"]
image:https://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"] image::https://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://api.codacy.com/project/badge/Grade/97b04c4e609c4b4f86b415e4437a6484["Codacy code quality", link="https://www.codacy.com/app/Spring-Cloud/spring-cloud-openfeign?utm_source=github.com&utm_medium=referral&utm_content=spring-cloud/spring-cloud-openfeign&utm_campaign=Badge_Grade"] image:https://api.codacy.com/project/badge/Grade/97b04c4e609c4b4f86b415e4437a6484["Codacy code quality", link="https://www.codacy.com/app/Spring-Cloud/spring-cloud-openfeign?utm_source=github.com&utm_medium=referral&utm_content=spring-cloud/spring-cloud-openfeign&utm_campaign=Badge_Grade"]
:doctype: book
:idprefix:
:idseparator: -
:toc: left
:toclevels: 4
:tabsize: 4
:numbered:
:sectanchors:
:sectnums:
:icons: font
:hide-uri-scheme:
:docinfo: shared,private
:sc-ext: java
:project-full-name: Spring Cloud OpenFeign
:all: {asterisk}{asterisk}
:core_path: {project-root}/spring-cloud-openfeign-core
This project provides OpenFeign integrations for Spring Boot apps through autoconfiguration This project provides OpenFeign integrations for Spring Boot apps through autoconfiguration
and binding to the Spring Environment and other Spring programming model idioms. and binding to the Spring Environment and other Spring programming model idioms.
@@ -16,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
@@ -42,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
http://compose.docker.io/[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
@@ -73,13 +84,18 @@ a modified file in the correct place. Just commit it and push the change.
=== Working with the code === Working with the code
If you don't have an IDE preference we would recommend that you use If you don't have an IDE preference we would recommend that you use
http://www.springsource.com/developer/sts[Spring Tools Suite] or https://www.springsource.com/developer/sts[Spring Tools Suite] or
http://eclipse.org[Eclipse] when working with the code. We use the https://eclipse.org[Eclipse] when working with the code. We use the
http://eclipse.org/m2e/[m2eclipse] eclipse plugin for maven support. Other IDEs and tools https://eclipse.org/m2e/[m2eclipse] eclipse plugin for maven support. Other IDEs and tools
should also work without issue as long as they use Maven 3.3.3 or better. should also work without issue as long as they use Maven 3.3.3 or better.
==== Activate the Spring Maven profile
Spring Cloud projects require the 'spring' Maven profile to be activated to resolve
the spring milestone and snapshot repositories. Use your preferred IDE to set this
profile to be active, or you may experience build errors.
==== Importing into eclipse with m2eclipse ==== Importing into eclipse with m2eclipse
We recommend the http://eclipse.org/m2e/[m2eclipse] eclipse plugin when working with We recommend the https://eclipse.org/m2e/[m2eclipse] eclipse plugin when working with
eclipse. If you don't already have m2eclipse installed it is available from the "eclipse eclipse. If you don't already have m2eclipse installed it is available from the "eclipse
marketplace". marketplace".
@@ -108,6 +124,8 @@ from the `file` menu.
== Contributing == Contributing
:spring-cloud-build-branch: master
Spring Cloud is released under the non-restrictive Apache 2.0 license, Spring Cloud is released under the non-restrictive Apache 2.0 license,
and follows a very standard Github development process, using Github and follows a very standard Github development process, using Github
tracker for issues and merging pull requests into master. If you want tracker for issues and merging pull requests into master. If you want
@@ -136,7 +154,7 @@ added after the original pull request but before a merge.
`eclipse-code-formatter.xml` file from the `eclipse-code-formatter.xml` file from the
https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml[Spring https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml[Spring
Cloud Build] project. If using IntelliJ, you can use the Cloud Build] project. If using IntelliJ, you can use the
http://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter https://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter
Plugin] to import the same file. Plugin] to import the same file.
* Make sure all new `.java` files to have a simple Javadoc class comment with at least an * Make sure all new `.java` files to have a simple Javadoc class comment with at least an
`@author` tag identifying you, and preferably at least a paragraph on what the class is `@author` tag identifying you, and preferably at least a paragraph on what the class is
@@ -149,6 +167,194 @@ added after the original pull request but before a merge.
* A few unit tests would help a lot as well -- someone has to do it. * A few unit tests would help a lot as well -- someone has to do it.
* If no-one else is using your branch, please rebase it against the current master (or * If no-one else is using your branch, please rebase it against the current master (or
other target branch in the main project). other target branch in the main project).
* When writing a commit message please follow http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions], * When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions],
if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit
message (where XXXX is the issue number). message (where XXXX is the issue number).
=== Checkstyle
Spring Cloud Build comes with a set of checkstyle rules. You can find them in the `spring-cloud-build-tools` module. The most notable files under the module are:
.spring-cloud-build-tools/
----
└── src
   ├── checkstyle
   │   └── checkstyle-suppressions.xml <3>
   └── main
   └── resources
   ├── checkstyle-header.txt <2>
   └── checkstyle.xml <1>
----
<1> Default Checkstyle rules
<2> File header setup
<3> Default suppression rules
==== Checkstyle configuration
Checkstyle rules are *disabled by default*. To add checkstyle to your project just define the following properties and plugins.
.pom.xml
----
<properties>
<maven-checkstyle-plugin.failsOnError>true</maven-checkstyle-plugin.failsOnError> <1>
<maven-checkstyle-plugin.failsOnViolation>true
</maven-checkstyle-plugin.failsOnViolation> <2>
<maven-checkstyle-plugin.includeTestSourceDirectory>true
</maven-checkstyle-plugin.includeTestSourceDirectory> <3>
</properties>
<build>
<plugins>
<plugin> <4>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
</plugin>
<plugin> <5>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
<reporting>
<plugins>
<plugin> <5>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</reporting>
</build>
----
<1> Fails the build upon Checkstyle errors
<2> Fails the build upon Checkstyle violations
<3> Checkstyle analyzes also the test sources
<4> Add the Spring Java Format plugin that will reformat your code to pass most of the Checkstyle formatting rules
<5> Add checkstyle plugin to your build and reporting phases
If you need to suppress some rules (e.g. line length needs to be longer), then it's enough for you to define a file under `${project.root}/src/checkstyle/checkstyle-suppressions.xml` with your suppressions. Example:
.projectRoot/src/checkstyle/checkstyle-suppresions.xml
----
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Puppy Crawl//DTD Suppressions 1.1//EN"
"https://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
<suppress files=".*ConfigServerApplication\.java" checks="HideUtilityClassConstructor"/>
<suppress files=".*ConfigClientWatch\.java" checks="LineLengthCheck"/>
</suppressions>
----
It's advisable to copy the `${spring-cloud-build.rootFolder}/.editorconfig` and `${spring-cloud-build.rootFolder}/.springformat` to your project. That way, some default formatting rules will be applied. You can do so by running this script:
```bash
$ curl https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/.editorconfig -o .editorconfig
$ touch .springformat
```
=== IDE setup
==== Intellij IDEA
In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin.
The following files can be found in the https://github.com/spring-cloud/spring-cloud-build/tree/master/spring-cloud-build-tools[Spring Cloud Build] project.
.spring-cloud-build-tools/
----
└── src
   ├── checkstyle
   │   └── checkstyle-suppressions.xml <3>
   └── main
   └── resources
   ├── checkstyle-header.txt <2>
   ├── checkstyle.xml <1>
   └── intellij
      ├── Intellij_Project_Defaults.xml <4>
      └── Intellij_Spring_Boot_Java_Conventions.xml <5>
----
<1> Default Checkstyle rules
<2> File header setup
<3> Default suppression rules
<4> Project defaults for Intellij that apply most of Checkstyle rules
<5> Project style conventions for Intellij that apply most of Checkstyle rules
.Code style
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-code-style.png[Code style]
Go to `File` -> `Settings` -> `Editor` -> `Code style`. There click on the icon next to the `Scheme` section. There, click on the `Import Scheme` value and pick the `Intellij IDEA code style XML` option. Import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml` file.
.Inspection profiles
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-inspections.png[Code style]
Go to `File` -> `Settings` -> `Editor` -> `Inspections`. There click on the icon next to the `Profile` section. There, click on the `Import Profile` and import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml` file.
.Checkstyle
To have Intellij work with Checkstyle, you have to install the `Checkstyle` plugin. It's advisable to also install the `Assertions2Assertj` to automatically convert the JUnit assertions
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-checkstyle.png[Checkstyle]
Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on the `+` icon in the `Configuration file` section. There, you'll have to define where the checkstyle rules should be picked from. In the image above, we've picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build's GitHub repository (e.g. for the `checkstyle.xml` : `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml`). We need to provide the following variables:
- `checkstyle.header.file` - please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` URL.
- `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` URL.
- `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`.
IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources.
=== 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
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/main/LICENSE.txt[here].
+2009 -397
View File
File diff suppressed because it is too large Load Diff
+29 -22
View File
@@ -1,58 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xmlns="http://maven.apache.org/POM/4.0.0"
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>
<parent> <parent>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId> <artifactId>spring-cloud-openfeign</artifactId>
<version>2.1.0.M2</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>
<docs.main>spring-cloud-openfeign</docs.main> <docs.main>spring-cloud-openfeign</docs.main>
<main.basedir>${basedir}/..</main.basedir> <main.basedir>${basedir}/..</main.basedir>
<docs.whitelisted.branches>2.0.x</docs.whitelisted.branches> <configprops.inclusionPattern>feign.*</configprops.inclusionPattern>
<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>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
<build> <build>
<plugins> <sourceDirectory>src/main/asciidoc</sourceDirectory>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build> </build>
<profiles> <profiles>
<profile> <profile>
<id>docs</id> <id>docs</id>
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.asciidoctor</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId> <artifactId>maven-resources-plugin</artifactId>
<inherited>false</inherited>
</plugin> </plugin>
<plugin> <plugin>
<groupId>com.agilejava.docbkx</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>docbkx-maven-plugin</artifactId> <artifactId>exec-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId> <artifactId>maven-antrun-plugin</artifactId>
<inherited>false</inherited>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <artifactId>maven-deploy-plugin</artifactId>
<artifactId>build-helper-maven-plugin</artifactId>
<inherited>false</inherited>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
+10 -4
View File
@@ -1,9 +1,11 @@
image:https://circleci.com/gh/spring-cloud/spring-cloud-openfeign.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-openfeign"] image::https://github.com/spring-cloud/spring-cloud-openfeign/workflows/Build/badge.svg?branch=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/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"] image:https://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/main/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
image:https://api.codacy.com/project/badge/Grade/97b04c4e609c4b4f86b415e4437a6484["Codacy code quality", link="https://www.codacy.com/app/Spring-Cloud/spring-cloud-openfeign?utm_source=github.com&utm_medium=referral&utm_content=spring-cloud/spring-cloud-openfeign&utm_campaign=Badge_Grade"] image:https://api.codacy.com/project/badge/Grade/97b04c4e609c4b4f86b415e4437a6484["Codacy code quality", link="https://www.codacy.com/app/Spring-Cloud/spring-cloud-openfeign?utm_source=github.com&utm_medium=referral&utm_content=spring-cloud/spring-cloud-openfeign&utm_campaign=Badge_Grade"]
include::_attributes.adoc[]
include::intro.adoc[] include::intro.adoc[]
== Features == Features
@@ -12,8 +14,12 @@ include::intro.adoc[]
== Building == Building
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/building-jdk8.adoc[] include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/docs/src/main/asciidoc/building-jdk8.adoc[]
== Contributing == Contributing
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[] include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/docs/src/main/asciidoc/contributing.adoc[]
== License
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/main/LICENSE.txt[here].
+18
View File
@@ -0,0 +1,18 @@
:doctype: book
:idprefix:
:idseparator: -
:toc: left
:toclevels: 4
:tabsize: 4
:numbered:
:sectanchors:
:sectnums:
:icons: font
:hide-uri-scheme:
:docinfo: shared,private
:sc-ext: java
:project-full-name: Spring Cloud OpenFeign
:all: {asterisk}{asterisk}
:core_path: {project-root}/spring-cloud-openfeign-core
+37
View File
@@ -0,0 +1,37 @@
|===
|Name | Default | Description
|spring.cloud.openfeign.autoconfiguration.jackson.enabled | `false` | If true, PageJacksonModule and SortJacksonModule bean will be provided for Jackson page decoding.
|spring.cloud.openfeign.circuitbreaker.enabled | `false` | If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker.
|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.
|spring.cloud.openfeign.client.config | |
|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`.
|spring.cloud.openfeign.client.default-config | `default` |
|spring.cloud.openfeign.client.default-to-properties | `true` |
|spring.cloud.openfeign.client.refresh-enabled | `false` | Enables options value refresh capability for Feign.
|spring.cloud.openfeign.compression.request.enabled | `false` | Enables the request sent by Feign to be compressed.
|spring.cloud.openfeign.compression.request.mime-types | `[text/xml, application/xml, application/json]` | The list of supported mime types.
|spring.cloud.openfeign.compression.request.min-request-size | `2048` | The minimum threshold content size.
|spring.cloud.openfeign.compression.response.enabled | `false` | Enables the response from Feign to be compressed.
|spring.cloud.openfeign.encoder.charset-from-content-type | `false` | Indicates whether the charset should be derived from the {@code Content-Type} header.
|spring.cloud.openfeign.httpclient.connection-timeout | `2000` |
|spring.cloud.openfeign.httpclient.connection-timer-repeat | `3000` |
|spring.cloud.openfeign.httpclient.disable-ssl-validation | `false` |
|spring.cloud.openfeign.httpclient.enabled | `true` | Enables the use of the Apache HTTP Client by Feign.
|spring.cloud.openfeign.httpclient.follow-redirects | `true` |
|spring.cloud.openfeign.httpclient.hc5.enabled | `false` | Enables the use of the Apache HTTP Client 5 by Feign.
|spring.cloud.openfeign.httpclient.hc5.pool-concurrency-policy | | Pool concurrency policies.
|spring.cloud.openfeign.httpclient.hc5.pool-reuse-policy | | Pool connection re-use policies.
|spring.cloud.openfeign.httpclient.hc5.socket-timeout | `5` | Default value for socket timeout.
|spring.cloud.openfeign.httpclient.hc5.socket-timeout-unit | | Default value for socket timeout unit.
|spring.cloud.openfeign.httpclient.max-connections | `200` |
|spring.cloud.openfeign.httpclient.max-connections-per-route | `50` |
|spring.cloud.openfeign.httpclient.ok-http.read-timeout | `60s` | {@link OkHttpClient} read timeout; defaults to 60 seconds.
|spring.cloud.openfeign.httpclient.time-to-live | `900` |
|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.
|===
+14
View File
@@ -0,0 +1,14 @@
:numbered!:
[appendix]
[[common-application-properties]]
== Common application properties
include::_attributes.adoc[]
Various properties can be specified inside your `application.properties` file, inside your `application.yml` file, or as command line switches.
This appendix provides a list of common {project-full-name} properties and references to the underlying classes that consume them.
NOTE: Property contributions can come from additional jar files on your classpath, so you should not consider this an exhaustive list.
Also, you can define your own properties.
include::_configprops.adoc[]
+8 -8
View File
@@ -39,8 +39,8 @@ function check_if_anything_to_sync() {
} }
function retrieve_current_branch() { function retrieve_current_branch() {
# Code getting the name of the current branch. For master we want to publish as we did until now # Code getting the name of the current branch. For main we want to publish as we did until now
# http://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch # https://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch
# If there is a branch already passed will reuse it - otherwise will try to find it # If there is a branch already passed will reuse it - otherwise will try to find it
CURRENT_BRANCH=${BRANCH} CURRENT_BRANCH=${BRANCH}
if [[ -z "${CURRENT_BRANCH}" ]] ; then if [[ -z "${CURRENT_BRANCH}" ]] ; then
@@ -134,8 +134,8 @@ function add_docs_from_target() {
# Copies the docs by using the retrieved properties from Maven build # Copies the docs by using the retrieved properties from Maven build
function copy_docs_for_current_version() { function copy_docs_for_current_version() {
if [[ "${CURRENT_BRANCH}" == "master" ]] ; then if [[ "${CURRENT_BRANCH}" == "main" ]] ; then
echo -e "Current branch is master - will copy the current docs only to the root folder" echo -e "Current branch is main - will copy the current docs only to the root folder"
for f in docs/target/generated-docs/*; do for f in docs/target/generated-docs/*; do
file=${f#docs/target/generated-docs/*} file=${f#docs/target/generated-docs/*}
if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then
@@ -147,7 +147,7 @@ function copy_docs_for_current_version() {
COMMIT_CHANGES="yes" COMMIT_CHANGES="yes"
else else
echo -e "Current branch is [${CURRENT_BRANCH}]" echo -e "Current branch is [${CURRENT_BRANCH}]"
# http://stackoverflow.com/questions/29300806/a-bash-script-to-check-if-a-string-is-present-in-a-comma-separated-list-of-strin # https://stackoverflow.com/questions/29300806/a-bash-script-to-check-if-a-string-is-present-in-a-comma-separated-list-of-strin
if [[ ",${WHITELISTED_BRANCHES_VALUE}," = *",${CURRENT_BRANCH},"* ]] ; then if [[ ",${WHITELISTED_BRANCHES_VALUE}," = *",${CURRENT_BRANCH},"* ]] ; then
mkdir -p ${ROOT_FOLDER}/${CURRENT_BRANCH} mkdir -p ${ROOT_FOLDER}/${CURRENT_BRANCH}
echo -e "Branch [${CURRENT_BRANCH}] is whitelisted! Will copy the current docs to the [${CURRENT_BRANCH}] folder" echo -e "Branch [${CURRENT_BRANCH}] is whitelisted! Will copy the current docs to the [${CURRENT_BRANCH}] folder"
@@ -216,7 +216,7 @@ function commit_changes_if_applicable() {
git commit -a -m "Sync docs from ${CURRENT_BRANCH} to gh-pages" && COMMIT_SUCCESSFUL="yes" || echo "Failed to commit changes" git commit -a -m "Sync docs from ${CURRENT_BRANCH} to gh-pages" && COMMIT_SUCCESSFUL="yes" || echo "Failed to commit changes"
# Uncomment the following push if you want to auto push to # Uncomment the following push if you want to auto push to
# the gh-pages branch whenever you commit to master locally. # the gh-pages branch whenever you commit to main locally.
# This is a little extreme. Use with care! # This is a little extreme. Use with care!
################################################################### ###################################################################
if [[ "${COMMIT_SUCCESSFUL}" == "yes" ]] ; then if [[ "${COMMIT_SUCCESSFUL}" == "yes" ]] ; then
@@ -249,7 +249,7 @@ The idea of this script is to update gh-pages branch with the generated docs. Wi
the script will work in the following manner: the script will work in the following manner:
- if there's no gh-pages / target for docs module then the script ends - if there's no gh-pages / target for docs module then the script ends
- for master branch the generated docs are copied to the root of gh-pages branch - for main branch the generated docs are copied to the root of gh-pages branch
- for any other branch (if that branch is whitelisted) a subfolder with branch name is created - for any other branch (if that branch is whitelisted) a subfolder with branch name is created
and docs are copied there and docs are copied there
- if the version switch is passed (-v) then a tag with (v) prefix will be retrieved and a folder - if the version switch is passed (-v) then a tag with (v) prefix will be retrieved and a folder
@@ -327,4 +327,4 @@ build_docs_if_applicable
retrieve_doc_properties retrieve_doc_properties
stash_changes stash_changes
add_docs_from_target add_docs_from_target
checkout_previous_branch checkout_previous_branch
+1
View File
@@ -0,0 +1 @@
include::spring-cloud-openfeign.adoc[]
+41
View File
@@ -0,0 +1,41 @@
This project provides https://github.com/OpenFeign/feign[OpenFeign] integrations for Spring Boot apps through autoconfiguration and binding to the Spring Environment and other Spring programming model idioms.
## Features
* Declarative REST Client: Feign creates a dynamic implementation of an interface decorated with JAX-RS or Spring MVC annotations
## Getting Started
```java
@SpringBootApplication
@EnableFeignClients
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
@FeignClient("name")
static interface NameService {
@RequestMapping("/")
public String getName();
}
}
```
## Contributing
We welcome contributions. You can read more on how to contribute to the project https://github.com/spring-cloud/spring-cloud-openfeign/blob/main/README.adoc#3-contributing[here].
## Community Support
* You can report issues through https://github.com/spring-cloud/spring-cloud-openfeign/issues[Github].
* We monitor https://stackoverflow.com/[StackOverflow] for questions with the `spring-cloud-feign` tag.
* You can contact our team at https://gitter.im/spring-cloud/spring-cloud[Gitter].
## Commercial Support
Commercial Support is provided as part of the https://spring.io/support[VMware Spring Runtime] offering.
+562 -151
View File
@@ -1,11 +1,5 @@
:github-tag: master
:github-repo: spring-cloud/spring-cloud-openfeign
:github-raw: http://raw.github.com/{github-repo}/{github-tag}
:github-code: http://github.com/{github-repo}/tree/{github-tag}
:all: {asterisk}{asterisk}
:nofooter:
:branch: master
= Spring Cloud OpenFeign = Spring Cloud OpenFeign
include::_attributes.adoc[]
*{spring-cloud-version}* *{spring-cloud-version}*
@@ -15,13 +9,19 @@ include::intro.adoc[]
[[spring-cloud-feign]] [[spring-cloud-feign]]
== Declarative REST Client: Feign == Declarative REST Client: Feign
https://github.com/Netflix/feign[Feign] is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. 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 integrates Ribbon and Eureka to provide a load balanced http client when using Feign. https://github.com/OpenFeign/feign[Feign] is a declarative web service client.
It makes writing web service clients easier.
To use Feign create an interface and annotate it.
It has pluggable annotation support including Feign annotations and JAX-RS annotations.
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 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
To include Feign in your project use the starter with group `org.springframework.cloud` To include Feign in your project use the starter with group `org.springframework.cloud`
and artifact id `spring-cloud-starter-openfeign`. See the http://projects.spring.io/spring-cloud/[Spring Cloud Project page] and artifact id `spring-cloud-starter-openfeign`. See the https://projects.spring.io/spring-cloud/[Spring Cloud Project page]
for details on setting up your build system with the current Spring Cloud Release Train. for details on setting up your build system with the current Spring Cloud Release Train.
Example spring boot app Example spring boot app
@@ -32,9 +32,9 @@ Example spring boot app
@EnableFeignClients @EnableFeignClients
public class Application { public class Application {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(Application.class, args); SpringApplication.run(Application.class, args);
} }
} }
---- ----
@@ -44,35 +44,47 @@ public class Application {
---- ----
@FeignClient("stores") @FeignClient("stores")
public interface StoreClient { public interface StoreClient {
@RequestMapping(method = RequestMethod.GET, value = "/stores") @RequestMapping(method = RequestMethod.GET, value = "/stores")
List<Store> getStores(); List<Store> getStores();
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json") @RequestMapping(method = RequestMethod.GET, value = "/stores")
Store update(@PathVariable("storeId") Long storeId, Store store); Page<Store> getStores(Pageable pageable);
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
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 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].
an arbitrary client name, which is used to create a Ribbon load You can also specify a URL using the `url` attribute
balancer (see <<spring-cloud-ribbon,below for details of Ribbon
support>>). You can also specify a URL using the `url` attribute
(absolute value or just a hostname). The name of the bean in the (absolute value or just a hostname). The name of the bean in the
application context is the fully qualified name of the interface. application context is the fully qualified name of the interface.
To specify your own alias value you can use the `qualifier` value To specify your own alias value you can use the `qualifiers` value
of the `@FeignClient` annotation. of the `@FeignClient` annotation.
The Ribbon 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 (see in your external configuration using https://docs.spring.io/spring-cloud-commons/docs/current/reference/html/#simplediscoveryclient[`SimpleDiscoveryClient`].
<<spring-cloud-ribbon-without-eureka,above for example>>).
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].
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
A central concept in Spring Cloud's Feign support is that of the named client. Each feign client is part of an ensemble of components that work together to contact a remote server on demand, and the ensemble has a name that you give it as an application developer using the `@FeignClient` annotation. Spring Cloud creates a new ensemble as an A central concept in Spring Cloud's Feign support is that of the named client. Each feign client is part of an ensemble of components that work together to contact a remote server on demand, and the ensemble has a name that you give it as an application developer using the `@FeignClient` annotation. Spring Cloud creates a new ensemble as an
`ApplicationContext` on demand for each named client using `FeignClientsConfiguration`. This contains (amongst other things) an `feign.Decoder`, a `feign.Encoder`, and a `feign.Contract`. `ApplicationContext` on demand for each named client using `FeignClientsConfiguration`. This contains (amongst other things) an `feign.Decoder`, a `feign.Encoder`, and a `feign.Contract`.
It is possible to override the name of that ensemble by using the `contextId`
attribute of the `@FeignClient` annotation.
Spring Cloud lets you take full control of the feign client by declaring additional configuration (on top of the `FeignClientsConfiguration`) using `@FeignClient`. Example: Spring Cloud lets you take full control of the feign client by declaring additional configuration (on top of the `FeignClientsConfiguration`) using `@FeignClient`. Example:
@@ -80,7 +92,7 @@ Spring Cloud lets you take full control of the feign client by declaring additio
---- ----
@FeignClient(name = "stores", configuration = FooConfiguration.class) @FeignClient(name = "stores", configuration = FooConfiguration.class)
public interface StoreClient { public interface StoreClient {
//.. //..
} }
---- ----
@@ -88,7 +100,9 @@ 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
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.
WARNING: Previously, using the `url` attribute, did not require the `name` attribute. Using `name` is now required. WARNING: Previously, using the `url` attribute, did not require the `name` attribute. Using `name` is now required.
@@ -98,23 +112,28 @@ Placeholders are supported in the `name` and `url` attributes.
---- ----
@FeignClient(name = "${feign.name}", url = "${feign.url}") @FeignClient(name = "${feign.name}", url = "${feign.url}")
public interface StoreClient { public interface StoreClient {
//.. //..
} }
---- ----
Spring Cloud Netflix provides the following beans by default for feign (`BeanType` beanName: `ClassName`): Spring Cloud OpenFeign provides the following beans by default for feign (`BeanType` beanName: `ClassName`):
* `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`
* `Client` feignClient: if Ribbon is enabled it is a `LoadBalancerFeignClient`, otherwise the default feign client is used. * `Client` feignClient: If Spring Cloud LoadBalancer is on the classpath, `FeignBlockingLoadBalancerClient` is used.
If none of them is on the classpath, the default feign client is used.
The OkHttpClient and ApacheHttpClient feign clients can be used by setting `feign.okhttp.enabled` or `feign.httpclient.enabled` to `true`, respectively, and having them on the classpath. 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.
You can customize the HTTP client used by providing a bean of either `ClosableHttpClient` when using Apache or `OkHttpClient` when using OK HTTP.
Spring Cloud Netflix _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: 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.
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:
* `Logger.Level` * `Logger.Level`
* `Retryer` * `Retryer`
@@ -122,6 +141,12 @@ Spring Cloud Netflix _does not_ provide the following beans by default for feign
* `Request.Options` * `Request.Options`
* `Collection<RequestInterceptor>` * `Collection<RequestInterceptor>`
* `SetterFactory` * `SetterFactory`
* `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.
Notice this retrying behavior is different from the Feign default one, where it will automatically retry IOExceptions,
treating them as transient network related exceptions, and any RetryableException thrown from an ErrorDecoder.
Creating a bean of one of those type and placing it in a `@FeignClient` configuration (such as `FooConfiguration` above) allows you to override each one of the beans described. Example: Creating a bean of one of those type and placing it in a `@FeignClient` configuration (such as `FooConfiguration` above) allows you to override each one of the beans described. Example:
@@ -129,15 +154,15 @@ Creating a bean of one of those type and placing it in a `@FeignClient` configur
---- ----
@Configuration @Configuration
public class FooConfiguration { public class FooConfiguration {
@Bean @Bean
public Contract feignContract() { public Contract feignContract() {
return new feign.Contract.Default(); return new feign.Contract.Default();
} }
@Bean @Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() { public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("user", "password"); return new BasicAuthRequestInterceptor("user", "password");
} }
} }
---- ----
@@ -148,64 +173,121 @@ This replaces the `SpringMvcContract` with `feign.Contract.Default` and adds a `
application.yml application.yml
[source,yaml] [source,yaml]
---- ----
feign: spring:
client: cloud:
config: openfeign:
feignName: client:
connectTimeout: 5000 config:
readTimeout: 5000 feignName:
loggerLevel: full connectTimeout: 5000
errorDecoder: com.example.SimpleErrorDecoder readTimeout: 5000
retryer: com.example.SimpleRetryer loggerLevel: full
requestInterceptors: errorDecoder: com.example.SimpleErrorDecoder
- com.example.FooRequestInterceptor retryer: com.example.SimpleRetryer
- com.example.BarRequestInterceptor defaultQueryParameters:
decode404: false query: queryValue
encoder: com.example.SimpleEncoder defaultRequestHeaders:
decoder: com.example.SimpleDecoder header: headerValue
contract: com.example.SimpleContract requestInterceptors:
- com.example.FooRequestInterceptor
- com.example.BarRequestInterceptor
decode404: false
encoder: com.example.SimpleEncoder
decoder: com.example.SimpleDecoder
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 `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:
client: cloud:
config: openfeign:
default: client:
connectTimeout: 5000 config:
readTimeout: 5000 default:
loggerLevel: basic connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic
---- ----
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 If we want to create multiple feign clients with the same name or url
thread isolation strategy for Hystrix to `SEMAPHORE` or disable Hystrix in Feign. so that they would point to the same server but each with a different custom configuration then
we have to use `contextId` attribute of the `@FeignClient` in order to avoid name
collision of these configuration beans.
application.yml [source,java,indent=0]
[source,yaml]
---- ----
# To disable Hystrix in Feign @FeignClient(contextId = "fooClient", name = "stores", configuration = FooConfiguration.class)
feign: public interface FooClient {
hystrix: //..
enabled: false }
# To set thread isolation to SEMAPHORE
hystrix:
command:
default:
execution:
isolation:
strategy: SEMAPHORE
---- ----
[source,java,indent=0]
----
@FeignClient(contextId = "barClient", name = "stores", configuration = BarConfiguration.class)
public interface BarClient {
//..
}
----
It is also possible to configure FeignClient not to inherit beans from the parent context.
You can do this by overriding the `inheritParentConfiguration()` in a `FeignClientConfigurer`
bean to return `false`:
[source,java,indent=0]
----
@Configuration
public class CustomConfiguration{
@Bean
public FeignClientConfigurer feignClientConfigurer() {
return new FeignClientConfigurer() {
@Override
public boolean inheritParentConfiguration() {
return 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
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 `spring.cloud.openfeign.encoder.charset-from-content-type` to `true`.
[[timeout-handling]]
=== Timeout Handling
We can configure timeouts on both the default and the named client. OpenFeign works with two timeout parameters:
- `connectTimeout` prevents blocking the caller due to the long server processing time.
- `readTimeout` is applied from the time of connection establishment and is triggered when returning the response takes too long.
NOTE: In case the server is not running or available a packet results in _connection refused_. The communication ends either with an error message or in a fallback. This can happen _before_ the `connectTimeout` if it is set very low. The time taken to perform a lookup and to receive such a packet causes a significant part of this delay. It is subject to change based on the remote host that involves a DNS lookup.
=== 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
@@ -223,27 +305,29 @@ 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, "http://PROD-SVC"); .target(FooClient.class, "https://PROD-SVC");
this.adminClient = Feign.builder().client(client) this.adminClient = Feign.builder().client(client)
.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, "http://PROD-SVC"); .target(FooClient.class, "https://PROD-SVC");
} }
} }
---- ----
NOTE: In the above example `FeignClientsConfiguration.class` is the default configuration NOTE: In the above example `FeignClientsConfiguration.class` is the default configuration
provided by Spring Cloud Netflix. provided by Spring Cloud OpenFeign.
NOTE: `PROD-SVC` is the name of the service the Clients will be making requests to. NOTE: `PROD-SVC` is the name of the service the Clients will be making requests to.
@@ -251,18 +335,21 @@ NOTE: The Feign `Contract` object defines what annotations and values are valid
autowired `Contract` bean provides supports for SpringMVC annotations, instead of autowired `Contract` bean provides supports for SpringMVC annotations, instead of
the default Feign native annotations. the default Feign native annotations.
[[spring-cloud-feign-hystrix]] You can also use the `Builder`to configure FeignClient not to inherit beans from the parent context.
=== Feign Hystrix Support You can do this by overriding calling `inheritParentContext(false)` on the `Builder`.
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()`). [[spring-cloud-feign-circuitbreaker]]
=== Feign Spring Cloud CircuitBreaker Support
To disable Hystrix support on a per-client basis create a vanilla `Feign.Builder` with the "prototype" scope, e.g.: 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.:
[source,java,indent=0] [source,java,indent=0]
---- ----
@Configuration @Configuration
public class FooConfiguration { public class FooConfiguration {
@Bean @Bean
@Scope("prototype") @Scope("prototype")
public Feign.Builder feignBuilder() { public Feign.Builder feignBuilder() {
return Feign.builder(); return Feign.builder();
@@ -270,60 +357,143 @@ public class FooConfiguration {
} }
---- ----
WARNING: Prior to the Spring Cloud Dalston release, if Hystrix was on the classpath Feign would have wrapped 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()`.
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]] NOTE: As of 2020.0.2, the circuit breaker name pattern has changed from `<feignClientName>_<calledMethod>`.
=== Feign Hystrix Fallbacks Using `CircuitBreakerNameResolver` introduced in 2020.0.4, circuit breaker names can retain the old pattern.
Hystrix supports the notion of a fallback: a default code path that is executed when they circuit is open or there is an error. To enable fallbacks for a given `@FeignClient` set the `fallback` attribute to the class name that implements the fallback. You also need to declare your implementation as a Spring bean. 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] [source,java,indent=0]
---- ----
@FeignClient(name = "hello", fallback = HystrixClientFallback.class) @FeignClient(url = "http://localhost:8080")
protected interface HystrixClient { public interface DemoClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello iFailSometimes();
}
static class HystrixClientFallback implements HystrixClient { @GetMapping("demo")
@Override String getDemo();
public Hello iFailSometimes() {
return new Hello("fallback");
}
} }
---- ----
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]]
=== Feign Spring Cloud CircuitBreaker Fallbacks
Spring Cloud CircuitBreaker supports the notion of a fallback: a default code path that is executed when the circuit is open or there is an error. To enable fallbacks for a given `@FeignClient` set the `fallback` attribute to the class name that implements the fallback. You also need to declare your implementation as a Spring bean.
[source,java,indent=0]
----
@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]
---- ----
@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class) @FeignClient(name = "testClientWithFactory", url = "http://localhost:${server.port}/",
protected interface HystrixClient { fallbackFactory = TestFallbackFactory.class)
@RequestMapping(method = RequestMethod.GET, value = "/hello") protected interface TestClientWithFactory {
Hello iFailSometimes();
} @RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello getHello();
@RequestMapping(method = RequestMethod.GET, value = "/hellonotfound")
String getException();
@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`. @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 Netflix 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]
---- ----
@@ -344,8 +514,8 @@ This allows grouping common operations into convenient base interfaces.
---- ----
public interface UserService { public interface UserService {
@RequestMapping(method = RequestMethod.GET, value ="/users/{id}") @RequestMapping(method = RequestMethod.GET, value ="/users/{id}")
User getUser(@PathVariable("id") long id); User getUser(@PathVariable("id") long id);
} }
---- ----
@@ -369,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
@@ -381,17 +548,17 @@ 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.
@@ -420,17 +587,261 @@ For example, the following would set the `Logger.Level` to `FULL`:
---- ----
@Configuration @Configuration
public class FooConfiguration { public class FooConfiguration {
@Bean @Bean
Logger.Level feignLoggerLevel() { Logger.Level feignLoggerLevel() {
return Logger.Level.FULL; return Logger.Level.FULL;
} }
} }
---- ----
OtherClass.someMethod(myprop.get());
} === 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();
}
} }
stripped). The proxy uses Ribbon to locate an instance to forward to ----
via discovery, and all requests are executed in a
<<hystrix-fallbacks-for-routes, hystrix command>>, so === Feign metrics
failures will show up in Hystrix metrics, and once the circuit is open
the proxy will not try to contact the service. 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
The OpenFeign `@QueryMap` annotation provides support for POJOs to be used as
GET parameter maps. Unfortunately, the default OpenFeign QueryMap annotation is
incompatible with Spring because it lacks a `value` property.
Spring Cloud OpenFeign provides an equivalent `@SpringQueryMap` annotation, which
is used to annotate a POJO or Map parameter as a query parameter map.
For example, the `Params` class defines parameters `param1` and `param2`:
[source,java,indent=0]
----
// Params.java
public class Params {
private String param1;
private String param2;
// [Getters and setters omitted for brevity]
}
----
The following feign client uses the `Params` class by using the `@SpringQueryMap` annotation:
[source,java,indent=0]
----
@FeignClient("demo")
public interface DemoTemplate {
@GetMapping(path = "/demo")
String demoEndpoint(@SpringQueryMap Params params);
}
----
If you need more control over the generated query parameter map, you can implement a custom `QueryMapEncoder` bean.
=== HATEOAS support
Spring provides some APIs to create REST representations that follow the https://en.wikipedia.org/wiki/HATEOAS[HATEOAS] principle, https://spring.io/projects/spring-hateoas[Spring Hateoas] and https://spring.io/projects/spring-data-rest[Spring Data REST].
If your project use the `org.springframework.boot:spring-boot-starter-hateoas` starter
or the `org.springframework.boot:spring-boot-starter-data-rest` starter, Feign HATEOAS support is enabled by default.
When HATEOAS support is enabled, Feign clients are allowed to serialize
and deserialize HATEOAS representation models: https://docs.spring.io/spring-hateoas/docs/1.0.0.M1/apidocs/org/springframework/hateoas/EntityModel.html[EntityModel], https://docs.spring.io/spring-hateoas/docs/1.0.0.M1/apidocs/org/springframework/hateoas/CollectionModel.html[CollectionModel] and https://docs.spring.io/spring-hateoas/docs/1.0.0.M1/apidocs/org/springframework/hateoas/PagedModel.html[PagedModel].
[source,java,indent=0]
----
@FeignClient("demo")
public interface DemoTemplate {
@GetMapping(path = "/stores")
CollectionModel<Store> getStores();
}
----
=== Spring @MatrixVariable Support
Spring Cloud OpenFeign provides support for the Spring `@MatrixVariable` annotation.
If a map is passed as the method argument, the `@MatrixVariable` path segment is created by joining key-value pairs from the map with a `=`.
If a different object is passed, either the `name` provided in the `@MatrixVariable` annotation (if defined) or the annotated variable name is
joined with the provided method argument using `=`.
IMPORTANT:: Even though, on the server side, Spring does not require the users to name the path segment placeholder same as the matrix variable name, since it would be too ambiguous on the client side, Spring Cloud OpenFeign requires that you add a path segment placeholder with a name matching either the `name` provided in the `@MatrixVariable` annotation (if defined) or the annotated variable name.
For example:
[source,java,indent=0]
----
@GetMapping("/objects/links/{matrixVars}")
Map<String, List<String>> getObjects(@MatrixVariable Map<String, List<String>> matrixVars);
----
Note that both variable name and the path segment placeholder are called `matrixVars`.
[source,java,indent=0]
----
@FeignClient("demo")
public interface DemoTemplate {
@GetMapping(path = "/stores")
CollectionModel<Store> getStores();
}
----
=== Feign `CollectionFormat` support
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.
[source,java,indent=0]
----
@FeignClient(name = "demo")
protected interface PageableFeignClient {
@CollectionFormat(feign.CollectionFormat.CSV)
@GetMapping(path = "/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.
=== 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.
Until that is done, we recommend using https://github.com/Playtika/feign-reactive[feign-reactive] for Spring WebClient support.
==== Early Initialization Errors
Depending on how you are using your Feign clients you may see initialization errors when starting your application.
To work around this problem you can use an `ObjectProvider` when autowiring your client.
[source,java,indent=0]
----
@Autowired
ObjectProvider<TestFeignClient> testFeignClient;
----
=== Spring Data Support
You may consider enabling Jackson Modules for the support `org.springframework.data.domain.Page` and `org.springframework.data.domain.Sort` decoding.
[source,java]
----
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
To see the list of all Spring Cloud OpenFeign related configuration properties please check link:appendix.html[the Appendix page].
Vendored
+1 -1
View File
@@ -8,7 +8,7 @@
# "License"); you may not use this file except in compliance # "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at # with the License. You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0 # https://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, # Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an # software distributed under the License is distributed on an
Vendored
+1 -1
View File
@@ -7,7 +7,7 @@
@REM "License"); you may not use this file except in compliance @REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at @REM with the License. You may obtain a copy of the License at
@REM @REM
@REM http://www.apache.org/licenses/LICENSE-2.0 @REM https://www.apache.org/licenses/LICENSE-2.0
@REM @REM
@REM Unless required by applicable law or agreed to in writing, @REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an @REM software distributed under the License is distributed on an
+56 -33
View File
@@ -1,42 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xmlns="http://maven.apache.org/POM/4.0.0"
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.1.0.M2</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.1.0.RC2</version> <version>4.0.0-SNAPSHOT</version>
<relativePath /> <relativePath/>
</parent> </parent>
<scm> <scm>
<url>https://github.com/spring-cloud/spring-cloud-openfeign</url> <url>https://github.com/spring-cloud/spring-cloud-openfeign</url>
<connection>scm:git:git://github.com/spring-cloud/spring-cloud-openfeign.git</connection> <connection>scm:git:git://github.com/spring-cloud/spring-cloud-openfeign.git
<developerConnection>scm:git:ssh://git@github.com/spring-cloud/spring-cloud-openfeign.git</developerConnection> </connection>
<developerConnection>
scm:git:ssh://git@github.com/spring-cloud/spring-cloud-openfeign.git
</developerConnection>
<tag>HEAD</tag> <tag>HEAD</tag>
</scm> </scm>
<properties> <properties>
<main.basedir>${basedir}</main.basedir> <main.basedir>${basedir}</main.basedir>
<jackson.version>2.7.3</jackson.version> <jackson.version>2.11.3</jackson.version>
<spring-cloud-commons.version>2.1.0.M2</spring-cloud-commons.version> <spring-cloud-commons.version>4.0.0-SNAPSHOT</spring-cloud-commons.version>
<spring-cloud-netflix.version>2.1.0.M2</spring-cloud-netflix.version>
<!-- Plugin versions --> <!-- Plugin versions -->
<maven-compiler-plugin.version>3.6.1</maven-compiler-plugin.version>
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version> <maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
<!-- Sonar --> <!-- Sonar -->
<surefire.plugin.version>2.19.1</surefire.plugin.version> <surefire.plugin.version>2.19.1</surefire.plugin.version>
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin> <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis> <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath> <sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec
</sonar.jacoco.reportPath>
<sonar.language>java</sonar.language> <sonar.language>java</sonar.language>
</properties> </properties>
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId> <artifactId>maven-eclipse-plugin</artifactId>
@@ -46,34 +53,48 @@
<additionalConfig> <additionalConfig>
<file> <file>
<name>.settings/org.eclipse.jdt.ui.prefs</name> <name>.settings/org.eclipse.jdt.ui.prefs</name>
<location>${main.basedir}/eclipse/org.eclipse.jdt.ui.prefs</location> <location>${main.basedir}/eclipse/org.eclipse.jdt.ui.prefs
</location>
</file> </file>
<file> <file>
<name>.settings/org.eclipse.jdt.core.prefs</name> <name>.settings/org.eclipse.jdt.core.prefs</name>
<location>${main.basedir}/eclipse/org.eclipse.jdt.core.prefs</location> <location>${main.basedir}/eclipse/org.eclipse.jdt.core.prefs
</location>
</file> </file>
</additionalConfig> </additionalConfig>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId>
<version>${maven-compiler-plugin.version}</version> <artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
<plugin>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
<configuration> <configuration>
<source>1.8</source> <ignoredResourcePatterns>
<target>1.8</target> <ignoredResourcePattern>mozilla/public-suffix-list.txt</ignoredResourcePattern>
</ignoredResourcePatterns>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</reporting>
<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>
@@ -106,7 +127,7 @@
<module>spring-cloud-openfeign-core</module> <module>spring-cloud-openfeign-core</module>
<module>spring-cloud-starter-openfeign</module> <module>spring-cloud-starter-openfeign</module>
<module>docs</module> <module>docs</module>
</modules> </modules>
<profiles> <profiles>
<profile> <profile>
<id>spring</id> <id>spring</id>
@@ -114,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>
@@ -125,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>
@@ -143,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>
@@ -154,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>
@@ -162,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>
@@ -184,7 +205,8 @@
</goals> </goals>
<configuration> <configuration>
<propertyName>surefireArgLine</propertyName> <propertyName>surefireArgLine</propertyName>
<destFile>${project.build.directory}/jacoco.exec</destFile> <destFile>${project.build.directory}/jacoco.exec
</destFile>
</configuration> </configuration>
</execution> </execution>
<execution> <execution>
@@ -195,7 +217,8 @@
</goals> </goals>
<configuration> <configuration>
<!-- Sets the path to the file which contains the execution data. --> <!-- Sets the path to the file which contains the execution data. -->
<dataFile>${project.build.directory}/jacoco.exec</dataFile> <dataFile>${project.build.directory}/jacoco.exec
</dataFile>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
+84 -83
View File
@@ -1,11 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xmlns="http://maven.apache.org/POM/4.0.0"
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>
<parent> <parent>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId> <artifactId>spring-cloud-openfeign</artifactId>
<version>2.1.0.M2</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>
@@ -20,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>
@@ -49,6 +46,11 @@
<artifactId>spring-boot-starter-reactor-netty</artifactId> <artifactId>spring-boot-starter-reactor-netty</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>io.netty</groupId> <groupId>io.netty</groupId>
<artifactId>netty-codec-http</artifactId> <artifactId>netty-codec-http</artifactId>
@@ -59,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>
@@ -83,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>
@@ -96,12 +94,24 @@
<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>
<artifactId>feign-slf4j</artifactId> <artifactId>feign-slf4j</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-micrometer</artifactId>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>io.github.openfeign</groupId> <groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId> <artifactId>feign-httpclient</artifactId>
@@ -109,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>
@@ -117,56 +127,30 @@
<artifactId>feign-okhttp</artifactId> <artifactId>feign-okhttp</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-java8</artifactId>
<optional>true</optional>
</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>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-apache-client4</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>
@@ -187,19 +171,19 @@
<artifactId>spring-cloud-test-support</artifactId> <artifactId>spring-cloud-test-support</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>io.projectreactor</groupId> <groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId> <artifactId>reactor-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.netflix.ribbon</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>ribbon</artifactId> <artifactId>spring-boot-starter-data-rest</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@@ -211,25 +195,42 @@
<dependency> <dependency>
<groupId>com.google.protobuf</groupId> <groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId> <artifactId>protobuf-java</artifactId>
<version>3.4.0</version> <version>3.19.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>0.10.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<profiles> <profiles>
<profile> <profile>
<id>java8plus</id> <id>java8plus</id>
<activation> <activation>
<jdk>[1.8,2.0)</jdk> <jdk>[1.8,2.0)</jdk>
</activation> </activation>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<configuration> <configuration>
<compilerArgs> <compilerArgs>
<arg>-parameters</arg> <arg>-parameters</arg>
</compilerArgs> </compilerArgs>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2017 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -32,17 +32,15 @@ public interface AnnotatedParameterProcessor {
/** /**
* Retrieves the processor supported annotation type. * Retrieves the processor supported annotation type.
*
* @return the annotation type * @return the annotation type
*/ */
Class<? extends Annotation> getAnnotationType(); Class<? extends Annotation> getAnnotationType();
/** /**
* Process the annotated parameter. * Process the annotated parameter.
* * @param context the parameter context
* @param context the parameter context
* @param annotation the annotation instance * @param annotation the annotation instance
* @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, Method method); boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method);
@@ -56,32 +54,30 @@ public interface AnnotatedParameterProcessor {
/** /**
* Retrieves the method metadata. * Retrieves the method metadata.
*
* @return the method metadata * @return the method metadata
*/ */
MethodMetadata getMethodMetadata(); MethodMetadata getMethodMetadata();
/** /**
* Retrieves the index of the parameter. * Retrieves the index of the parameter.
*
* @return the parameter index * @return the parameter index
*/ */
int getParameterIndex(); int getParameterIndex();
/** /**
* Sets the parameter name. * Sets the parameter name.
*
* @param name the name of the parameter * @param name the name of the parameter
*/ */
void setParameterName(String name); void setParameterName(String name);
/** /**
* Sets the template parameter. * Sets the template parameter.
*
* @param name the template parameter * @param name the template parameter
* @param rest the existing parameter values * @param rest the existing parameter values
* @return parameters * @return parameters
*/ */
Collection<String> setTemplateParameter(String name, Collection<String> rest); Collection<String> setTemplateParameter(String name, Collection<String> rest);
} }
} }
@@ -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);
}
}
@@ -0,0 +1,34 @@
/*
* 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.Method;
import feign.Target;
/**
* 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
*/
public interface CircuitBreakerNameResolver {
String resolveCircuitBreakerName(String feignClientName, Target<?> target, Method method);
}
@@ -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 java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates which collection format should be used while processing the annotated method.
*
* @author Olga Maciaszek-Sharma
* @author Sam Kruglov
* @see feign.CollectionFormat
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface CollectionFormat {
/**
* Allows setting the {@link feign.CollectionFormat} to be used while processing the
* annotated method.
* @return the {@link feign.CollectionFormat} to be used
*/
feign.CollectionFormat value();
}
@@ -1,11 +1,11 @@
/* /*
* Copyright 2016 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -1,18 +1,17 @@
/* /*
* Copyright 2013-2016 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*
*/ */
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
@@ -27,7 +26,8 @@ class DefaultTargeter implements Targeter {
@Override @Override
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context, public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context,
Target.HardCodedTarget<T> target) { Target.HardCodedTarget<T> target) {
return feign.target(target); return feign.target(target);
} }
} }
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2015 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -25,10 +25,11 @@ import java.lang.annotation.Target;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
/** /**
* Scans for interfaces that declare they are feign clients (via {@link FeignClient * Scans for interfaces that declare they are feign clients (via
* <code>@FeignClient</code>}). Configures component scanning directives for use with * {@link org.springframework.cloud.openfeign.FeignClient} <code>@FeignClient</code>).
* {@link org.springframework.context.annotation.Configuration * Configures component scanning directives for use with
* <code>@Configuration</code>} classes. * {@link org.springframework.context.annotation.Configuration}
* <code>@Configuration</code> classes.
* *
* @author Spencer Gibb * @author Spencer Gibb
* @author Dave Syer * @author Dave Syer
@@ -55,7 +56,6 @@ public @interface EnableFeignClients {
* <p> * <p>
* Use {@link #basePackageClasses()} for a type-safe alternative to String-based * Use {@link #basePackageClasses()} for a type-safe alternative to String-based
* package names. * package names.
*
* @return the array of 'basePackages'. * @return the array of 'basePackages'.
*/ */
String[] basePackages() default {}; String[] basePackages() default {};
@@ -66,7 +66,6 @@ public @interface EnableFeignClients {
* <p> * <p>
* Consider creating a special no-op marker class or interface in each package that * Consider creating a special no-op marker class or interface in each package that
* serves no purpose other than being referenced by this attribute. * serves no purpose other than being referenced by this attribute.
*
* @return the array of 'basePackageClasses'. * @return the array of 'basePackageClasses'.
*/ */
Class<?>[] basePackageClasses() default {}; Class<?>[] basePackageClasses() default {};
@@ -77,12 +76,15 @@ public @interface EnableFeignClients {
* {@link feign.codec.Decoder}, {@link feign.codec.Encoder}, {@link feign.Contract}. * {@link feign.codec.Decoder}, {@link feign.codec.Encoder}, {@link feign.Contract}.
* *
* @see FeignClientsConfiguration for the defaults * @see FeignClientsConfiguration for the defaults
* @return list of default configurations
*/ */
Class<?>[] defaultConfiguration() default {}; Class<?>[] defaultConfiguration() default {};
/** /**
* List of classes annotated with @FeignClient. If not empty, disables classpath scanning. * List of classes annotated with @FeignClient. If not empty, disables classpath
* @return * scanning.
* @return list of FeignClient classes
*/ */
Class<?>[] clients() default {}; Class<?>[] clients() default {};
} }
@@ -0,0 +1,87 @@
/*
* 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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import static feign.Util.checkNotNull;
/**
* Used to control the fallback given its cause.
*
* Ex.
*
* <pre>
* {@code
* // This instance will be invoked if there are errors of any kind.
* FallbackFactory<GitHub> fallbackFactory = cause -> (owner, repo) -> {
* if (cause instanceof FeignException && ((FeignException) cause).status() == 403) {
* return Collections.emptyList();
* } else {
* return Arrays.asList("yogi");
* }
* };
*
* GitHub github = FeignCircuitBreaker.builder()
* ...
* .target(GitHub.class, "https://api.github.com", fallbackFactory);
* }
* </pre>
*
* @param <T> the feign interface type
*/
public interface FallbackFactory<T> {
/**
* Returns an instance of the fallback appropriate for the given cause.
* @param cause cause of an exception.
* @return fallback
*/
T create(Throwable cause);
final class Default<T> implements FallbackFactory<T> {
final Log logger;
final T constant;
public Default(T constant) {
this(constant, LogFactory.getLog(Default.class));
}
Default(T constant, Log logger) {
this.constant = checkNotNull(constant, "fallback");
this.logger = checkNotNull(logger, "logger");
}
@Override
public T create(Throwable cause) {
if (logger.isTraceEnabled()) {
logger.trace("fallback due to: " + cause.getMessage(), cause);
}
return constant;
}
@Override
public String toString() {
return constant.toString();
}
}
}
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2015 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,49 +16,89 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
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 com.fasterxml.jackson.databind.Module;
import feign.Capability;
import feign.Client;
import feign.Feign;
import feign.RequestInterceptor;
import feign.Target;
import feign.hc5.ApacheHttp5Client;
import feign.httpclient.ApacheHttpClient;
import feign.okhttp.OkHttpClient;
import jakarta.annotation.PreDestroy;
import okhttp3.ConnectionPool;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.RegistryBuilder; import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager; 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.beans.factory.annotation.Value;
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.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.security.OAuth2FeignRequestInterceptor;
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptorConfigurer;
import org.springframework.cloud.openfeign.support.FeignEncoderProperties;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties; import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.cloud.openfeign.support.PageJacksonModule;
import org.springframework.cloud.openfeign.support.SortJacksonModule;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import feign.Client; import static org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptorBuilder.buildWithConfigurers;
import feign.Feign;
import feign.httpclient.ApacheHttpClient;
import feign.okhttp.OkHttpClient;
import okhttp3.ConnectionPool;
import javax.annotation.PreDestroy;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
* @author Julien Roy * @author Julien Roy
* @author Grzegorz Poznachowski
* @author Nikita Konev
* @author Tim Peeters
* @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh
* @author Andrii Bohutskyi
* @author Kwangyong Kim
* @author Sam Kruglov
* @author Wojciech Mąka
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Feign.class) @ConditionalOnClass(Feign.class)
@EnableConfigurationProperties({FeignClientProperties.class, FeignHttpClientProperties.class}) @EnableConfigurationProperties({ FeignClientProperties.class, FeignHttpClientProperties.class,
FeignEncoderProperties.class })
public class FeignAutoConfiguration { public class FeignAutoConfiguration {
private static final Log LOG = LogFactory.getLog(FeignAutoConfiguration.class);
@Autowired(required = false) @Autowired(required = false)
private List<FeignClientSpecification> configurations = new ArrayList<>(); private List<FeignClientSpecification> configurations = new ArrayList<>();
@@ -74,36 +114,112 @@ public class FeignAutoConfiguration {
return context; return context;
} }
@Configuration @Bean
@ConditionalOnClass(name = "feign.hystrix.HystrixFeign") @ConditionalOnProperty(value = "spring.cloud.openfeign.cache.enabled", matchIfMissing = true)
protected static class HystrixFeignTargeterConfiguration { @ConditionalOnBean(CacheInterceptor.class)
@Bean public Capability cachingCapability(CacheInterceptor cacheInterceptor) {
@ConditionalOnMissingBean return new CachingCapability(cacheInterceptor);
public Targeter feignTargeter() {
return new HystrixTargeter();
}
} }
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnMissingClass("feign.hystrix.HystrixFeign") @ConditionalOnClass({ Module.class, Page.class, Sort.class })
@ConditionalOnProperty(value = "spring.cloud.openfeign.autoconfiguration.jackson.enabled", havingValue = "true")
protected static class FeignJacksonConfiguration {
@Bean
@ConditionalOnMissingBean(PageJacksonModule.class)
public PageJacksonModule pageJacksonModule() {
return new PageJacksonModule();
}
@Bean
@ConditionalOnMissingBean(SortJacksonModule.class)
public SortJacksonModule sortModule() {
return new SortJacksonModule();
}
}
@Configuration(proxyBeanMethods = false)
@Conditional(FeignCircuitBreakerDisabledConditions.class)
protected static class DefaultFeignTargeterConfiguration { protected static class DefaultFeignTargeterConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public Targeter feignTargeter() { public Targeter feignTargeter() {
return new DefaultTargeter(); return new DefaultTargeter();
} }
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(CircuitBreaker.class)
@ConditionalOnProperty(value = "spring.cloud.openfeign.circuitbreaker.enabled", havingValue = "true")
protected static class CircuitBreakerPresentFeignTargeterConfiguration {
@Bean
@ConditionalOnMissingBean(CircuitBreakerFactory.class)
public Targeter defaultFeignTargeter() {
return new DefaultTargeter();
}
@Bean
@ConditionalOnMissingBean(CircuitBreakerNameResolver.class)
@ConditionalOnProperty(value = "spring.cloud.openfeign.circuitbreaker.alphanumeric-ids.enabled",
havingValue = "false")
public CircuitBreakerNameResolver circuitBreakerNameResolver() {
return new DefaultCircuitBreakerNameResolver();
}
@Bean
@ConditionalOnMissingBean(CircuitBreakerNameResolver.class)
@ConditionalOnProperty(value = "spring.cloud.openfeign.circuitbreaker.alphanumeric-ids.enabled",
havingValue = "true", matchIfMissing = true)
public CircuitBreakerNameResolver alphanumericCircuitBreakerNameResolver() {
return new AlphanumericCircuitBreakerNameResolver();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(CircuitBreakerFactory.class)
public Targeter circuitBreakerFeignTargeter(CircuitBreakerFactory circuitBreakerFactory,
@Value("${spring.cloud.openfeign.circuitbreaker.group.enabled:false}") boolean circuitBreakerGroupEnabled,
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 @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)
protected static class HttpClientFeignConfiguration { protected static class HttpClientFeignConfiguration {
private final Timer connectionManagerTimer = new Timer( private final Timer connectionManagerTimer = new Timer(
"FeignApacheHttpClientConfiguration.connectionManagerTimer", true); "FeignApacheHttpClientConfiguration.connectionManagerTimer", true);
@@ -117,11 +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.getMaxConnections(), httpClientProperties.isDisableSslValidation(), httpClientProperties.getMaxConnections(),
httpClientProperties.getMaxConnectionsPerRoute(), httpClientProperties.getMaxConnectionsPerRoute(), httpClientProperties.getTimeToLive(),
httpClientProperties.getTimeToLive(), httpClientProperties.getTimeToLiveUnit(), this.registryBuilder);
httpClientProperties.getTimeToLiveUnit(), registryBuilder);
this.connectionManagerTimer.schedule(new TimerTask() { this.connectionManagerTimer.schedule(new TimerTask() {
@Override @Override
public void run() { public void run() {
@@ -137,11 +252,9 @@ 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(). .setDefaultRequestConfig(defaultRequestConfig).build();
setConnectionManager(httpClientConnectionManager).
setDefaultRequestConfig(defaultRequestConfig).build();
return this.httpClient; return this.httpClient;
} }
@@ -152,19 +265,26 @@ public class FeignAutoConfiguration {
} }
@PreDestroy @PreDestroy
public void destroy() throws Exception { public void destroy() {
connectionManagerTimer.cancel(); this.connectionManagerTimer.cancel();
if(httpClient != null) { if (this.httpClient != null) {
httpClient.close(); try {
this.httpClient.close();
}
catch (IOException e) {
if (LOG.isErrorEnabled()) {
LOG.error("Could not correctly close httpClient.");
}
}
} }
} }
} }
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OkHttpClient.class) @ConditionalOnClass(OkHttpClient.class)
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
@ConditionalOnMissingBean(okhttp3.OkHttpClient.class) @ConditionalOnMissingBean(okhttp3.OkHttpClient.class)
@ConditionalOnProperty(value = "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;
@@ -172,31 +292,31 @@ public class FeignAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean(ConnectionPool.class) @ConditionalOnMissingBean(ConnectionPool.class)
public ConnectionPool httpClientConnectionPool(FeignHttpClientProperties httpClientProperties, public ConnectionPool httpClientConnectionPool(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();
this.okHttpClient = httpClientFactory.createBuilder(disableSslValidation). Duration readTimeout = httpClientProperties.getOkHttp().getReadTimeout();
connectTimeout(connectTimeout, TimeUnit.MILLISECONDS). this.okHttpClient = httpClientFactory.createBuilder(disableSslValidation)
followRedirects(followRedirects). .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects)
connectionPool(connectionPool).build(); .readTimeout(readTimeout).connectionPool(connectionPool).build();
return this.okHttpClient; return this.okHttpClient;
} }
@PreDestroy @PreDestroy
public void destroy() { public void destroy() {
if(okHttpClient != null) { if (this.okHttpClient != null) {
okHttpClient.dispatcher().executorService().shutdown(); this.okHttpClient.dispatcher().executorService().shutdown();
okHttpClient.connectionPool().evictAll(); this.okHttpClient.connectionPool().evictAll();
} }
} }
@@ -205,6 +325,56 @@ public class FeignAutoConfiguration {
public Client feignClient(okhttp3.OkHttpClient client) { public Client feignClient(okhttp3.OkHttpClient client) {
return new OkHttpClient(client); return new OkHttpClient(client);
} }
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttp5Client.class)
@ConditionalOnMissingBean(org.apache.hc.client5.http.impl.classic.CloseableHttpClient.class)
@ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.hc5.enabled", havingValue = "true")
@Import(org.springframework.cloud.openfeign.clientconfig.HttpClient5FeignConfiguration.class)
protected static class HttpClient5FeignConfiguration {
@Bean
@ConditionalOnMissingBean(Client.class)
public Client feignClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient httpClient5) {
return new ApacheHttp5Client(httpClient5);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OAuth2ClientContext.class)
@ConditionalOnProperty("spring.cloud.openfeign.oauth2.enabled")
@Deprecated // spring-security-oauth2 reached EOL
protected static class Oauth2FeignConfiguration {
@ConditionalOnBean({ RetryLoadBalancerInterceptor.class, OAuth2ClientContext.class,
OAuth2ProtectedResourceDetails.class })
@ConditionalOnProperty(value = "spring.cloud.openfeign.oauth2.load-balanced", havingValue = "true")
@Bean
public OAuth2FeignRequestInterceptorConfigurer retryLoadBalancerInterceptorInjectingConfigurer(
final RetryLoadBalancerInterceptor loadBalancerInterceptor) {
return builder -> builder.withAccessTokenProviderInterceptors(loadBalancerInterceptor);
}
@ConditionalOnBean({ LoadBalancerInterceptor.class, OAuth2ClientContext.class,
OAuth2ProtectedResourceDetails.class })
@ConditionalOnProperty(value = "spring.cloud.openfeign.oauth2.load-balanced", havingValue = "true")
@Bean
public OAuth2FeignRequestInterceptorConfigurer loadBalancerInterceptorInjectingConfigurer(
final LoadBalancerInterceptor loadBalancerInterceptor) {
return builder -> builder.withAccessTokenProviderInterceptors(loadBalancerInterceptor);
}
@Bean
@ConditionalOnMissingBean(OAuth2FeignRequestInterceptor.class)
@ConditionalOnBean({ OAuth2ClientContext.class, OAuth2ProtectedResourceDetails.class })
public RequestInterceptor oauth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext,
OAuth2ProtectedResourceDetails resource, List<OAuth2FeignRequestInterceptorConfigurer> configurers) {
return buildWithConfigurers(oAuth2ClientContext, resource, configurers);
}
} }
} }
@@ -0,0 +1,31 @@
/*
* 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.Feign;
/**
* Allows application to customize the Feign builder.
*
* @author Matt King
*/
@FunctionalInterface
public interface FeignBuilderCustomizer {
void customize(Feign.Builder builder);
}
@@ -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;
}
});
};
}
}
@@ -0,0 +1,101 @@
/*
* 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.Feign;
import feign.Target;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
/**
* Allows Feign interfaces to work with {@link CircuitBreaker}.
*
* @author Marcin Grzejszczak
* @author Andrii Bohutskyi
* @author Kwangyong Kim
* @since 3.0.0
*/
public final class FeignCircuitBreaker {
private FeignCircuitBreaker() {
throw new IllegalStateException("Don't instantiate a utility class");
}
/**
* @return builder for Feign CircuitBreaker integration
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for Feign CircuitBreaker integration.
*/
public static final class Builder extends Feign.Builder {
private CircuitBreakerFactory circuitBreakerFactory;
private String feignClientName;
private boolean circuitBreakerGroupEnabled;
private CircuitBreakerNameResolver circuitBreakerNameResolver;
Builder circuitBreakerFactory(CircuitBreakerFactory circuitBreakerFactory) {
this.circuitBreakerFactory = circuitBreakerFactory;
return this;
}
Builder feignClientName(String feignClientName) {
this.feignClientName = feignClientName;
return this;
}
Builder circuitBreakerGroupEnabled(boolean circuitBreakerGroupEnabled) {
this.circuitBreakerGroupEnabled = circuitBreakerGroupEnabled;
return this;
}
Builder circuitBreakerNameResolver(CircuitBreakerNameResolver circuitBreakerNameResolver) {
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);
}
@Override
public <T> T target(Target<T> target) {
return build(null).newInstance(target);
}
public Feign build(final FallbackFactory<?> nullableFallbackFactory) {
super.invocationHandlerFactory((target, dispatch) -> new FeignCircuitBreakerInvocationHandler(
circuitBreakerFactory, feignClientName, target, dispatch, nullableFallbackFactory,
circuitBreakerGroupEnabled, circuitBreakerNameResolver));
return super.build();
}
}
}
@@ -0,0 +1,40 @@
/*
* 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 org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
class FeignCircuitBreakerDisabledConditions extends AnyNestedCondition {
FeignCircuitBreakerDisabledConditions() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnMissingClass("org.springframework.cloud.client.circuitbreaker.CircuitBreaker")
static class CircuitBreakerClassMissing {
}
@ConditionalOnProperty(value = "spring.cloud.openfeign.circuitbreaker.enabled", havingValue = "false",
matchIfMissing = true)
static class CircuitBreakerDisabled {
}
}
@@ -0,0 +1,176 @@
/*
* 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.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import feign.InvocationHandlerFactory;
import feign.Target;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
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;
class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
private final CircuitBreakerFactory factory;
private final String feignClientName;
private final Target<?> target;
private final Map<Method, InvocationHandlerFactory.MethodHandler> dispatch;
private final FallbackFactory<?> nullableFallbackFactory;
private final Map<Method, Method> fallbackMethodMap;
private final boolean circuitBreakerGroupEnabled;
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.feignClientName = feignClientName;
this.target = checkNotNull(target, "target");
this.dispatch = checkNotNull(dispatch, "dispatch");
this.fallbackMethodMap = toFallbackMethod(dispatch);
this.nullableFallbackFactory = nullableFallbackFactory;
this.circuitBreakerGroupEnabled = circuitBreakerGroupEnabled;
this.circuitBreakerNameResolver = circuitBreakerNameResolver;
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
// early exit if the invoked method is from java.lang.Object
// code is the same as ReflectiveFeign.FeignInvocationHandler
if ("equals".equals(method.getName())) {
try {
Object otherHandler = args.length > 0 && args[0] != null ? Proxy.getInvocationHandler(args[0]) : null;
return equals(otherHandler);
}
catch (IllegalArgumentException e) {
return false;
}
}
else if ("hashCode".equals(method.getName())) {
return hashCode();
}
else if ("toString".equals(method.getName())) {
return toString();
}
String circuitName = circuitBreakerNameResolver.resolveCircuitBreakerName(feignClientName, target, method);
CircuitBreaker circuitBreaker = circuitBreakerGroupEnabled ? factory.create(circuitName, feignClientName)
: factory.create(circuitName);
Supplier<Object> supplier = asSupplier(method, args);
if (this.nullableFallbackFactory != null) {
Function<Throwable, Object> fallbackFunction = throwable -> {
Object fallback = this.nullableFallbackFactory.create(throwable);
try {
return this.fallbackMethodMap.get(method).invoke(fallback, args);
}
catch (Exception exception) {
unwrapAndRethrow(exception);
}
return null;
};
return circuitBreaker.run(supplier, fallbackFunction);
}
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) {
final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return () -> {
try {
RequestContextHolder.setRequestAttributes(requestAttributes);
return dispatch.get(method).invoke(args);
}
catch (RuntimeException throwable) {
throw throwable;
}
catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
};
}
/**
* If the method param of InvocationHandler.invoke is not accessible, i.e in a
* package-private interface, the fallback call will cause of access restrictions. But
* methods in dispatch are copied methods. So setting access to dispatch method
* doesn't take effect to the method in InvocationHandler.invoke. Use map to store a
* copy of method to invoke the fallback to bypass this and reducing the count of
* reflection calls.
* @return cached methods map for fallback invoking
*/
static Map<Method, Method> toFallbackMethod(Map<Method, InvocationHandlerFactory.MethodHandler> dispatch) {
Map<Method, Method> result = new LinkedHashMap<Method, Method>();
for (Method method : dispatch.keySet()) {
method.setAccessible(true);
result.put(method, method);
}
return result;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof FeignCircuitBreakerInvocationHandler) {
FeignCircuitBreakerInvocationHandler other = (FeignCircuitBreakerInvocationHandler) obj;
return this.target.equals(other.target);
}
return false;
}
@Override
public int hashCode() {
return this.target.hashCode();
}
@Override
public String toString() {
return this.target.toString();
}
}
@@ -0,0 +1,96 @@
/*
* 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.Feign;
import feign.Target;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.util.StringUtils;
@SuppressWarnings("unchecked")
class FeignCircuitBreakerTargeter implements Targeter {
private final CircuitBreakerFactory circuitBreakerFactory;
private final boolean circuitBreakerGroupEnabled;
private final CircuitBreakerNameResolver circuitBreakerNameResolver;
FeignCircuitBreakerTargeter(CircuitBreakerFactory circuitBreakerFactory, boolean circuitBreakerGroupEnabled,
CircuitBreakerNameResolver circuitBreakerNameResolver) {
this.circuitBreakerFactory = circuitBreakerFactory;
this.circuitBreakerGroupEnabled = circuitBreakerGroupEnabled;
this.circuitBreakerNameResolver = circuitBreakerNameResolver;
}
@Override
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context,
Target.HardCodedTarget<T> target) {
if (!(feign instanceof FeignCircuitBreaker.Builder)) {
return feign.target(target);
}
FeignCircuitBreaker.Builder builder = (FeignCircuitBreaker.Builder) feign;
String name = !StringUtils.hasText(factory.getContextId()) ? factory.getName() : factory.getContextId();
Class<?> fallback = factory.getFallback();
if (fallback != void.class) {
return targetWithFallback(name, context, target, builder, fallback);
}
Class<?> fallbackFactory = factory.getFallbackFactory();
if (fallbackFactory != void.class) {
return targetWithFallbackFactory(name, context, target, builder, fallbackFactory);
}
return builder(name, builder).target(target);
}
private <T> T targetWithFallbackFactory(String feignClientName, FeignContext context,
Target.HardCodedTarget<T> target, FeignCircuitBreaker.Builder builder, Class<?> fallbackFactoryClass) {
FallbackFactory<? extends T> fallbackFactory = (FallbackFactory<? extends T>) getFromContext("fallbackFactory",
feignClientName, context, fallbackFactoryClass, FallbackFactory.class);
return builder(feignClientName, builder).target(target, fallbackFactory);
}
private <T> T targetWithFallback(String feignClientName, FeignContext context, Target.HardCodedTarget<T> target,
FeignCircuitBreaker.Builder builder, Class<?> fallback) {
T fallbackInstance = getFromContext("fallback", feignClientName, context, fallback, target.type());
return builder(feignClientName, builder).target(target, fallbackInstance);
}
private <T> T getFromContext(String fallbackMechanism, String feignClientName, FeignContext context,
Class<?> beanType, Class<T> targetType) {
Object fallbackInstance = context.getInstance(feignClientName, beanType);
if (fallbackInstance == null) {
throw new IllegalStateException(
String.format("No " + fallbackMechanism + " instance of type %s found for feign client %s",
beanType, feignClientName));
}
if (!targetType.isAssignableFrom(beanType)) {
throw new IllegalStateException(String.format("Incompatible " + fallbackMechanism
+ " instance. Fallback/fallbackFactory of type %s is not assignable to %s for feign client %s",
beanType, targetType, feignClientName));
}
return (T) fallbackInstance;
}
private FeignCircuitBreaker.Builder builder(String feignClientName, FeignCircuitBreaker.Builder builder) {
return builder.circuitBreakerFactory(circuitBreakerFactory).feignClientName(feignClientName)
.circuitBreakerGroupEnabled(circuitBreakerGroupEnabled)
.circuitBreakerNameResolver(circuitBreakerNameResolver);
}
}
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2016 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -18,6 +18,7 @@ package org.springframework.cloud.openfeign;
import java.lang.annotation.Documented; import java.lang.annotation.Documented;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
@@ -26,88 +27,111 @@ 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
* @author Olga Maciaszek-Sharma
*/ */
@Target(ElementType.TYPE) @Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Documented @Documented
@Inherited
public @interface FeignClient { public @interface FeignClient {
/** /**
* The name of the service with optional protocol prefix. Synonym for {@link #name() * The name of the service with optional protocol prefix. Synonym for {@link #name()
* name}. A name must be specified for all clients, whether or not a url is provided. * name}. A name must be specified for all clients, whether or not a url is provided.
* Can be specified as property key, eg: ${propertyKey}. * Can be specified as property key, eg: ${propertyKey}.
* @return the name of the service with optional protocol prefix
*/ */
@AliasFor("name") @AliasFor("name")
String value() default ""; String value() default "";
/** /**
* The service id with optional protocol prefix. Synonym for {@link #value() value}. * This will be used as the bean name instead of name if present, but will not be used
* * as a service id.
* @deprecated use {@link #name() name} instead * @return bean name instead of name if present
*/ */
@Deprecated String contextId() default "";
String serviceId() default "";
/** /**
* The service id with optional protocol prefix. Synonym for {@link #value() value}. * @return The service id with optional protocol prefix. Synonym for {@link #value()
* value}.
*/ */
@AliasFor("value") @AliasFor("value")
String name() default ""; String name() default "";
/** /**
* Sets the <code>@Qualifier</code> value for the feign client. * @return the <code>@Qualifier</code> value for the feign client.
* @deprecated in favour of {@link #qualifiers()}.
*
* If both {@link #qualifier()} and {@link #qualifiers()} are present, we will use the
* latter, unless the array returned by {@link #qualifiers()} is empty or only
* contains <code>null</code> or whitespace values, in which case we'll fall back
* first to {@link #qualifier()} and, if that's also not present, to the default =
* <code>contextId + "FeignClient"</code>.
*/ */
@Deprecated
String qualifier() default ""; String qualifier() default "";
/** /**
* An absolute URL or resolvable hostname (the protocol is optional). * @return the <code>@Qualifiers</code> value for the feign client.
*
* If both {@link #qualifier()} and {@link #qualifiers()} are present, we will use the
* latter, unless the array returned by {@link #qualifiers()} is empty or only
* contains <code>null</code> or whitespace values, in which case we'll fall back
* first to {@link #qualifier()} and, if that's also not present, to the default =
* <code>contextId + "FeignClient"</code>.
*/
String[] qualifiers() default {};
/**
* @return an absolute URL or resolvable hostname (the protocol is optional).
*/ */
String url() default ""; String url() default "";
/** /**
* Whether 404s should be decoded instead of throwing FeignExceptions * @return whether 404s should be decoded instead of throwing FeignExceptions
*/ */
boolean decode404() default false; boolean decode404() default false;
/** /**
* A custom <code>@Configuration</code> for the feign client. Can contain override * A custom configuration class for the feign client. Can contain override
* <code>@Bean</code> definition for the pieces that make up the client, for instance * <code>@Bean</code> definition for the pieces that make up the client, for instance
* {@link feign.codec.Decoder}, {@link feign.codec.Encoder}, {@link feign.Contract}. * {@link feign.codec.Decoder}, {@link feign.codec.Encoder}, {@link feign.Contract}.
* *
* @see FeignClientsConfiguration for the defaults * @see FeignClientsConfiguration for the defaults
* @return list of configurations for feign client
*/ */
Class<?>[] configuration() default {}; Class<?>[] configuration() default {};
/** /**
* Fallback class for the specified Feign client interface. The fallback class must * Fallback class for the specified Feign client interface. The fallback class must
* implement the interface annotated by this annotation and be a valid spring bean. * implement the interface annotated by this annotation and be a valid spring bean.
* @return fallback class for the specified Feign client interface
*/ */
Class<?> fallback() default void.class; Class<?> fallback() default void.class;
/** /**
* Define a fallback factory for the specified Feign client interface. The fallback * Define a fallback factory for the specified Feign client interface. The fallback
* 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 * annotated by {@link FeignClient}. The fallback factory must be a valid spring bean.
* bean.
* *
* @see feign.hystrix.FallbackFactory for details. * @see FallbackFactory for details.
* @return fallback factory for the specified Feign client interface
*/ */
Class<?> fallbackFactory() default void.class; Class<?> fallbackFactory() default void.class;
/** /**
* Path prefix to be used by all method-level mappings. Can be used with or without * @return path prefix to be used by all method-level mappings.
* <code>@RibbonClient</code>.
*/ */
String path() default ""; String path() default "";
/** /**
* Whether to mark the feign proxy as a primary bean. Defaults to true. * @return whether to mark the feign proxy as a primary bean. Defaults to true.
*/ */
boolean primary() default true; boolean primary() default true;
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2018 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import feign.Feign;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
/** /**
@@ -25,6 +27,8 @@ import org.springframework.context.ApplicationContext;
* {@link FeignClient} annotation. * {@link FeignClient} annotation.
* *
* @author Sven Döring * @author Sven Döring
* @author Matt King
* @author Sam Kruglov
*/ */
public class FeignClientBuilder { public class FeignClientBuilder {
@@ -35,59 +39,91 @@ public class FeignClientBuilder {
} }
public <T> Builder<T> forType(final Class<T> type, final String name) { public <T> Builder<T> forType(final Class<T> type, final String name) {
return new Builder<>(applicationContext, type, name); return new Builder<>(this.applicationContext, type, name);
} }
public static class Builder<T> { 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.
*
* @param <T> type of target
*/
public static final class Builder<T> {
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);
this.feignClientFactoryBean.setName(FeignClientsRegistrar.getName(name)); this.feignClientFactoryBean.setName(FeignClientsRegistrar.getName(name));
this.feignClientFactoryBean.setContextId(FeignClientsRegistrar.getName(name));
this.feignClientFactoryBean.setInheritParentContext(true);
// preset default values - these values resemble the default values on the // preset default values - these values resemble the default values on the
// FeignClient annotation // FeignClient annotation
this.url("").path("").decode404(false).fallback(void.class) this.url("").path("").decode404(false);
.fallbackFactory(void.class);
} }
public Builder url(final String url) { public Builder<T> url(final String url) {
this.feignClientFactoryBean.setUrl(FeignClientsRegistrar.getUrl(url)); this.feignClientFactoryBean.setUrl(FeignClientsRegistrar.getUrl(url));
return this; return this;
} }
public Builder path(final String path) { /**
* Applies a {@link FeignBuilderCustomizer} to the underlying
* {@link Feign.Builder}. May be called multiple times.
* @param customizer applied in the same order as supplied here after applying
* customizers found in the context.
* @return the {@link Builder} with the customizer added
*/
public Builder<T> customize(final FeignBuilderCustomizer customizer) {
this.feignClientFactoryBean.addCustomizer(customizer);
return this;
}
public Builder<T> contextId(final String contextId) {
this.feignClientFactoryBean.setContextId(contextId);
return this;
}
public Builder<T> path(final String path) {
this.feignClientFactoryBean.setPath(FeignClientsRegistrar.getPath(path)); this.feignClientFactoryBean.setPath(FeignClientsRegistrar.getPath(path));
return this; return this;
} }
public Builder decode404(final boolean decode404) { public Builder<T> decode404(final boolean decode404) {
this.feignClientFactoryBean.setDecode404(decode404); this.feignClientFactoryBean.setDecode404(decode404);
return this; return this;
} }
public Builder fallback(final Class<T> fallback) { public Builder<T> inheritParentContext(final boolean inheritParentContext) {
this.feignClientFactoryBean.setInheritParentContext(inheritParentContext);
return this;
}
public Builder<T> fallback(final Class<? extends T> fallback) {
FeignClientsRegistrar.validateFallback(fallback); FeignClientsRegistrar.validateFallback(fallback);
this.feignClientFactoryBean.setFallback(fallback); this.feignClientFactoryBean.setFallback(fallback);
return this; return this;
} }
public Builder fallbackFactory(final Class<T> fallbackFactory) {
FeignClientsRegistrar.validateFallbackFactory(fallbackFactory);
this.feignClientFactoryBean.setFallbackFactory(fallbackFactory);
return this;
}
/** /**
* @param <T> the target type of the Feign client to be created
* @return the created Feign client * @return the created Feign client
*/ */
public <T> T build() { public T build() {
return this.feignClientFactoryBean.getTarget(); return this.feignClientFactoryBean.getTarget();
} }
} }
} }
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2018 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,24 +16,20 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import java.util.ArrayList;
import java.util.Collection;
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 org.springframework.beans.BeanUtils; import feign.Capability;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import feign.Client; import feign.Client;
import feign.Contract; import feign.Contract;
import feign.ExceptionPropagationPolicy;
import feign.Feign; import feign.Feign;
import feign.Logger; import feign.Logger;
import feign.QueryMapEncoder;
import feign.Request; import feign.Request;
import feign.RequestInterceptor; import feign.RequestInterceptor;
import feign.Retryer; import feign.Retryer;
@@ -41,48 +37,91 @@ import feign.Target.HardCodedTarget;
import feign.codec.Decoder; import feign.codec.Decoder;
import feign.codec.Encoder; import feign.codec.Encoder;
import feign.codec.ErrorDecoder; import feign.codec.ErrorDecoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer;
import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient;
import org.springframework.cloud.openfeign.loadbalancer.RetryableFeignBlockingLoadBalancerClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
* @author Venil Noronha * @author Venil Noronha
* @author Eko Kurniawan Khannedy * @author Eko Kurniawan Khannedy
* @author Gregor Zurowski * @author Gregor Zurowski
* @author Matt King
* @author Olga Maciaszek-Sharma
* @author Ilia Ilinykh
* @author Marcin Grzejszczak
* @author Jonatan Ivanov
* @author Sam Kruglov
* @author Jasbir Singh
* @author Hyeonmin Park
* @author Felix Dittrich
*/ */
class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean, public class FeignClientFactoryBean
ApplicationContextAware { implements FactoryBean<Object>, InitializingBean, ApplicationContextAware, BeanFactoryAware {
/*********************************** /***********************************
* WARNING! Nothing in this class should be @Autowired. It causes NPEs because of some lifecycle race condition. * WARNING! Nothing in this class should be @Autowired. It causes NPEs because of some
* lifecycle race condition.
***********************************/ ***********************************/
private static Log LOG = LogFactory.getLog(FeignClientFactoryBean.class);
private Class<?> type; private Class<?> type;
private String name; private String name;
private String url; private String url;
private String contextId;
private String path; private String path;
private boolean decode404; private boolean decode404;
private boolean inheritParentContext = true;
private ApplicationContext applicationContext; private ApplicationContext applicationContext;
private BeanFactory beanFactory;
private Class<?> fallback = void.class; private Class<?> fallback = void.class;
private Class<?> fallbackFactory = void.class; private Class<?> fallbackFactory = void.class;
@Override private int readTimeoutMillis = new Request.Options().readTimeoutMillis();
public void afterPropertiesSet() throws Exception {
Assert.hasText(this.name, "Name must be set"); private int connectTimeoutMillis = new Request.Options().connectTimeoutMillis();
}
private boolean followRedirects = new Request.Options().isFollowRedirects();
private boolean refreshableClient = false;
private final List<FeignBuilderCustomizer> additionalCustomizers = new ArrayList<>();
@Override @Override
public void setApplicationContext(ApplicationContext context) throws BeansException { public void afterPropertiesSet() {
this.applicationContext = context; Assert.hasText(contextId, "Context id must be set");
Assert.hasText(name, "Name must be set");
} }
protected Feign.Builder feign(FeignContext context) { protected Feign.Builder feign(FeignContext context) {
FeignLoggerFactory loggerFactory = get(context, FeignLoggerFactory.class); FeignLoggerFactory loggerFactory = get(context, FeignLoggerFactory.class);
Logger logger = loggerFactory.create(this.type); Logger logger = loggerFactory.create(type);
// @formatter:off // @formatter:off
Feign.Builder builder = get(context, Feign.Builder.class) Feign.Builder builder = get(context, Feign.Builder.class)
@@ -98,52 +137,101 @@ class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean,
return builder; return builder;
} }
private void applyBuildCustomizers(FeignContext context, Feign.Builder builder) {
Map<String, FeignBuilderCustomizer> customizerMap = context.getInstances(contextId,
FeignBuilderCustomizer.class);
if (customizerMap != null) {
customizerMap.values().stream().sorted(AnnotationAwareOrderComparator.INSTANCE)
.forEach(feignBuilderCustomizer -> feignBuilderCustomizer.customize(builder));
}
additionalCustomizers.forEach(customizer -> customizer.customize(builder));
}
protected void configureFeign(FeignContext context, Feign.Builder builder) { protected void configureFeign(FeignContext context, Feign.Builder builder) {
FeignClientProperties properties = applicationContext.getBean(FeignClientProperties.class); FeignClientProperties properties = beanFactory != null ? beanFactory.getBean(FeignClientProperties.class)
if (properties != null) { : applicationContext.getBean(FeignClientProperties.class);
FeignClientConfigurer feignClientConfigurer = getOptional(context, FeignClientConfigurer.class);
setInheritParentContext(feignClientConfigurer.inheritParentConfiguration());
if (properties != null && inheritParentContext) {
if (properties.isDefaultToProperties()) { if (properties.isDefaultToProperties()) {
configureUsingConfiguration(context, builder); configureUsingConfiguration(context, builder);
configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder); configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder);
configureUsingProperties(properties.getConfig().get(this.name), builder); configureUsingProperties(properties.getConfig().get(contextId), builder);
} else { }
else {
configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder); configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder);
configureUsingProperties(properties.getConfig().get(this.name), builder); configureUsingProperties(properties.getConfig().get(contextId), builder);
configureUsingConfiguration(context, builder); configureUsingConfiguration(context, builder);
} }
} else { }
else {
configureUsingConfiguration(context, builder); configureUsingConfiguration(context, builder);
} }
} }
protected void configureUsingConfiguration(FeignContext context, Feign.Builder builder) { protected void configureUsingConfiguration(FeignContext context, Feign.Builder builder) {
Logger.Level level = getOptional(context, Logger.Level.class); Logger.Level level = getInheritedAwareOptional(context, Logger.Level.class);
if (level != null) { if (level != null) {
builder.logLevel(level); builder.logLevel(level);
} }
Retryer retryer = getOptional(context, Retryer.class); Retryer retryer = getInheritedAwareOptional(context, Retryer.class);
if (retryer != null) { if (retryer != null) {
builder.retryer(retryer); builder.retryer(retryer);
} }
ErrorDecoder errorDecoder = getOptional(context, ErrorDecoder.class); ErrorDecoder errorDecoder = getInheritedAwareOptional(context, ErrorDecoder.class);
if (errorDecoder != null) { if (errorDecoder != null) {
builder.errorDecoder(errorDecoder); builder.errorDecoder(errorDecoder);
} }
Request.Options options = getOptional(context, Request.Options.class); else {
if (options != null) { FeignErrorDecoderFactory errorDecoderFactory = getOptional(context, FeignErrorDecoderFactory.class);
builder.options(options); if (errorDecoderFactory != null) {
ErrorDecoder factoryErrorDecoder = errorDecoderFactory.create(type);
builder.errorDecoder(factoryErrorDecoder);
}
} }
Map<String, RequestInterceptor> requestInterceptors = context.getInstances( Request.Options options = getInheritedAwareOptional(context, Request.Options.class);
this.name, RequestInterceptor.class); if (options == null) {
if (requestInterceptors != null) { options = getOptionsByName(context, contextId);
builder.requestInterceptors(requestInterceptors.values());
} }
if (options != null) {
builder.options(options);
readTimeoutMillis = options.readTimeoutMillis();
connectTimeoutMillis = options.connectTimeoutMillis();
followRedirects = options.isFollowRedirects();
}
Map<String, RequestInterceptor> requestInterceptors = getInheritedAwareInstances(context,
RequestInterceptor.class);
if (requestInterceptors != null) {
List<RequestInterceptor> interceptors = new ArrayList<>(requestInterceptors.values());
AnnotationAwareOrderComparator.sort(interceptors);
builder.requestInterceptors(interceptors);
}
QueryMapEncoder queryMapEncoder = getInheritedAwareOptional(context, QueryMapEncoder.class);
if (queryMapEncoder != null) {
builder.queryMapEncoder(queryMapEncoder);
}
if (decode404) { if (decode404) {
builder.decode404(); builder.decode404();
} }
ExceptionPropagationPolicy exceptionPropagationPolicy = getInheritedAwareOptional(context,
ExceptionPropagationPolicy.class);
if (exceptionPropagationPolicy != null) {
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(FeignClientProperties.FeignClientConfiguration config, Feign.Builder builder) { protected void configureUsingProperties(FeignClientProperties.FeignClientConfiguration config,
Feign.Builder builder) {
if (config == null) { if (config == null) {
return; return;
} }
@@ -152,8 +240,14 @@ class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean,
builder.logLevel(config.getLoggerLevel()); builder.logLevel(config.getLoggerLevel());
} }
if (config.getConnectTimeout() != null && config.getReadTimeout() != null) { if (!refreshableClient) {
builder.options(new Request.Options(config.getConnectTimeout(), config.getReadTimeout())); connectTimeoutMillis = config.getConnectTimeout() != null ? config.getConnectTimeout()
: connectTimeoutMillis;
readTimeoutMillis = config.getReadTimeout() != null ? config.getReadTimeout() : readTimeoutMillis;
followRedirects = config.isFollowRedirects() != null ? config.isFollowRedirects() : followRedirects;
builder.options(new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS, readTimeoutMillis,
TimeUnit.MILLISECONDS, followRedirects));
} }
if (config.getRetryer() != null) { if (config.getRetryer() != null) {
@@ -184,6 +278,9 @@ class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean,
builder.encoder(getOrInstantiate(config.getEncoder())); builder.encoder(getOrInstantiate(config.getEncoder()));
} }
addDefaultRequestHeaders(config, builder);
addDefaultQueryParams(config, builder);
if (Objects.nonNull(config.getDecoder())) { if (Objects.nonNull(config.getDecoder())) {
builder.decoder(getOrInstantiate(config.getDecoder())); builder.decoder(getOrInstantiate(config.getDecoder()));
} }
@@ -191,86 +288,173 @@ class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean,
if (Objects.nonNull(config.getContract())) { if (Objects.nonNull(config.getContract())) {
builder.contract(getOrInstantiate(config.getContract())); builder.contract(getOrInstantiate(config.getContract()));
} }
if (Objects.nonNull(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 applicationContext.getBean(tClass); return beanFactory != null ? beanFactory.getBean(tClass) : applicationContext.getBean(tClass);
} catch (NoSuchBeanDefinitionException e) { }
catch (NoSuchBeanDefinitionException e) {
return BeanUtils.instantiateClass(tClass); return BeanUtils.instantiateClass(tClass);
} }
} }
protected <T> T get(FeignContext context, Class<T> type) { protected <T> T get(FeignContext context, Class<T> type) {
T instance = context.getInstance(this.name, type); T instance = context.getInstance(contextId, type);
if (instance == null) { if (instance == null) {
throw new IllegalStateException("No bean found of type " + type + " for " throw new IllegalStateException("No bean found of type " + type + " for " + contextId);
+ this.name);
} }
return instance; return instance;
} }
protected <T> T getOptional(FeignContext context, Class<T> type) { protected <T> T getOptional(FeignContext context, Class<T> type) {
return context.getInstance(this.name, type); return context.getInstance(contextId, type);
} }
protected <T> T loadBalance(Feign.Builder builder, FeignContext context, protected <T> T getInheritedAwareOptional(FeignContext context, Class<T> type) {
HardCodedTarget<T> target) { if (inheritParentContext) {
return getOptional(context, type);
}
else {
return context.getInstanceWithoutAncestors(contextId, type);
}
}
protected <T> Map<String, T> getInheritedAwareInstances(FeignContext context, Class<T> type) {
if (inheritParentContext) {
return context.getInstances(contextId, type);
}
else {
return context.getInstancesWithoutAncestors(contextId, type);
}
}
protected <T> T loadBalance(Feign.Builder builder, FeignContext context, 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?"); "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
public Object getObject() throws Exception { public Object getObject() {
return getTarget(); return getTarget();
} }
/** /**
* @param <T> the target type of the Feign client * @param <T> the target type of the Feign client
* @return a {@link Feign} client created with the specified data and the context information * @return a {@link Feign} client created with the specified data and the context
* information
*/ */
<T> T getTarget() { <T> T getTarget() {
FeignContext context = applicationContext.getBean(FeignContext.class); FeignContext context = beanFactory != null ? beanFactory.getBean(FeignContext.class)
: applicationContext.getBean(FeignContext.class);
Feign.Builder builder = feign(context); Feign.Builder builder = feign(context);
if (!StringUtils.hasText(this.url)) { if (!StringUtils.hasText(url)) {
String url;
if (!this.name.startsWith("http")) { if (LOG.isInfoEnabled()) {
url = "http://" + this.name; LOG.info("For '" + name + "' URL not provided. Will try picking an instance via load-balancing.");
}
if (!name.startsWith("http")) {
url = "http://" + name;
} }
else { else {
url = this.name; url = name;
} }
url += cleanPath(); url += cleanPath();
return (T) loadBalance(builder, context, new HardCodedTarget<>(this.type, return (T) loadBalance(builder, context, new HardCodedTarget<>(type, name, url));
this.name, url));
} }
if (StringUtils.hasText(this.url) && !this.url.startsWith("http")) { if (StringUtils.hasText(url) && !url.startsWith("http")) {
this.url = "http://" + this.url; url = "http://" + url;
} }
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) { if (client instanceof FeignBlockingLoadBalancerClient) {
// not load balancing because we have a url, // not load balancing because we have a url,
// but ribbon is on the classpath, so unwrap // but Spring Cloud LoadBalancer is on the classpath, so unwrap
client = ((LoadBalancerFeignClient)client).getDelegate(); client = ((FeignBlockingLoadBalancerClient) client).getDelegate();
}
if (client instanceof RetryableFeignBlockingLoadBalancerClient) {
// not load balancing because we have a url,
// but Spring Cloud LoadBalancer is on the classpath, so unwrap
client = ((RetryableFeignBlockingLoadBalancerClient) client).getDelegate();
} }
builder.client(client); builder.client(client);
} }
applyBuildCustomizers(context, builder);
Targeter targeter = get(context, Targeter.class); Targeter targeter = get(context, Targeter.class);
return (T) targeter.target(this, builder, context, new HardCodedTarget<>( return (T) targeter.target(this, builder, context, new HardCodedTarget<>(type, name, url));
this.type, this.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("/")) {
@@ -285,7 +469,7 @@ class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean,
@Override @Override
public Class<?> getObjectType() { public Class<?> getObjectType() {
return this.type; return type;
} }
@Override @Override
@@ -309,6 +493,14 @@ class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean,
this.name = name; this.name = name;
} }
public String getContextId() {
return contextId;
}
public void setContextId(String contextId) {
this.contextId = contextId;
}
public String getUrl() { public String getUrl() {
return url; return url;
} }
@@ -333,10 +525,28 @@ class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean,
this.decode404 = decode404; this.decode404 = decode404;
} }
public boolean isInheritParentContext() {
return inheritParentContext;
}
public void setInheritParentContext(boolean inheritParentContext) {
this.inheritParentContext = inheritParentContext;
}
public void addCustomizer(FeignBuilderCustomizer customizer) {
additionalCustomizers.add(customizer);
}
public ApplicationContext getApplicationContext() { public ApplicationContext getApplicationContext() {
return applicationContext; return applicationContext;
} }
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
beanFactory = context;
}
public Class<?> getFallback() { public Class<?> getFallback() {
return fallback; return fallback;
} }
@@ -353,39 +563,52 @@ class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean,
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) return true; if (this == o) {
if (o == null || getClass() != o.getClass()) return false; return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FeignClientFactoryBean that = (FeignClientFactoryBean) o; FeignClientFactoryBean that = (FeignClientFactoryBean) o;
return Objects.equals(applicationContext, that.applicationContext) && return Objects.equals(applicationContext, that.applicationContext)
decode404 == that.decode404 && && Objects.equals(beanFactory, that.beanFactory) && decode404 == that.decode404
Objects.equals(fallback, that.fallback) && && inheritParentContext == that.inheritParentContext && Objects.equals(fallback, that.fallback)
Objects.equals(fallbackFactory, that.fallbackFactory) && && Objects.equals(fallbackFactory, that.fallbackFactory) && Objects.equals(name, that.name)
Objects.equals(name, that.name) && && Objects.equals(path, that.path) && Objects.equals(type, that.type) && Objects.equals(url, that.url)
Objects.equals(path, that.path) && && Objects.equals(connectTimeoutMillis, that.connectTimeoutMillis)
Objects.equals(type, that.type) && && Objects.equals(readTimeoutMillis, that.readTimeoutMillis)
Objects.equals(url, that.url); && Objects.equals(followRedirects, that.followRedirects)
&& Objects.equals(refreshableClient, that.refreshableClient);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(applicationContext, decode404, fallback, fallbackFactory, return Objects.hash(applicationContext, beanFactory, decode404, inheritParentContext, fallback, fallbackFactory,
name, path, type, url); name, path, type, url, readTimeoutMillis, connectTimeoutMillis, followRedirects, refreshableClient);
} }
@Override @Override
public String toString() { public String toString() {
return new StringBuilder("FeignClientFactoryBean{") return new StringBuilder("FeignClientFactoryBean{").append("type=").append(type).append(", ").append("name='")
.append("type=").append(type).append(", ") .append(name).append("', ").append("url='").append(url).append("', ").append("path='").append(path)
.append("name='").append(name).append("', ") .append("', ").append("decode404=").append(decode404).append(", ").append("inheritParentContext=")
.append("url='").append(url).append("', ") .append(inheritParentContext).append(", ").append("applicationContext=").append(applicationContext)
.append("path='").append(path).append("', ") .append(", ").append("beanFactory=").append(beanFactory).append(", ").append("fallback=")
.append("decode404=").append(decode404).append(", ") .append(fallback).append(", ").append("fallbackFactory=").append(fallbackFactory).append("}")
.append("applicationContext=").append(applicationContext).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("refreshableClient=").append(refreshableClient).append("}").toString();
.append("}").toString(); }
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
} }
} }
@@ -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,11 +1,11 @@
/* /*
* Copyright 2013-2017 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -13,26 +13,37 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import feign.Contract; import java.util.Collection;
import feign.Logger;
import feign.RequestInterceptor;
import feign.Retryer;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.Objects; import java.util.Objects;
import feign.Capability;
import feign.Contract;
import feign.ExceptionPropagationPolicy;
import feign.Logger;
import feign.QueryMapEncoder;
import feign.RequestInterceptor;
import feign.Retryer;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import org.springframework.boot.context.properties.ConfigurationProperties;
/** /**
* @author Eko Kurniawan Khannedy * @author Eko Kurniawan Khannedy
* @author Ilia Ilinykh
* @author Ram Anaswara
* @author Jonatan Ivanov
* @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;
@@ -41,6 +52,12 @@ public class FeignClientProperties {
private Map<String, FeignClientConfiguration> config = new HashMap<>(); private Map<String, FeignClientConfiguration> config = new HashMap<>();
/**
* Feign clients do not encode slash `/` characters by default. To change this
* behavior, set the `decodeSlash` to `false`.
*/
private boolean decodeSlash = true;
public boolean isDefaultToProperties() { public boolean isDefaultToProperties() {
return defaultToProperties; return defaultToProperties;
} }
@@ -65,21 +82,35 @@ public class FeignClientProperties {
this.config = config; this.config = config;
} }
public boolean isDecodeSlash() {
return decodeSlash;
}
public void setDecodeSlash(boolean decodeSlash) {
this.decodeSlash = decodeSlash;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) {
if (o == null || getClass() != o.getClass()) return false; return true;
}
if (o == null || getClass() != o.getClass()) {
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);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(defaultToProperties, defaultConfig, config); return Objects.hash(defaultToProperties, defaultConfig, config, decodeSlash);
} }
/**
* Feign client configuration.
*/
public static class FeignClientConfiguration { public static class FeignClientConfiguration {
private Logger.Level loggerLevel; private Logger.Level loggerLevel;
@@ -94,6 +125,10 @@ public class FeignClientProperties {
private List<Class<RequestInterceptor>> requestInterceptors; private List<Class<RequestInterceptor>> requestInterceptors;
private Map<String, Collection<String>> defaultRequestHeaders;
private Map<String, Collection<String>> defaultQueryParameters;
private Boolean decode404; private Boolean decode404;
private Class<Decoder> decoder; private Class<Decoder> decoder;
@@ -102,6 +137,16 @@ public class FeignClientProperties {
private Class<Contract> contract; private Class<Contract> contract;
private ExceptionPropagationPolicy exceptionPropagationPolicy;
private List<Class<Capability>> capabilities;
private Class<QueryMapEncoder> queryMapEncoder;
private MetricsProperties metrics;
private Boolean followRedirects;
public Logger.Level getLoggerLevel() { public Logger.Level getLoggerLevel() {
return loggerLevel; return loggerLevel;
} }
@@ -150,6 +195,22 @@ public class FeignClientProperties {
this.requestInterceptors = requestInterceptors; this.requestInterceptors = requestInterceptors;
} }
public Map<String, Collection<String>> getDefaultRequestHeaders() {
return defaultRequestHeaders;
}
public void setDefaultRequestHeaders(Map<String, Collection<String>> defaultRequestHeaders) {
this.defaultRequestHeaders = defaultRequestHeaders;
}
public Map<String, Collection<String>> getDefaultQueryParameters() {
return defaultQueryParameters;
}
public void setDefaultQueryParameters(Map<String, Collection<String>> defaultQueryParameters) {
this.defaultQueryParameters = defaultQueryParameters;
}
public Boolean getDecode404() { public Boolean getDecode404() {
return decode404; return decode404;
} }
@@ -182,28 +243,111 @@ public class FeignClientProperties {
this.contract = contract; this.contract = contract;
} }
public ExceptionPropagationPolicy getExceptionPropagationPolicy() {
return exceptionPropagationPolicy;
}
public void setExceptionPropagationPolicy(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() {
return followRedirects;
}
public void setFollowRedirects(Boolean followRedirects) {
this.followRedirects = followRedirects;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) {
if (o == null || getClass() != o.getClass()) return false; return true;
}
if (o == null || getClass() != o.getClass()) {
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(errorDecoder, that.errorDecoder)
Objects.equals(retryer, that.retryer) && && Objects.equals(requestInterceptors, that.requestInterceptors)
Objects.equals(errorDecoder, that.errorDecoder) && && Objects.equals(decode404, that.decode404) && Objects.equals(encoder, that.encoder)
Objects.equals(requestInterceptors, that.requestInterceptors) && && Objects.equals(decoder, that.decoder) && Objects.equals(contract, that.contract)
Objects.equals(decode404, that.decode404) && && Objects.equals(exceptionPropagationPolicy, that.exceptionPropagationPolicy)
Objects.equals(encoder, that.encoder) && && Objects.equals(defaultRequestHeaders, that.defaultRequestHeaders)
Objects.equals(decoder, that.decoder) && && Objects.equals(defaultQueryParameters, that.defaultQueryParameters)
Objects.equals(contract, that.contract); && Objects.equals(capabilities, that.capabilities)
&& Objects.equals(queryMapEncoder, that.queryMapEncoder) && Objects.equals(metrics, that.metrics)
&& 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, contract); decode404, encoder, decoder, contract, exceptionPropagationPolicy, defaultQueryParameters,
defaultRequestHeaders, capabilities, queryMapEncoder, metrics, 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,11 +1,11 @@
/* /*
* Copyright 2013-2015 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,22 +16,23 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import org.springframework.cloud.context.named.NamedContextFactory;
import java.util.Arrays; import java.util.Arrays;
import java.util.Objects; import java.util.Objects;
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;
private Class<?>[] configuration; private Class<?>[] configuration;
public FeignClientSpecification() {} FeignClientSpecification() {
}
public FeignClientSpecification(String name, Class<?>[] configuration) { public FeignClientSpecification(String name, Class<?>[] configuration) {
this.name = name; this.name = name;
@@ -39,7 +40,7 @@ class FeignClientSpecification implements NamedContextFactory.Specification {
} }
public String getName() { public String getName() {
return name; return this.name;
} }
public void setName(String name) { public void setName(String name) {
@@ -47,7 +48,7 @@ class FeignClientSpecification implements NamedContextFactory.Specification {
} }
public Class<?>[] getConfiguration() { public Class<?>[] getConfiguration() {
return configuration; return this.configuration;
} }
public void setConfiguration(Class<?>[] configuration) { public void setConfiguration(Class<?>[] configuration) {
@@ -56,24 +57,25 @@ class FeignClientSpecification implements NamedContextFactory.Specification {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) {
if (o == null || getClass() != o.getClass()) return false; return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FeignClientSpecification that = (FeignClientSpecification) o; FeignClientSpecification that = (FeignClientSpecification) o;
return Objects.equals(name, that.name) && return Objects.equals(this.name, that.name) && Arrays.equals(this.configuration, that.configuration);
Arrays.equals(configuration, that.configuration);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(name, configuration); return Objects.hash(this.name, this.configuration);
} }
@Override @Override
public String toString() { public String toString() {
return new StringBuilder("FeignClientSpecification{") return new StringBuilder("FeignClientSpecification{").append("name='").append(this.name).append("', ")
.append("name='").append(name).append("', ") .append("configuration=").append(Arrays.toString(this.configuration)).append("}").toString();
.append("configuration=").append(Arrays.toString(configuration))
.append("}").toString();
} }
} }
@@ -1,18 +1,17 @@
/* /*
* Copyright 2013-2017 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*
*/ */
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
@@ -20,39 +19,61 @@ package org.springframework.cloud.openfeign;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import feign.Contract;
import feign.Feign;
import feign.Logger;
import feign.QueryMapEncoder;
import feign.Retryer;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.form.MultipartFormContentProcessor;
import feign.form.spring.SpringFormEncoder;
import feign.micrometer.MicrometerCapability;
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.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer;
import org.springframework.cloud.openfeign.support.AbstractFormWriter;
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.PageableSpringQueryMapEncoder;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder; import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder; import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.cloud.openfeign.support.SpringMvcContract; import org.springframework.cloud.openfeign.support.SpringMvcContract;
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;
import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService; import org.springframework.format.support.FormattingConversionService;
import com.netflix.hystrix.HystrixCommand; import static feign.form.ContentType.MULTIPART;
import feign.Contract;
import feign.Feign;
import feign.Logger;
import feign.Retryer;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.hystrix.HystrixFeign;
import feign.optionals.OptionalDecoder;
/** /**
* @author Dave Syer * @author Dave Syer
* @author Venil Noronha * @author Venil Noronha
* @author Darren Foong
* @author Jonatan Ivanov
* @author Olga Maciaszek-Sharma
* @author Hyeonmin Park
* @author Yanming Zhou
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
public class FeignClientsConfiguration { public class FeignClientsConfiguration {
@Autowired @Autowired
@@ -67,22 +88,63 @@ public class FeignClientsConfiguration {
@Autowired(required = false) @Autowired(required = false)
private Logger logger; private Logger logger;
@Autowired(required = false)
private SpringDataWebProperties springDataWebProperties;
@Autowired(required = false)
private FeignClientProperties feignClientProperties;
@Autowired(required = false)
private FeignEncoderProperties encoderProperties;
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public Decoder feignDecoder() { public Decoder feignDecoder(ObjectProvider<HttpMessageConverterCustomizer> customizers) {
return new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(this.messageConverters))); return new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(messageConverters, customizers)));
} }
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public Encoder feignEncoder() { @ConditionalOnMissingClass("org.springframework.data.domain.Pageable")
return new SpringEncoder(this.messageConverters); public Encoder feignEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider,
ObjectProvider<HttpMessageConverterCustomizer> customizers) {
return springEncoder(formWriterProvider, encoderProperties, customizers);
}
@Bean
@ConditionalOnClass(name = "org.springframework.data.domain.Pageable")
@ConditionalOnMissingBean
public Encoder feignEncoderPageable(ObjectProvider<AbstractFormWriter> formWriterProvider,
ObjectProvider<HttpMessageConverterCustomizer> customizers) {
PageableSpringEncoder encoder = new PageableSpringEncoder(
springEncoder(formWriterProvider, encoderProperties, customizers));
if (springDataWebProperties != null) {
encoder.setPageParameter(springDataWebProperties.getPageable().getPageParameter());
encoder.setSizeParameter(springDataWebProperties.getPageable().getSizeParameter());
encoder.setSortParameter(springDataWebProperties.getSort().getSortParameter());
}
return encoder;
}
@Bean
@ConditionalOnClass(name = "org.springframework.data.domain.Pageable")
@ConditionalOnMissingBean
public QueryMapEncoder feignQueryMapEncoderPageable() {
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) {
return new SpringMvcContract(this.parameterProcessors, feignConversionService); boolean decodeSlash = feignClientProperties == null || feignClientProperties.isDecodeSlash();
return new SpringMvcContract(parameterProcessors, feignConversionService, decodeSlash);
} }
@Bean @Bean
@@ -94,35 +156,97 @@ public class FeignClientsConfiguration {
return conversionService; return conversionService;
} }
@Configuration
@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();
}
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public Retryer feignRetryer() { public Retryer feignRetryer() {
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(logger); return new DefaultFeignLoggerFactory(logger);
} }
@Bean
@ConditionalOnMissingBean(FeignClientConfigurer.class)
public FeignClientConfigurer feignClientConfigurer() {
return new FeignClientConfigurer() {
};
}
private Encoder springEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider,
FeignEncoderProperties encoderProperties, ObjectProvider<HttpMessageConverterCustomizer> customizers) {
AbstractFormWriter formWriter = formWriterProvider.getIfAvailable();
if (formWriter != null) {
return new SpringEncoder(new SpringPojoFormEncoder(formWriter), messageConverters, encoderProperties,
customizers);
}
else {
return new SpringEncoder(new SpringFormEncoder(), messageConverters, encoderProperties, customizers);
}
}
private class SpringPojoFormEncoder extends SpringFormEncoder {
SpringPojoFormEncoder(AbstractFormWriter formWriter) {
super();
MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor(MULTIPART);
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)
@ConditionalOnClass(CircuitBreaker.class)
@ConditionalOnProperty("spring.cloud.openfeign.circuitbreaker.enabled")
protected static class CircuitBreakerPresentFeignBuilderConfiguration {
@Bean
@Scope("prototype")
@ConditionalOnMissingBean({ Feign.Builder.class, CircuitBreakerFactory.class })
public Feign.Builder defaultFeignBuilder(Retryer retryer) {
return Feign.builder().retryer(retryer);
}
@Bean
@Scope("prototype")
@ConditionalOnMissingBean
@ConditionalOnBean(CircuitBreakerFactory.class)
public Feign.Builder circuitBreakerFeignBuilder() {
return FeignCircuitBreaker.builder();
}
}
@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,11 +1,11 @@
/* /*
* Copyright 2013-2016 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,20 +16,30 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import feign.Request;
import org.springframework.aop.scope.ScopedProxyUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.beans.factory.config.BeanExpressionResolver;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
@@ -42,14 +52,10 @@ import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AbstractClassTestingTypeFilter;
import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
@@ -57,9 +63,12 @@ import org.springframework.util.StringUtils;
* @author Jakub Narloch * @author Jakub Narloch
* @author Venil Noronha * @author Venil Noronha
* @author Gang Li * @author Gang Li
* @author Michal Domagala
* @author Marcin Grzejszczak
* @author Olga Maciaszek-Sharma
* @author Jasbir Singh
*/ */
class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar, class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
ResourceLoaderAware, EnvironmentAware {
// patterned after Spring Integration IntegrationComponentScanRegistrar // patterned after Spring Integration IntegrationComponentScanRegistrar
// and RibbonClientsConfigurationRegistgrar // and RibbonClientsConfigurationRegistgrar
@@ -68,163 +77,16 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar,
private Environment environment; private Environment environment;
public FeignClientsRegistrar() { FeignClientsRegistrar() {
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
registerDefaultConfiguration(metadata, registry);
registerFeignClients(metadata, registry);
}
private void registerDefaultConfiguration(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
Map<String, Object> defaultAttrs = metadata
.getAnnotationAttributes(EnableFeignClients.class.getName(), true);
if (defaultAttrs != null && defaultAttrs.containsKey("defaultConfiguration")) {
String name;
if (metadata.hasEnclosingClass()) {
name = "default." + metadata.getEnclosingClassName();
}
else {
name = "default." + metadata.getClassName();
}
registerClientConfiguration(registry, name,
defaultAttrs.get("defaultConfiguration"));
}
}
public void registerFeignClients(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
ClassPathScanningCandidateComponentProvider scanner = getScanner();
scanner.setResourceLoader(this.resourceLoader);
Set<String> basePackages;
Map<String, Object> attrs = metadata
.getAnnotationAttributes(EnableFeignClients.class.getName());
AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
FeignClient.class);
final Class<?>[] clients = attrs == null ? null
: (Class<?>[]) attrs.get("clients");
if (clients == null || clients.length == 0) {
scanner.addIncludeFilter(annotationTypeFilter);
basePackages = getBasePackages(metadata);
}
else {
final Set<String> clientClasses = new HashSet<>();
basePackages = new HashSet<>();
for (Class<?> clazz : clients) {
basePackages.add(ClassUtils.getPackageName(clazz));
clientClasses.add(clazz.getCanonicalName());
}
AbstractClassTestingTypeFilter filter = new AbstractClassTestingTypeFilter() {
@Override
protected boolean match(ClassMetadata metadata) {
String cleaned = metadata.getClassName().replaceAll("\\$", ".");
return clientClasses.contains(cleaned);
}
};
scanner.addIncludeFilter(
new AllTypeFilter(Arrays.asList(filter, annotationTypeFilter)));
}
for (String basePackage : basePackages) {
Set<BeanDefinition> candidateComponents = scanner
.findCandidateComponents(basePackage);
for (BeanDefinition candidateComponent : candidateComponents) {
if (candidateComponent instanceof AnnotatedBeanDefinition) {
// verify annotated class is an interface
AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
Assert.isTrue(annotationMetadata.isInterface(),
"@FeignClient can only be specified on an interface");
Map<String, Object> attributes = annotationMetadata
.getAnnotationAttributes(
FeignClient.class.getCanonicalName());
String name = getClientName(attributes);
registerClientConfiguration(registry, name,
attributes.get("configuration"));
registerFeignClient(registry, annotationMetadata, attributes);
}
}
}
}
private void registerFeignClient(BeanDefinitionRegistry registry,
AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
String className = annotationMetadata.getClassName();
BeanDefinitionBuilder definition = BeanDefinitionBuilder
.genericBeanDefinition(FeignClientFactoryBean.class);
validate(attributes);
definition.addPropertyValue("url", getUrl(attributes));
definition.addPropertyValue("path", getPath(attributes));
String name = getName(attributes);
definition.addPropertyValue("name", name);
definition.addPropertyValue("type", className);
definition.addPropertyValue("decode404", attributes.get("decode404"));
definition.addPropertyValue("fallback", attributes.get("fallback"));
definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
String alias = name + "FeignClient";
AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
boolean primary = (Boolean)attributes.get("primary"); // has a default, won't be null
beanDefinition.setPrimary(primary);
String qualifier = getQualifier(attributes);
if (StringUtils.hasText(qualifier)) {
alias = qualifier;
}
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
new String[] { alias });
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
}
private void validate(Map<String, Object> attributes) {
AnnotationAttributes annotation = AnnotationAttributes.fromMap(attributes);
// This blows up if an aliased property is overspecified
// FIXME annotation.getAliasedString("name", FeignClient.class, null);
validateFallback(annotation.getClass("fallback"));
validateFallbackFactory(annotation.getClass("fallbackFactory"));
} }
static void validateFallback(final Class clazz) { static void validateFallback(final Class clazz) {
Assert.isTrue( Assert.isTrue(!clazz.isInterface(), "Fallback class must implement the interface annotated by @FeignClient");
!clazz.isInterface(),
"Fallback class must implement the interface annotated by @FeignClient"
);
} }
static void validateFallbackFactory(final Class clazz) { static void validateFallbackFactory(final Class clazz) {
Assert.isTrue(!clazz.isInterface(), Assert.isTrue(!clazz.isInterface(), "Fallback factory must produce instances "
"Fallback factory must produce instances of fallback classes that implement the interface annotated by @FeignClient" + "of fallback classes that implement the interface annotated by @FeignClient");
);
}
/* for testing */ String getName(Map<String, Object> attributes) {
String name = (String) attributes.get("serviceId");
if (!StringUtils.hasText(name)) {
name = (String) attributes.get("name");
}
if (!StringUtils.hasText(name)) {
name = (String) attributes.get("value");
}
name = resolve(name);
return getName(name);
} }
static String getName(String name) { static String getName(String name) {
@@ -237,7 +99,8 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar,
String url; String url;
if (!name.startsWith("http://") && !name.startsWith("https://")) { if (!name.startsWith("http://") && !name.startsWith("https://")) {
url = "http://" + name; url = "http://" + name;
} else { }
else {
url = name; url = name;
} }
host = new URI(url).getHost(); host = new URI(url).getHost();
@@ -249,18 +112,6 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar,
return name; return name;
} }
private String resolve(String value) {
if (StringUtils.hasText(value)) {
return this.environment.resolvePlaceholders(value);
}
return value;
}
private String getUrl(Map<String, Object> attributes) {
String url = resolve((String) attributes.get("url"));
return getUrl(url);
}
static String getUrl(String url) { static String getUrl(String url) {
if (StringUtils.hasText(url) && !(url.startsWith("#{") && url.contains("}"))) { if (StringUtils.hasText(url) && !(url.startsWith("#{") && url.contains("}"))) {
if (!url.contains("://")) { if (!url.contains("://")) {
@@ -276,11 +127,6 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar,
return url; return url;
} }
private String getPath(Map<String, Object> attributes) {
String path = resolve((String) attributes.get("path"));
return getPath(path);
}
static String getPath(String path) { static String getPath(String path) {
if (StringUtils.hasText(path)) { if (StringUtils.hasText(path)) {
path = path.trim(); path = path.trim();
@@ -294,6 +140,187 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar,
return path; return path;
} }
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
registerDefaultConfiguration(metadata, registry);
registerFeignClients(metadata, registry);
}
private void registerDefaultConfiguration(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
Map<String, Object> defaultAttrs = metadata.getAnnotationAttributes(EnableFeignClients.class.getName(), true);
if (defaultAttrs != null && defaultAttrs.containsKey("defaultConfiguration")) {
String name;
if (metadata.hasEnclosingClass()) {
name = "default." + metadata.getEnclosingClassName();
}
else {
name = "default." + metadata.getClassName();
}
registerClientConfiguration(registry, name, defaultAttrs.get("defaultConfiguration"));
}
}
public void registerFeignClients(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
LinkedHashSet<BeanDefinition> candidateComponents = new LinkedHashSet<>();
Map<String, Object> attrs = metadata.getAnnotationAttributes(EnableFeignClients.class.getName());
final Class<?>[] clients = attrs == null ? null : (Class<?>[]) attrs.get("clients");
if (clients == null || clients.length == 0) {
ClassPathScanningCandidateComponentProvider scanner = getScanner();
scanner.setResourceLoader(this.resourceLoader);
scanner.addIncludeFilter(new AnnotationTypeFilter(FeignClient.class));
Set<String> basePackages = getBasePackages(metadata);
for (String basePackage : basePackages) {
candidateComponents.addAll(scanner.findCandidateComponents(basePackage));
}
}
else {
for (Class<?> clazz : clients) {
candidateComponents.add(new AnnotatedGenericBeanDefinition(clazz));
}
}
for (BeanDefinition candidateComponent : candidateComponents) {
if (candidateComponent instanceof AnnotatedBeanDefinition) {
// verify annotated class is an interface
AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
Assert.isTrue(annotationMetadata.isInterface(), "@FeignClient can only be specified on an interface");
Map<String, Object> attributes = annotationMetadata
.getAnnotationAttributes(FeignClient.class.getCanonicalName());
String name = getClientName(attributes);
registerClientConfiguration(registry, name, attributes.get("configuration"));
registerFeignClient(registry, annotationMetadata, attributes);
}
}
}
private void registerFeignClient(BeanDefinitionRegistry registry, AnnotationMetadata annotationMetadata,
Map<String, Object> attributes) {
String className = annotationMetadata.getClassName();
Class clazz = ClassUtils.resolveClassName(className, null);
ConfigurableBeanFactory beanFactory = registry instanceof ConfigurableBeanFactory
? (ConfigurableBeanFactory) registry : null;
String contextId = getContextId(beanFactory, attributes);
String name = getName(attributes);
FeignClientFactoryBean factoryBean = new FeignClientFactoryBean();
factoryBean.setBeanFactory(beanFactory);
factoryBean.setName(name);
factoryBean.setContextId(contextId);
factoryBean.setType(clazz);
factoryBean.setRefreshableClient(isClientRefreshEnabled());
BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(clazz, () -> {
factoryBean.setUrl(getUrl(beanFactory, attributes));
factoryBean.setPath(getPath(beanFactory, attributes));
factoryBean.setDecode404(Boolean.parseBoolean(String.valueOf(attributes.get("decode404"))));
Object fallback = attributes.get("fallback");
if (fallback != null) {
factoryBean.setFallback(fallback instanceof Class ? (Class<?>) fallback
: ClassUtils.resolveClassName(fallback.toString(), null));
}
Object fallbackFactory = attributes.get("fallbackFactory");
if (fallbackFactory != null) {
factoryBean.setFallbackFactory(fallbackFactory instanceof Class ? (Class<?>) fallbackFactory
: ClassUtils.resolveClassName(fallbackFactory.toString(), null));
}
return factoryBean.getObject();
});
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
definition.setLazyInit(true);
validate(attributes);
AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
beanDefinition.setAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE, className);
beanDefinition.setAttribute("feignClientsRegistrarFactoryBean", factoryBean);
// has a default, won't be null
boolean primary = (Boolean) attributes.get("primary");
beanDefinition.setPrimary(primary);
String[] qualifiers = getQualifiers(attributes);
if (ObjectUtils.isEmpty(qualifiers)) {
qualifiers = new String[] { contextId + "FeignClient" };
}
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, qualifiers);
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
registerOptionsBeanDefinition(registry, contextId);
}
private void validate(Map<String, Object> attributes) {
AnnotationAttributes annotation = AnnotationAttributes.fromMap(attributes);
// This blows up if an aliased property is overspecified
// FIXME annotation.getAliasedString("name", FeignClient.class, null);
validateFallback(annotation.getClass("fallback"));
validateFallbackFactory(annotation.getClass("fallbackFactory"));
}
/* for testing */ String getName(Map<String, Object> attributes) {
return getName(null, attributes);
}
String getName(ConfigurableBeanFactory beanFactory, Map<String, Object> attributes) {
String name = (String) attributes.get("serviceId");
if (!StringUtils.hasText(name)) {
name = (String) attributes.get("name");
}
if (!StringUtils.hasText(name)) {
name = (String) attributes.get("value");
}
name = resolve(beanFactory, name);
return getName(name);
}
private String getContextId(ConfigurableBeanFactory beanFactory, Map<String, Object> attributes) {
String contextId = (String) attributes.get("contextId");
if (!StringUtils.hasText(contextId)) {
return getName(attributes);
}
contextId = resolve(beanFactory, contextId);
return getName(contextId);
}
private String resolve(ConfigurableBeanFactory beanFactory, String value) {
if (StringUtils.hasText(value)) {
if (beanFactory == null) {
return this.environment.resolvePlaceholders(value);
}
BeanExpressionResolver resolver = beanFactory.getBeanExpressionResolver();
String resolved = beanFactory.resolveEmbeddedValue(value);
if (resolver == null) {
return resolved;
}
Object evaluateValue = resolver.evaluate(resolved, new BeanExpressionContext(beanFactory, null));
if (evaluateValue != null) {
return String.valueOf(evaluateValue);
}
return null;
}
return value;
}
private String getUrl(ConfigurableBeanFactory beanFactory, Map<String, Object> attributes) {
String url = resolve(beanFactory, (String) attributes.get("url"));
return getUrl(url);
}
private String getPath(ConfigurableBeanFactory beanFactory, Map<String, Object> attributes) {
String path = resolve(beanFactory, (String) attributes.get("path"));
return getPath(path);
}
protected ClassPathScanningCandidateComponentProvider getScanner() { protected ClassPathScanningCandidateComponentProvider getScanner() {
return new ClassPathScanningCandidateComponentProvider(false, this.environment) { return new ClassPathScanningCandidateComponentProvider(false, this.environment) {
@Override @Override
@@ -329,12 +356,11 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar,
} }
if (basePackages.isEmpty()) { if (basePackages.isEmpty()) {
basePackages.add( basePackages.add(ClassUtils.getPackageName(importingClassMetadata.getClassName()));
ClassUtils.getPackageName(importingClassMetadata.getClassName()));
} }
return basePackages; return basePackages;
} }
private String getQualifier(Map<String, Object> client) { private String getQualifier(Map<String, Object> client) {
if (client == null) { if (client == null) {
return null; return null;
@@ -346,11 +372,26 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar,
return null; return null;
} }
private String[] getQualifiers(Map<String, Object> client) {
if (client == null) {
return null;
}
List<String> qualifierList = new ArrayList<>(Arrays.asList((String[]) client.get("qualifiers")));
qualifierList.removeIf(qualifier -> !StringUtils.hasText(qualifier));
if (qualifierList.isEmpty() && getQualifier(client) != null) {
qualifierList = Collections.singletonList(getQualifier(client));
}
return !qualifierList.isEmpty() ? qualifierList.toArray(new String[0]) : null;
}
private String getClientName(Map<String, Object> client) { private String getClientName(Map<String, Object> client) {
if (client == null) { if (client == null) {
return null; return null;
} }
String value = (String) client.get("value"); String value = (String) client.get("contextId");
if (!StringUtils.hasText(value)) {
value = (String) client.get("value");
}
if (!StringUtils.hasText(value)) { if (!StringUtils.hasText(value)) {
value = (String) client.get("name"); value = (String) client.get("name");
} }
@@ -361,18 +402,15 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar,
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());
} }
@@ -382,36 +420,27 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar,
} }
/** /**
* Helper class to create a {@link TypeFilter} that matches if all the delegates * This method is meant to create {@link Request.Options} beans definition with
* match. * refreshScope.
* * @param registry spring bean definition registry
* @author Oliver Gierke * @param contextId name of feign client
*/ */
private static class AllTypeFilter implements TypeFilter { private void registerOptionsBeanDefinition(BeanDefinitionRegistry registry, String contextId) {
if (isClientRefreshEnabled()) {
private final List<TypeFilter> delegates; String beanName = Request.Options.class.getCanonicalName() + "-" + contextId;
BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder
/** .genericBeanDefinition(OptionsFactoryBean.class);
* Creates a new {@link AllTypeFilter} to match if all the given delegates match. definitionBuilder.setScope("refresh");
* definitionBuilder.addPropertyValue("contextId", contextId);
* @param delegates must not be {@literal null}. BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(definitionBuilder.getBeanDefinition(),
*/ beanName);
public AllTypeFilter(List<TypeFilter> delegates) { definitionHolder = ScopedProxyUtils.createScopedProxy(definitionHolder, registry, true);
Assert.notNull(delegates, "This argument is required, it must not be null"); BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);
this.delegates = delegates;
}
@Override
public boolean match(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
for (TypeFilter filter : this.delegates) {
if (!filter.match(metadataReader, metadataReaderFactory)) {
return false;
}
}
return true;
} }
} }
private boolean isClientRefreshEnabled() {
return environment.getProperty("spring.cloud.openfeign.client.refresh-enabled", Boolean.class, false);
}
} }
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2015 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,7 +16,12 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.cloud.context.named.NamedContextFactory; import org.springframework.cloud.context.named.NamedContextFactory;
import org.springframework.lang.Nullable;
/** /**
* A factory that creates instances of feign classes. It creates a Spring * A factory that creates instances of feign classes. It creates a Spring
@@ -24,11 +29,32 @@ import org.springframework.cloud.context.named.NamedContextFactory;
* *
* @author Spencer Gibb * @author Spencer Gibb
* @author Dave Syer * @author Dave Syer
* @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
public <T> T getInstanceWithoutAncestors(String name, Class<T> type) {
try {
return BeanFactoryUtils.beanOfType(getContext(name), type);
}
catch (BeansException ex) {
return null;
}
}
@Nullable
public <T> Map<String, T> getInstancesWithoutAncestors(String name, Class<T> type) {
return getContext(name).getBeansOfType(type);
}
public <T> T getInstance(String contextName, String beanName, Class<T> type) {
return getContext(contextName).getBean(beanName, type);
} }
} }
@@ -0,0 +1,37 @@
/*
* Copyright 2020-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.codec.ErrorDecoder;
/**
* Allows an application to use a custom Feign {@link feign.codec.ErrorDecoder}.
*
* @author Michael Cramer
*/
public interface FeignErrorDecoderFactory {
/**
* Factory method to provide a {@link feign.codec.ErrorDecoder} for a given
* {@link Class}.
* @param type the {@link Class} for which a {@link feign.codec.ErrorDecoder} instance
* is to be created
* @return a {@link feign.codec.ErrorDecoder} instance
*/
ErrorDecoder create(Class<?> type);
}
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2016 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -1,11 +1,11 @@
/* /*
* Copyright 2016 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -27,10 +27,9 @@ public interface FeignLoggerFactory {
/** /**
* Factory method to provide a {@link Logger} for a given {@link Class}. * Factory method to provide a {@link Logger} for a given {@link Class}.
*
* @param type the {@link Class} for which a {@link Logger} instance is to be created * @param type the {@link Class} for which a {@link Logger} instance is to be created
* @return a {@link Logger} instance * @return a {@link Logger} instance
*/ */
public Logger create(Class<?> type); Logger create(Class<?> type);
} }
@@ -0,0 +1,43 @@
/*
* 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 org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
/**
* @author Nguyen Ky Thanh
*/
public class HttpClient5DisabledConditions extends AnyNestedCondition {
public HttpClient5DisabledConditions() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnMissingClass("feign.hc5.ApacheHttp5Client")
static class ApacheHttp5ClientClassMissing {
}
@ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.hc5.enabled", havingValue = "false",
matchIfMissing = true)
static class HttpClient5Disabled {
}
}
@@ -1,98 +0,0 @@
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.cloud.openfeign;
import org.springframework.util.Assert;
import feign.Feign;
import feign.Target;
import feign.hystrix.FallbackFactory;
import feign.hystrix.HystrixFeign;
import feign.hystrix.SetterFactory;
/**
* @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;
SetterFactory setterFactory = getOptional(factory.getName(), context,
SetterFactory.class);
if (setterFactory != null) {
builder.setterFactory(setterFactory);
}
Class<?> fallback = factory.getFallback();
if (fallback != void.class) {
return targetWithFallback(factory.getName(), context, target, builder, fallback);
}
Class<?> fallbackFactory = factory.getFallbackFactory();
if (fallbackFactory != void.class) {
return targetWithFallbackFactory(factory.getName(), 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);
}
}
@@ -0,0 +1,53 @@
/*
* 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.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import feign.QueryMap;
import org.springframework.core.annotation.AliasFor;
/**
* Spring MVC equivalent of OpenFeign's {@link feign.QueryMap} parameter annotation.
*
* @author Aram Peres
* @see feign.QueryMap
* @see org.springframework.cloud.openfeign.annotation.QueryMapParameterProcessor
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER })
public @interface SpringQueryMap {
/**
* @see QueryMap#encoded()
* @return alias for {@link #encoded()}.
*/
@AliasFor("encoded")
boolean value() default false;
/**
* @see QueryMap#encoded()
* @return Specifies whether parameter names and values are already encoded.
*/
@AliasFor("value")
boolean encoded() default false;
}
@@ -1,18 +1,17 @@
/* /*
* Copyright 2013-2016 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*
*/ */
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
@@ -23,7 +22,9 @@ import feign.Target;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
*/ */
interface Targeter { public interface Targeter {
<T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context, <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, 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;
}
}
@@ -0,0 +1,79 @@
/*
* 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.Map;
import java.util.stream.Collectors;
import feign.MethodMetadata;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.web.bind.annotation.MatrixVariable;
import static feign.Util.checkState;
import static feign.Util.emptyToNull;
/**
* {@link MatrixVariable} annotation processor.
*
* Can expand maps or single objects. Values are assigned from the objects
* {@code toString()} method.
*
* @author Matt King
* @see AnnotatedParameterProcessor
*/
public class MatrixVariableParameterProcessor implements AnnotatedParameterProcessor {
private static final Class<MatrixVariable> ANNOTATION = MatrixVariable.class;
@Override
public Class<? extends Annotation> getAnnotationType() {
return ANNOTATION;
}
@Override
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
int parameterIndex = context.getParameterIndex();
Class<?> parameterType = method.getParameterTypes()[parameterIndex];
MethodMetadata data = context.getMethodMetadata();
String name = ANNOTATION.cast(annotation).value();
checkState(emptyToNull(name) != null, "MatrixVariable annotation was empty on param %s.",
context.getParameterIndex());
context.setParameterName(name);
if (Map.class.isAssignableFrom(parameterType)) {
data.indexToExpander().put(parameterIndex, this::expandMap);
}
else {
data.indexToExpander().put(parameterIndex, object -> ";" + name + "=" + object.toString());
}
return true;
}
private String expandMap(Object object) {
Map<String, Object> paramMap = (Map) object;
return paramMap.keySet().stream().filter(key -> paramMap.get(key) != null)
.map(key -> ";" + key + "=" + paramMap.get(key).toString()).collect(Collectors.joining());
}
}
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2015 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,11 +21,11 @@ import java.lang.reflect.Method;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
import feign.MethodMetadata;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor; import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import feign.MethodMetadata;
import static feign.Util.checkState; import static feign.Util.checkState;
import static feign.Util.emptyToNull; import static feign.Util.emptyToNull;
@@ -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 {
@@ -48,14 +49,14 @@ public class PathVariableParameterProcessor implements AnnotatedParameterProcess
@Override @Override
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) { public boolean processArgument(AnnotatedParameterContext context, 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);
} }
@@ -74,4 +75,5 @@ public class PathVariableParameterProcessor implements AnnotatedParameterProcess
} }
return false; return false;
} }
} }
@@ -0,0 +1,53 @@
/*
* 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 feign.MethodMetadata;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.cloud.openfeign.SpringQueryMap;
/**
* {@link SpringQueryMap} parameter processor.
*
* @author Aram Peres
* @see AnnotatedParameterProcessor
*/
public class QueryMapParameterProcessor implements AnnotatedParameterProcessor {
private static final Class<SpringQueryMap> ANNOTATION = SpringQueryMap.class;
@Override
public Class<? extends Annotation> getAnnotationType() {
return ANNOTATION;
}
@Override
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
int paramIndex = context.getParameterIndex();
MethodMetadata metadata = context.getMethodMetadata();
if (metadata.queryMapIndex() == null) {
metadata.queryMapIndex(paramIndex);
metadata.queryMapEncoded(SpringQueryMap.class.cast(annotation).encoded());
}
return true;
}
}
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2015 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,11 +21,11 @@ import java.lang.reflect.Method;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
import feign.MethodMetadata;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor; import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestHeader;
import feign.MethodMetadata;
import static feign.Util.checkState; import static feign.Util.checkState;
import static feign.Util.emptyToNull; import static feign.Util.emptyToNull;
@@ -59,12 +59,12 @@ public class RequestHeaderParameterProcessor implements AnnotatedParameterProces
} }
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, data.template().headers().get(name)); Collection<String> header = context.setTemplateParameter(name, data.template().headers().get(name));
data.template().header(name, header); data.template().header(name, header);
return true; return true;
} }
} }
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2015 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,14 +21,14 @@ import java.lang.reflect.Method;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
import feign.MethodMetadata;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor; import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import static feign.Util.checkState; import static feign.Util.checkState;
import static feign.Util.emptyToNull; import static feign.Util.emptyToNull;
import feign.MethodMetadata;
/** /**
* {@link RequestParam} parameter processor. * {@link RequestParam} parameter processor.
* *
@@ -60,14 +60,12 @@ 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;
} }
} }
@@ -0,0 +1,61 @@
/*
* 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.Collection;
import feign.MethodMetadata;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.web.bind.annotation.RequestPart;
import static feign.Util.checkState;
import static feign.Util.emptyToNull;
/**
* {@link RequestPart} parameter processor.
*
* @author Aaron Whiteside
* @see AnnotatedParameterProcessor
*/
public class RequestPartParameterProcessor implements AnnotatedParameterProcessor {
private static final Class<RequestPart> ANNOTATION = RequestPart.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();
String name = ANNOTATION.cast(annotation).value();
checkState(emptyToNull(name) != null, "RequestPart.value() was empty on parameter %s", parameterIndex);
context.setParameterName(name);
data.formParams().add(name);
Collection<String> names = context.setTemplateParameter(name, data.indexToName().get(parameterIndex));
data.indexToName().put(parameterIndex, names);
return true;
}
}
@@ -0,0 +1,45 @@
/*
* 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.clientconfig;
/**
* Additional Feign Client configuration that are not included in
* {@link org.springframework.cloud.openfeign.FeignClient}.
*
* @author Matt King
*/
public interface FeignClientConfigurer {
/**
* @return whether to mark the feign proxy as a primary bean. Defaults to true.
*/
default boolean primary() {
return true;
}
/**
* FALSE will only apply configurations from classes listed in
* <code>configuration()</code>. Will still use parent instance of
* {@link feign.codec.Decoder}, {@link feign.codec.Encoder}, and
* {@link feign.Contract} if none are provided.
* @return weather to inherit parent context for client configuration.
*/
default boolean inheritParentConfiguration() {
return true;
}
}
@@ -0,0 +1,146 @@
/*
* 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.clientconfig;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import jakarta.annotation.PreDestroy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.socket.LayeredConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
import org.apache.hc.core5.http.io.SocketConfig;
import org.apache.hc.core5.http.ssl.TLS;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.pool.PoolConcurrencyPolicy;
import org.apache.hc.core5.pool.PoolReusePolicy;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Default configuration for {@link CloseableHttpClient}.
*
* @author Nguyen Ky Thanh
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(CloseableHttpClient.class)
public class HttpClient5FeignConfiguration {
private static final Log LOG = LogFactory.getLog(HttpClient5FeignConfiguration.class);
private CloseableHttpClient httpClient5;
@Bean
@ConditionalOnMissingBean(HttpClientConnectionManager.class)
public HttpClientConnectionManager hc5ConnectionManager(FeignHttpClientProperties httpClientProperties) {
return PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(httpsSSLConnectionSocketFactory(httpClientProperties.isDisableSslValidation()))
.setMaxConnTotal(httpClientProperties.getMaxConnections())
.setMaxConnPerRoute(httpClientProperties.getMaxConnectionsPerRoute())
.setConnPoolPolicy(PoolReusePolicy.valueOf(httpClientProperties.getHc5().getPoolReusePolicy().name()))
.setPoolConcurrencyPolicy(
PoolConcurrencyPolicy.valueOf(httpClientProperties.getHc5().getPoolConcurrencyPolicy().name()))
.setConnectionTimeToLive(
TimeValue.of(httpClientProperties.getTimeToLive(), httpClientProperties.getTimeToLiveUnit()))
.setDefaultSocketConfig(
SocketConfig.custom().setSoTimeout(Timeout.of(httpClientProperties.getHc5().getSocketTimeout(),
httpClientProperties.getHc5().getSocketTimeoutUnit())).build())
.build();
}
@Bean
public CloseableHttpClient httpClient5(HttpClientConnectionManager connectionManager,
FeignHttpClientProperties httpClientProperties) {
httpClient5 = HttpClients.custom().disableCookieManagement().useSystemProperties()
.setConnectionManager(connectionManager).evictExpiredConnections()
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout(
Timeout.of(httpClientProperties.getConnectionTimeout(), TimeUnit.MILLISECONDS))
.setRedirectsEnabled(httpClientProperties.isFollowRedirects()).build())
.build();
return httpClient5;
}
@PreDestroy
public void destroy() {
if (httpClient5 != null) {
httpClient5.close(CloseMode.GRACEFUL);
}
}
private LayeredConnectionSocketFactory httpsSSLConnectionSocketFactory(boolean isDisableSslValidation) {
final SSLConnectionSocketFactoryBuilder sslConnectionSocketFactoryBuilder = SSLConnectionSocketFactoryBuilder
.create().setTlsVersions(TLS.V_1_3, TLS.V_1_2);
if (isDisableSslValidation) {
try {
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] { new DisabledValidationTrustManager() }, new SecureRandom());
sslConnectionSocketFactoryBuilder.setSslContext(sslContext);
}
catch (NoSuchAlgorithmException e) {
LOG.warn("Error creating SSLContext", e);
}
catch (KeyManagementException e) {
LOG.warn("Error creating SSLContext", e);
}
}
else {
sslConnectionSocketFactoryBuilder.setSslContext(SSLContexts.createSystemDefault());
}
return sslConnectionSocketFactoryBuilder.build();
}
static class DisabledValidationTrustManager implements X509TrustManager {
DisabledValidationTrustManager() {
}
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}
@@ -0,0 +1,125 @@
/*
* 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.clientconfig;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import jakarta.annotation.PreDestroy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory;
import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Default configuration for {@link CloseableHttpClient}.
*
* @author Ryan Baxter
* @author Marcin Grzejszczak
* @author Spencer Gibb
* @author Olga Maciaszek-Sharma
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(CloseableHttpClient.class)
public class HttpClientFeignConfiguration {
private static final Log LOG = LogFactory.getLog(HttpClientFeignConfiguration.class);
private final Timer connectionManagerTimer = new Timer("FeignApacheHttpClientConfiguration.connectionManagerTimer",
true);
private CloseableHttpClient httpClient;
@Autowired(required = false)
private RegistryBuilder registryBuilder;
@Bean
@ConditionalOnMissingBean(HttpClientConnectionManager.class)
public HttpClientConnectionManager connectionManager(
ApacheHttpClientConnectionManagerFactory connectionManagerFactory,
FeignHttpClientProperties httpClientProperties) {
final HttpClientConnectionManager connectionManager = connectionManagerFactory.newConnectionManager(
httpClientProperties.isDisableSslValidation(), httpClientProperties.getMaxConnections(),
httpClientProperties.getMaxConnectionsPerRoute(), httpClientProperties.getTimeToLive(),
httpClientProperties.getTimeToLiveUnit(), this.registryBuilder);
this.connectionManagerTimer.schedule(new TimerTask() {
@Override
public void run() {
connectionManager.closeExpiredConnections();
}
}, 30000, httpClientProperties.getConnectionTimerRepeat());
return connectionManager;
}
@Bean
@ConditionalOnProperty(value = "spring.cloud.openfeign.compression.response.enabled", havingValue = "true")
public CloseableHttpClient customHttpClient(HttpClientConnectionManager httpClientConnectionManager,
FeignHttpClientProperties httpClientProperties) {
HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement().useSystemProperties();
this.httpClient = createClient(builder, httpClientConnectionManager, httpClientProperties);
return this.httpClient;
}
@Bean
@ConditionalOnProperty(value = "spring.cloud.openfeign.compression.response.enabled", havingValue = "false",
matchIfMissing = true)
public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory,
HttpClientConnectionManager httpClientConnectionManager, FeignHttpClientProperties httpClientProperties) {
this.httpClient = createClient(httpClientFactory.createBuilder(), httpClientConnectionManager,
httpClientProperties);
return this.httpClient;
}
private CloseableHttpClient createClient(HttpClientBuilder builder,
HttpClientConnectionManager httpClientConnectionManager, FeignHttpClientProperties httpClientProperties) {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(httpClientProperties.getConnectionTimeout())
.setRedirectsEnabled(httpClientProperties.isFollowRedirects()).build();
CloseableHttpClient httpClient = builder.setDefaultRequestConfig(defaultRequestConfig)
.setConnectionManager(httpClientConnectionManager).build();
return httpClient;
}
@PreDestroy
public void destroy() {
this.connectionManagerTimer.cancel();
if (this.httpClient != null) {
try {
this.httpClient.close();
}
catch (IOException e) {
if (LOG.isErrorEnabled()) {
LOG.error("Could not correctly close httpClient.");
}
}
}
}
}
@@ -0,0 +1,77 @@
/*
* 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.clientconfig;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import jakarta.annotation.PreDestroy;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory;
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Defualt configuration for {@link OkHttpClient}.
*
* @author Ryan Baxter
* @author Marcin Grzejszczak
* @author Spencer Gibb
* @author Olga Maciaszek-Sharma
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(okhttp3.OkHttpClient.class)
public class OkHttpFeignConfiguration {
private okhttp3.OkHttpClient okHttpClient;
@Bean
@ConditionalOnMissingBean(ConnectionPool.class)
public ConnectionPool httpClientConnectionPool(FeignHttpClientProperties httpClientProperties,
OkHttpClientConnectionPoolFactory connectionPoolFactory) {
int maxTotalConnections = httpClientProperties.getMaxConnections();
long timeToLive = httpClientProperties.getTimeToLive();
TimeUnit ttlUnit = httpClientProperties.getTimeToLiveUnit();
return connectionPoolFactory.create(maxTotalConnections, timeToLive, ttlUnit);
}
@Bean
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, ConnectionPool connectionPool,
FeignHttpClientProperties httpClientProperties) {
boolean followRedirects = httpClientProperties.isFollowRedirects();
int connectTimeout = httpClientProperties.getConnectionTimeout();
Duration reaTimeout = httpClientProperties.getOkHttp().getReadTimeout();
this.okHttpClient = httpClientFactory.createBuilder(httpClientProperties.isDisableSslValidation())
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects)
.readTimeout(reaTimeout).connectionPool(connectionPool).build();
return this.okHttpClient;
}
@PreDestroy
public void destroy() {
if (this.okHttpClient != null) {
this.okHttpClient.dispatcher().executorService().shutdown();
this.okHttpClient.connectionPool().evictAll();
}
}
}
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2017 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -18,6 +18,7 @@ package org.springframework.cloud.openfeign.encoding;
import feign.RequestInterceptor; import feign.RequestInterceptor;
import feign.RequestTemplate; import feign.RequestTemplate;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
@@ -34,7 +35,6 @@ public abstract class BaseRequestInterceptor implements RequestInterceptor {
/** /**
* Creates new instance of {@link BaseRequestInterceptor}. * Creates new instance of {@link BaseRequestInterceptor}.
*
* @param properties the encoding properties * @param properties the encoding properties
*/ */
protected BaseRequestInterceptor(FeignClientEncodingProperties properties) { protected BaseRequestInterceptor(FeignClientEncodingProperties properties) {
@@ -44,10 +44,9 @@ public abstract class BaseRequestInterceptor implements RequestInterceptor {
/** /**
* Adds the header if it wasn't yet specified. * Adds the header if it wasn't yet specified.
*
* @param requestTemplate the request * @param requestTemplate the request
* @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, String... values) { protected void addHeader(RequestTemplate requestTemplate, String name, String... values) {
@@ -57,7 +56,7 @@ public abstract class BaseRequestInterceptor implements RequestInterceptor {
} }
protected FeignClientEncodingProperties getProperties() { protected FeignClientEncodingProperties getProperties() {
return properties; return this.properties;
} }
} }
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2017 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -35,19 +35,21 @@ import org.springframework.context.annotation.Configuration;
* @author Jakub Narloch * @author Jakub Narloch
* @see FeignAcceptGzipEncodingInterceptor * @see FeignAcceptGzipEncodingInterceptor
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(FeignClientEncodingProperties.class) @EnableConfigurationProperties(FeignClientEncodingProperties.class)
@ConditionalOnClass(Feign.class) @ConditionalOnClass(Feign.class)
@ConditionalOnBean(Client.class) @ConditionalOnBean(Client.class)
@ConditionalOnProperty(value = "feign.compression.response.enabled", matchIfMissing = false) @ConditionalOnProperty(value = "spring.cloud.openfeign.compression.response.enabled", 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")
@AutoConfigureAfter(FeignAutoConfiguration.class) @AutoConfigureAfter(FeignAutoConfiguration.class)
public class FeignAcceptGzipEncodingAutoConfiguration { public class FeignAcceptGzipEncodingAutoConfiguration {
@Bean @Bean
public FeignAcceptGzipEncodingInterceptor feignAcceptGzipEncodingInterceptor(FeignClientEncodingProperties properties) { public FeignAcceptGzipEncodingInterceptor feignAcceptGzipEncodingInterceptor(
FeignClientEncodingProperties properties) {
return new FeignAcceptGzipEncodingInterceptor(properties); return new FeignAcceptGzipEncodingInterceptor(properties);
} }
} }
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2017 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -19,10 +19,11 @@ package org.springframework.cloud.openfeign.encoding;
import feign.RequestTemplate; import feign.RequestTemplate;
/** /**
* Enables the HTTP response payload compression by specifying the {@code Accept-Encoding} headers. * Enables the HTTP response payload compression by specifying the {@code Accept-Encoding}
* Although this does not yet mean that the requests will be compressed, it requires the remote server * headers. Although this does not yet mean that the requests will be compressed, it
* to understand the header and be configured to compress responses. Still no all responses might be compressed * requires the remote server to understand the header and be configured to compress
* based on the media type matching and other factors like the response content length. * responses. Still no all responses might be compressed based on the media type matching
* and other factors like the response content length.
* *
* @author Jakub Narloch * @author Jakub Narloch
*/ */
@@ -30,7 +31,6 @@ 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(FeignClientEncodingProperties properties) { protected FeignAcceptGzipEncodingInterceptor(FeignClientEncodingProperties properties) {
@@ -46,4 +46,5 @@ public class FeignAcceptGzipEncodingInterceptor extends BaseRequestInterceptor {
addHeader(template, HttpEncoding.ACCEPT_ENCODING_HEADER, HttpEncoding.GZIP_ENCODING, addHeader(template, HttpEncoding.ACCEPT_ENCODING_HEADER, HttpEncoding.GZIP_ENCODING,
HttpEncoding.DEFLATE_ENCODING); HttpEncoding.DEFLATE_ENCODING);
} }
} }
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2017 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,23 +16,23 @@
package org.springframework.cloud.openfeign.encoding; package org.springframework.cloud.openfeign.encoding;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.Arrays; import java.util.Arrays;
import java.util.Objects; import java.util.Objects;
import org.springframework.boot.context.properties.ConfigurationProperties;
/** /**
* The Feign encoding properties. * The Feign encoding properties.
* *
* @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", "application/json"}; private String[] mimeTypes = new String[] { "text/xml", "application/xml", "application/json" };
/** /**
* The minimum threshold content size. * The minimum threshold content size.
@@ -40,7 +40,7 @@ public class FeignClientEncodingProperties {
private int minRequestSize = 2048; private int minRequestSize = 2048;
public String[] getMimeTypes() { public String[] getMimeTypes() {
return mimeTypes; return this.mimeTypes;
} }
public void setMimeTypes(String[] mimeTypes) { public void setMimeTypes(String[] mimeTypes) {
@@ -48,7 +48,7 @@ public class FeignClientEncodingProperties {
} }
public int getMinRequestSize() { public int getMinRequestSize() {
return minRequestSize; return this.minRequestSize;
} }
public void setMinRequestSize(int minRequestSize) { public void setMinRequestSize(int minRequestSize) {
@@ -57,24 +57,27 @@ public class FeignClientEncodingProperties {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) {
if (o == null || getClass() != o.getClass()) return false; return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FeignClientEncodingProperties that = (FeignClientEncodingProperties) o; FeignClientEncodingProperties that = (FeignClientEncodingProperties) o;
return Arrays.equals(mimeTypes, that.mimeTypes) && return Arrays.equals(this.mimeTypes, that.mimeTypes)
Objects.equals(minRequestSize, that.minRequestSize); && Objects.equals(this.minRequestSize, that.minRequestSize);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(mimeTypes, minRequestSize); return Objects.hash(this.mimeTypes, this.minRequestSize);
} }
@Override @Override
public String toString() { public String toString() {
return new StringBuilder("FeignClientEncodingProperties{") return new StringBuilder("FeignClientEncodingProperties{").append("mimeTypes=")
.append("mimeTypes=").append(Arrays.toString(mimeTypes)).append(", ") .append(Arrays.toString(this.mimeTypes)).append(", ").append("minRequestSize=")
.append("minRequestSize=").append(minRequestSize) .append(this.minRequestSize).append("}").toString();
.append("}").toString();
} }
} }
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2017 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,11 +16,9 @@
package org.springframework.cloud.openfeign.encoding; package org.springframework.cloud.openfeign.encoding;
import feign.Client;
import feign.Feign; import feign.Feign;
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.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;
@@ -35,19 +33,20 @@ import org.springframework.context.annotation.Configuration;
* @author Jakub Narloch * @author Jakub Narloch
* @see FeignContentGzipEncodingInterceptor * @see FeignContentGzipEncodingInterceptor
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(FeignClientEncodingProperties.class) @EnableConfigurationProperties(FeignClientEncodingProperties.class)
@ConditionalOnClass(Feign.class) @ConditionalOnClass(Feign.class)
@ConditionalOnBean(Client.class) // 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(value = "feign.compression.request.enabled", matchIfMissing = false) @ConditionalOnProperty("spring.cloud.openfeign.compression.request.enabled")
@AutoConfigureAfter(FeignAutoConfiguration.class) @AutoConfigureAfter(FeignAutoConfiguration.class)
public class FeignContentGzipEncodingAutoConfiguration { public class FeignContentGzipEncodingAutoConfiguration {
@Bean @Bean
public FeignContentGzipEncodingInterceptor feignContentGzipEncodingInterceptor(FeignClientEncodingProperties properties) { public FeignContentGzipEncodingInterceptor feignContentGzipEncodingInterceptor(
FeignClientEncodingProperties properties) {
return new FeignContentGzipEncodingInterceptor(properties); return new FeignContentGzipEncodingInterceptor(properties);
} }
} }
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2017 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,13 +16,14 @@
package org.springframework.cloud.openfeign.encoding; package org.springframework.cloud.openfeign.encoding;
import feign.RequestTemplate;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
import feign.RequestTemplate;
/** /**
* Enables the HTTP request payload compression by specifying the {@code Content-Encoding} headers. * Enables the HTTP request payload compression by specifying the {@code Content-Encoding}
* headers.
* *
* @author Jakub Narloch * @author Jakub Narloch
*/ */
@@ -30,7 +31,6 @@ 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(FeignClientEncodingProperties properties) { protected FeignContentGzipEncodingInterceptor(FeignClientEncodingProperties properties) {
@@ -51,7 +51,6 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
/** /**
* Returns whether the request requires GZIP compression. * Returns whether the request requires GZIP compression.
*
* @param template the request template * @param template the request template
* @return true if request requires compression, false otherwise * @return true if request requires compression, false otherwise
*/ */
@@ -64,7 +63,6 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
/** /**
* Returns whether the request content length exceed configured minimum size. * Returns whether the request content length exceed configured minimum size.
*
* @param contentLength the content length header value * @param contentLength the content length header value
* @return true if length is grater than minimum size, false otherwise * @return true if length is grater than minimum size, false otherwise
*/ */
@@ -78,14 +76,14 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
final String strLen = contentLength.iterator().next(); final String strLen = contentLength.iterator().next();
final long length = Long.parseLong(strLen); final long length = Long.parseLong(strLen);
return length > getProperties().getMinRequestSize(); return length > getProperties().getMinRequestSize();
} catch (NumberFormatException ex) { }
catch (NumberFormatException ex) {
return false; return false;
} }
} }
/** /**
* 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
*/ */
@@ -107,4 +105,5 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
return false; return false;
} }
} }
@@ -1,11 +1,11 @@
/* /*
* Copyright 2013-2017 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -52,4 +52,5 @@ public interface HttpEncoding {
* The Deflate encoding. * The Deflate encoding.
*/ */
String DEFLATE_ENCODING = "deflate"; String DEFLATE_ENCODING = "deflate";
} }
@@ -0,0 +1,49 @@
/*
* 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 org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration;
import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration;
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.Configuration;
import org.springframework.hateoas.config.HateoasConfiguration;
import org.springframework.hateoas.config.WebConverters;
/**
* @author Hector Espert
* @author Olga Maciaszek-Sharma
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
@ConditionalOnClass(WebConverters.class)
@AutoConfigureAfter({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
RepositoryRestMvcAutoConfiguration.class, HateoasConfiguration.class })
public class FeignHalAutoConfiguration {
@Bean
@ConditionalOnBean(WebConverters.class)
HttpMessageConverterCustomizer webConvertersCustomizer(WebConverters webConverters) {
return new WebConvertersCustomizer(webConverters);
}
}
@@ -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);
}
}
@@ -0,0 +1,71 @@
/*
* 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.util.List;
import feign.Client;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
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.Conditional;
import org.springframework.context.annotation.Configuration;
/**
* Configuration instantiating a {@link LoadBalancerClient}-based {@link Client} object
* that uses {@link Client.Default} under the hood.
*
* @author Olga Maciaszek-Sharma
* @author changjin wei(魏昌进)
* @since 2.2.0
*/
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
class DefaultFeignLoadBalancerConfiguration {
@Bean
@ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(LoadBalancerClient loadBalancerClient,
LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
return new FeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient,
loadBalancerClientFactory, transformers);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
@ConditionalOnBean(LoadBalancedRetryFactory.class)
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
matchIfMissing = true)
public Client feignRetryClient(LoadBalancerClient loadBalancerClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
return new RetryableFeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient,
loadBalancedRetryFactory, loadBalancerClientFactory, transformers);
}
}
@@ -0,0 +1,165 @@
/*
* 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.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import feign.Client;
import feign.Request;
import feign.Response;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.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.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 LoadBalancerClient} to select a
* {@link ServiceInstance} to use while resolving the request host.
*
* @author Olga Maciaszek-Sharma
* @author changjin wei(魏昌进)
* @since 2.2.0
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class FeignBlockingLoadBalancerClient implements Client {
private static final Log LOG = LogFactory.getLog(FeignBlockingLoadBalancerClient.class);
private final Client delegate;
private final LoadBalancerClient loadBalancerClient;
private final LoadBalancerClientFactory loadBalancerClientFactory;
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.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
public Response execute(Request request, Request.Options options) throws IOException {
final URI originalUri = URI.create(request.url());
String serviceId = originalUri.getHost();
Assert.state(serviceId != null, "Request URI does not contain a valid hostname: " + originalUri);
String hint = getHint(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) {
String message = "Load balancer does not contain an instance for the service " + serviceId;
if (LOG.isWarnEnabled()) {
LOG.warn(message);
}
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle
.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();
}
String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri).toString();
Request newRequest = buildRequest(request, reconstructedUrl, instance);
return executeWithLoadBalancerLifecycleProcessing(delegate, options, newRequest, lbRequest, lbResponse,
supportedLifecycleProcessors);
}
protected Request buildRequest(Request request, String reconstructedUrl) {
return Request.create(request.httpMethod(), reconstructedUrl, request.headers(), request.body(),
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
public Client getDelegate() {
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;
}
}
@@ -0,0 +1,57 @@
/*
* 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.Client;
import feign.Feign;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.support.FeignHttpClientProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* An autoconfiguration that instantiates {@link LoadBalancerClient}-based implementations
* of {@link Client}.
*
* @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh
* @since 2.2.0
*/
@ConditionalOnClass(Feign.class)
@ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@AutoConfigureBefore(FeignAutoConfiguration.class)
@AutoConfigureAfter({ BlockingLoadBalancerClientAutoConfiguration.class, LoadBalancerAutoConfiguration.class })
@EnableConfigurationProperties(FeignHttpClientProperties.class)
@Configuration(proxyBeanMethods = false)
// 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({ HttpClientFeignLoadBalancerConfiguration.class, OkHttpFeignLoadBalancerConfiguration.class,
HttpClient5FeignLoadBalancerConfiguration.class, DefaultFeignLoadBalancerConfiguration.class })
public class FeignLoadBalancerAutoConfiguration {
}
@@ -0,0 +1,80 @@
/*
* 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.util.List;
import feign.Client;
import feign.hc5.ApacheHttp5Client;
import org.apache.hc.client5.http.classic.HttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
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.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Configuration instantiating a {@link LoadBalancerClient}-based {@link Client} object
* that uses {@link ApacheHttp5Client} under the hood.
*
* @author Nguyen Ky Thanh
* @author changjin wei(魏昌进)
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttp5Client.class)
@ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.hc5.enabled", havingValue = "true")
@Import(HttpClient5FeignConfiguration.class)
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
class HttpClient5FeignLoadBalancerConfiguration {
@Bean
@ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient5,
LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
Client delegate = new ApacheHttp5Client(httpClient5);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancerClientFactory,
transformers);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
@ConditionalOnBean(LoadBalancedRetryFactory.class)
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
matchIfMissing = true)
public Client feignRetryClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient5,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
Client delegate = new ApacheHttp5Client(httpClient5);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
loadBalancerClientFactory, transformers);
}
}
@@ -0,0 +1,84 @@
/*
* 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.util.List;
import feign.Client;
import feign.httpclient.ApacheHttpClient;
import org.apache.http.client.HttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
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.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;
/**
* Configuration instantiating a {@link LoadBalancerClient}-based {@link Client} object
* that uses {@link ApacheHttpClient} under the hood.
*
* @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh
* @author changjin wei(魏昌进)
* @since 2.2.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttpClient.class)
@ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.enabled", matchIfMissing = true)
@Conditional(HttpClient5DisabledConditions.class)
@Import(HttpClientFeignConfiguration.class)
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
class HttpClientFeignLoadBalancerConfiguration {
@Bean
@ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient,
LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancerClientFactory,
transformers);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
@ConditionalOnBean(LoadBalancedRetryFactory.class)
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
matchIfMissing = true)
public Client feignRetryClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
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,11 +1,11 @@
/* /*
* Copyright 2013-2018 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.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -13,33 +13,34 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.cloud.openfeign.ribbon;
package org.springframework.cloud.openfeign.loadbalancer;
import java.io.ByteArrayInputStream;
import java.net.URI;
import feign.Response; import feign.Response;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import org.springframework.cloud.client.loadbalancer.RetryableStatusCodeException; import org.springframework.cloud.client.loadbalancer.RetryableStatusCodeException;
import org.springframework.util.StreamUtils;
/** /**
* A {@link RetryableStatusCodeException} for {@link Response}s * A {@link RetryableStatusCodeException} for {@link Response}s.
*
* @author Ryan Baxter * @author Ryan Baxter
*/ */
public class RibbonResponseStatusCodeException extends RetryableStatusCodeException { public class LoadBalancerResponseStatusCodeException extends RetryableStatusCodeException {
private Response response;
public RibbonResponseStatusCodeException(String serviceId, Response response, byte[] body, URI uri) { private final Response response;
public LoadBalancerResponseStatusCodeException(String serviceId, Response response, byte[] body, URI uri) {
super(serviceId, response.status(), response, uri); super(serviceId, response.status(), response, uri);
this.response = Response.builder().body(new ByteArrayInputStream(body), body.length) this.response = Response.builder().body(new ByteArrayInputStream(body), body.length).headers(response.headers())
.headers(response.headers()).reason(response.reason()) .reason(response.reason()).status(response.status()).request(response.request()).build();
.status(response.status()).request(response.request()).build();
} }
@Override @Override
public Response getResponse() { public Response getResponse() {
return response; return this.response;
} }
} }
@@ -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);
}
}
@@ -0,0 +1,80 @@
/*
* 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.util.List;
import feign.Client;
import feign.okhttp.OkHttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
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.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Configuration instantiating a {@link LoadBalancerClient}-based {@link Client} object
* that uses {@link OkHttpClient} under the hood.
*
* @author Olga Maciaszek-Sharma
* @author changjin wei(魏昌进)
* @since 2.2.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OkHttpClient.class)
@ConditionalOnProperty("spring.cloud.openfeign.okhttp.enabled")
@ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@Import(OkHttpFeignConfiguration.class)
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
class OkHttpFeignLoadBalancerConfiguration {
@Bean
@ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(okhttp3.OkHttpClient okHttpClient, LoadBalancerClient loadBalancerClient,
LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
OkHttpClient delegate = new OkHttpClient(okHttpClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancerClientFactory,
transformers);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
@ConditionalOnBean(LoadBalancedRetryFactory.class)
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
matchIfMissing = true)
public Client feignRetryClient(LoadBalancerClient loadBalancerClient, okhttp3.OkHttpClient okHttpClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
OkHttpClient delegate = new OkHttpClient(okHttpClient);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
loadBalancerClientFactory, transformers);
}
}
@@ -0,0 +1,55 @@
/*
* 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 org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.retry.support.RetryTemplate;
/**
* A condition that verifies that {@link RetryTemplate} is on the classpath, a
* {@link LoadBalancedRetryFactory} bean is present and
* <code>spring.cloud.loadbalancer.retry.enabled</code> is not set to <code>false</code>.
*
* @author Olga Maciaszek-Sharma
* @since 2.2.6
*/
public class OnRetryNotEnabledCondition extends AnyNestedCondition {
public OnRetryNotEnabledCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnMissingClass("org.springframework.retry.support.RetryTemplate")
static class OnNoRetryTemplateCondition {
}
@ConditionalOnMissingBean(LoadBalancedRetryFactory.class)
static class OnRetryFactoryCondition {
}
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "false")
static class OnLoadBalancerRetryEnabledCondition {
}
}
@@ -0,0 +1,282 @@
/*
* 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.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import feign.Client;
import feign.Request;
import feign.Response;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.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.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.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.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.retry.RetryListener;
import org.springframework.retry.backoff.BackOffPolicy;
import org.springframework.retry.backoff.NoBackOffPolicy;
import org.springframework.retry.policy.NeverRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.util.Assert;
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
* load-balanced with Spring Cloud LoadBalancer.
*
* @author Olga Maciaszek-Sharma
* @author changjin wei(魏昌进)
* @since 2.2.6
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class RetryableFeignBlockingLoadBalancerClient implements Client {
private static final Log LOG = LogFactory.getLog(RetryableFeignBlockingLoadBalancerClient.class);
private final Client delegate;
private final LoadBalancerClient loadBalancerClient;
private final LoadBalancedRetryFactory loadBalancedRetryFactory;
private final LoadBalancerClientFactory loadBalancerClientFactory;
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.loadBalancerClient = loadBalancerClient;
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
public Response execute(Request request, Request.Options options) throws IOException {
final URI originalUri = URI.create(request.url());
String serviceId = originalUri.getHost();
Assert.state(serviceId != null, "Request URI does not contain a valid hostname: " + originalUri);
final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory.createRetryPolicy(serviceId,
loadBalancerClient);
RetryTemplate retryTemplate = buildRetryTemplate(serviceId, request, retryPolicy);
return retryTemplate.execute(context -> {
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
// and extract the server and update the request being made
if (context instanceof LoadBalancedRetryContext) {
LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context;
ServiceInstance serviceInstance = lbContext.getServiceInstance();
if (serviceInstance == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Service instance retrieved from LoadBalancedRetryContext: was null. "
+ "Reattempting service instance selection");
}
ServiceInstance previousServiceInstance = lbContext.getPreviousServiceInstance();
lbRequest.getContext().setPreviousServiceInstance(previousServiceInstance);
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 (retrievedServiceInstance == null) {
if (LOG.isWarnEnabled()) {
LOG.warn("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;
}
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();
if (retryPolicy != null && retryPolicy.retryableStatusCode(responseStatus)) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Retrying on status code: %d", responseStatus));
}
byte[] byteArray = response.body() == null ? new byte[] {}
: StreamUtils.copyToByteArray(response.body().asInputStream());
response.close();
throw new LoadBalancerResponseStatusCodeException(serviceId, response, byteArray,
URI.create(request.url()));
}
return response;
}, new LoadBalancedRecoveryCallback<Response, Response>() {
@Override
protected Response createResponse(Response response, URI uri) {
return response;
}
});
}
protected Request buildRequest(Request request, String reconstructedUrl) {
return Request.create(request.httpMethod(), reconstructedUrl, request.headers(), request.body(),
request.charset(), request.requestTemplate());
}
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;
}
private RetryTemplate buildRetryTemplate(String serviceId, Request request, LoadBalancedRetryPolicy retryPolicy) {
RetryTemplate retryTemplate = new RetryTemplate();
BackOffPolicy backOffPolicy = this.loadBalancedRetryFactory.createBackOffPolicy(serviceId);
retryTemplate.setBackOffPolicy(backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
RetryListener[] retryListeners = this.loadBalancedRetryFactory.createRetryListeners(serviceId);
if (retryListeners != null && retryListeners.length != 0) {
retryTemplate.setListeners(retryListeners);
}
retryTemplate.setRetryPolicy(retryPolicy == null ? new NeverRetryPolicy()
: new InterceptorRetryPolicy(toHttpRequest(request), retryPolicy, loadBalancerClient, serviceId));
return retryTemplate;
}
// Visible for Sleuth instrumentation
public Client getDelegate() {
return delegate;
}
private HttpRequest toHttpRequest(Request request) {
return new HttpRequest() {
@Override
public HttpMethod getMethod() {
return HttpMethod.resolve(request.httpMethod().name());
}
@Override
public String getMethodValue() {
return getMethod().name();
}
@Override
public URI getURI() {
return URI.create(request.url());
}
@Override
public HttpHeaders getHeaders() {
Map<String, List<String>> headers = new HashMap<>();
Map<String, Collection<String>> feignHeaders = request.headers();
for (String key : feignHeaders.keySet()) {
headers.put(key, new ArrayList<>(feignHeaders.get(key)));
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(headers);
return httpHeaders;
}
};
}
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,67 +0,0 @@
/*
* Copyright 2013-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.ribbon;
import java.util.Map;
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;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ILoadBalancer;
/**
* 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 = loadBalancedRetryFactory != null ? new RetryableFeignLoadBalancer(lb, config, serverIntrospector,
loadBalancedRetryFactory) : new FeignLoadBalancer(lb, config, serverIntrospector);
this.cache.put(clientName, client);
return client;
}
}
@@ -1,38 +0,0 @@
/*
* Copyright 2013-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.cloud.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
class DefaultFeignLoadBalancedConfiguration {
@Bean
@ConditionalOnMissingBean
public Client feignClient(CachingSpringLoadBalancerFactory cachingFactory,
SpringClientFactory clientFactory) {
return new LoadBalancerFeignClient(new Client.Default(null, null),
cachingFactory, clientFactory);
}
}
@@ -1,235 +0,0 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.ribbon;
import feign.Client;
import feign.Request;
import feign.Response;
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 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 com.netflix.client.AbstractLoadBalancerAwareClient;
import com.netflix.client.ClientException;
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 static org.springframework.cloud.netflix.ribbon.RibbonUtils.updateToSecureConnectionIfNeeded;
/**
* @author Dave Syer
* @author Spencer Gibb
* @author Ryan Baxter
* @author Tim Ysewyn
*/
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;
public FeignLoadBalancer(ILoadBalancer lb, IClientConfig clientConfig,
ServerIntrospector serverIntrospector) {
super(lb, clientConfig);
this.setRetryHandler(RetryHandler.DEFAULT);
this.clientConfig = clientConfig;
this.ribbon = RibbonProperties.from(clientConfig);
RibbonProperties ribbon = this.ribbon;
this.connectTimeout = ribbon.getConnectTimeout();
this.readTimeout = ribbon.getReadTimeout();
this.serverIntrospector = serverIntrospector;
}
@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(this.connectTimeout),
override.readTimeout(this.readTimeout));
}
else {
options = new Request.Options(this.connectTimeout, this.readTimeout);
}
Response response = request.client().execute(request.toRequest(), options);
return new RibbonResponse(request.getUri(), response);
}
@Override
public RequestSpecificRetryHandler getRequestSpecificRetryHandler(
RibbonRequest request, IClientConfig requestConfig) {
if (this.ribbon.isOkToRetryOnAllOperations()) {
return new RequestSpecificRetryHandler(true, true, this.getRetryHandler(),
requestConfig);
}
if (!request.toRequest().method().equals("GET")) {
return new RequestSpecificRetryHandler(true, false, this.getRetryHandler(),
requestConfig);
}
else {
return new RequestSpecificRetryHandler(true, true, this.getRetryHandler(),
requestConfig);
}
}
@Override
public URI reconstructURIWithServer(Server server, URI original) {
URI uri = updateToSecureConnectionIfNeeded(original, this.clientConfig, this.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.method(),getUri().toASCIIString(),headers,request.body(),request.charset());
}
Request toRequest() {
return toRequest(this.request);
}
Client client() {
return this.client;
}
HttpRequest toHttpRequest() {
return new HttpRequest() {
@Override
public HttpMethod getMethod() {
return HttpMethod.resolve(RibbonRequest.this.toRequest().method());
}
@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<String>(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(this.client, this.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() throws ClientException {
return this.response.body();
}
@Override
public boolean hasPayload() {
return this.response.body() != null;
}
@Override
public boolean isSuccess() {
return this.response.status() == 200;
}
@Override
public URI getRequestedURI() {
return this.uri;
}
@Override
public Map<String, Collection<String>> getHeaders() {
return this.response.headers();
}
Response toResponse() {
return this.response;
}
@Override
public void close() throws IOException {
if (this.response != null && this.response.body() != null) {
this.response.body().close();
}
}
}
}
@@ -1,119 +0,0 @@
/*
*
* * Copyright 2013-2016 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.cloud.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(serviceId, 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 serviceId;
}
@Override
public String getHost() {
return request.getURI().getHost();
}
@Override
public int getPort() {
return request.getURI().getPort();
}
@Override
public boolean isSecure() {
return "https".equals(request.getURI().getScheme());
}
@Override
public URI getUri() {
return request.getURI();
}
@Override
public Map<String, String> getMetadata() {
return metadata;
}
}
}
@@ -1,79 +0,0 @@
/*
* Copyright 2013-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.ribbon;
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.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import com.netflix.loadbalancer.ILoadBalancer;
import feign.Feign;
import feign.Request;
/**
* Autoconfiguration to be activated if Feign is in use and needs to be use Ribbon as a
* load balancer.
*
* @author Dave Syer
*/
@ConditionalOnClass({ ILoadBalancer.class, Feign.class })
@Configuration
@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,
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,128 +0,0 @@
/*
* Copyright 2013-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.cloud.openfeign.ribbon;
import feign.Client;
import feign.httpclient.ApacheHttpClient;
import java.util.Timer;
import java.util.TimerTask;
import javax.annotation.PreDestroy;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
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.commons.httpclient.ApacheHttpClientConnectionManagerFactory;
import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Spencer Gibb
*/
@Configuration
@ConditionalOnClass(ApacheHttpClient.class)
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
class HttpClientFeignLoadBalancedConfiguration {
@Configuration
@ConditionalOnMissingBean(CloseableHttpClient.class)
protected static class HttpClientFeignConfiguration {
private final Timer connectionManagerTimer = new Timer(
"FeignApacheHttpClientConfiguration.connectionManagerTimer", true);
private CloseableHttpClient httpClient;
@Autowired(required = false)
private RegistryBuilder registryBuilder;
@Bean
@ConditionalOnMissingBean(HttpClientConnectionManager.class)
public HttpClientConnectionManager connectionManager(
ApacheHttpClientConnectionManagerFactory connectionManagerFactory,
FeignHttpClientProperties httpClientProperties) {
final HttpClientConnectionManager connectionManager = connectionManagerFactory
.newConnectionManager(httpClientProperties.isDisableSslValidation(), httpClientProperties.getMaxConnections(),
httpClientProperties.getMaxConnectionsPerRoute(),
httpClientProperties.getTimeToLive(),
httpClientProperties.getTimeToLiveUnit(), registryBuilder);
this.connectionManagerTimer.schedule(new TimerTask() {
@Override
public void run() {
connectionManager.closeExpiredConnections();
}
}, 30000, httpClientProperties.getConnectionTimerRepeat());
return connectionManager;
}
@Bean
@ConditionalOnProperty(value = "feign.compression.response.enabled", havingValue = "true")
public CloseableHttpClient customHttpClient(HttpClientConnectionManager httpClientConnectionManager,
FeignHttpClientProperties httpClientProperties) {
HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement().useSystemProperties();
this.httpClient = createClient(builder, httpClientConnectionManager, httpClientProperties);
return this.httpClient;
}
@Bean
@ConditionalOnProperty(value = "feign.compression.response.enabled", havingValue = "false", matchIfMissing = true)
public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory, HttpClientConnectionManager httpClientConnectionManager,
FeignHttpClientProperties httpClientProperties) {
this.httpClient = createClient(httpClientFactory.createBuilder(), httpClientConnectionManager, httpClientProperties);
return this.httpClient;
}
private CloseableHttpClient createClient(HttpClientBuilder builder, HttpClientConnectionManager httpClientConnectionManager,
FeignHttpClientProperties httpClientProperties) {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(httpClientProperties.getConnectionTimeout())
.setRedirectsEnabled(httpClientProperties.isFollowRedirects())
.build();
CloseableHttpClient httpClient = builder.setDefaultRequestConfig(defaultRequestConfig).
setConnectionManager(httpClientConnectionManager).build();
return httpClient;
}
@PreDestroy
public void destroy() throws Exception {
connectionManagerTimer.cancel();
if(httpClient != null) {
httpClient.close();
}
}
}
@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,132 +0,0 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.ribbon;
import java.io.IOException;
import java.net.URI;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
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;
/**
* @author Dave Syer
*
*/
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;
}
@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;
}
static URI cleanUrl(String originalUrl, String host) {
String newUrl = originalUrl.replaceFirst(host, "");
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());
}
private FeignLoadBalancer lbClient(String clientName) {
return this.lbClientFactory.create(clientName);
}
static class FeignOptionsClientConfig extends DefaultClientConfigImpl {
public FeignOptionsClientConfig(Request.Options options) {
setProperty(CommonClientConfigKey.ConnectTimeout,
options.connectTimeoutMillis());
setProperty(CommonClientConfigKey.ReadTimeout, options.readTimeoutMillis());
}
@Override
public void loadProperties(String clientName) {
}
@Override
public void loadDefaultValues() {
}
}
}
@@ -1,87 +0,0 @@
/*
* Copyright 2013-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.cloud.openfeign.ribbon;
import feign.Client;
import feign.okhttp.OkHttpClient;
import okhttp3.ConnectionPool;
import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;
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.commons.httpclient.OkHttpClientConnectionPoolFactory;
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Spencer Gibb
*/
@Configuration
@ConditionalOnClass(OkHttpClient.class)
@ConditionalOnProperty(value = "feign.okhttp.enabled")
class OkHttpFeignLoadBalancedConfiguration {
@Configuration
@ConditionalOnMissingBean(okhttp3.OkHttpClient.class)
protected static class OkHttpFeignConfiguration {
private okhttp3.OkHttpClient okHttpClient;
@Bean
@ConditionalOnMissingBean(ConnectionPool.class)
public ConnectionPool httpClientConnectionPool(FeignHttpClientProperties httpClientProperties,
OkHttpClientConnectionPoolFactory connectionPoolFactory) {
Integer maxTotalConnections = httpClientProperties.getMaxConnections();
Long timeToLive = httpClientProperties.getTimeToLive();
TimeUnit ttlUnit = httpClientProperties.getTimeToLiveUnit();
return connectionPoolFactory.create(maxTotalConnections, timeToLive, ttlUnit);
}
@Bean
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory,
ConnectionPool connectionPool, FeignHttpClientProperties httpClientProperties) {
Boolean followRedirects = httpClientProperties.isFollowRedirects();
Integer connectTimeout = httpClientProperties.getConnectionTimeout();
this.okHttpClient = httpClientFactory.createBuilder(httpClientProperties.isDisableSslValidation()).
connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).
followRedirects(followRedirects).
connectionPool(connectionPool).build();
return this.okHttpClient;
}
@PreDestroy
public void destroy() {
if(okHttpClient != null) {
okHttpClient.dispatcher().executorService().shutdown();
okHttpClient.connectionPool().evictAll();
}
}
}
@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,131 +0,0 @@
/*
*
* * Copyright 2013-2016 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.springframework.cloud.openfeign.ribbon;
import feign.Request;
import feign.Response;
import java.io.IOException;
import java.net.URI;
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.RetryCallback;
import org.springframework.retry.RetryContext;
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;
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;
/**
* 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 = loadBalancedRetryFactory.createRetryPolicy(this.getClientName(), this);
RetryTemplate retryTemplate = new RetryTemplate();
BackOffPolicy backOffPolicy = loadBalancedRetryFactory.createBackOffPolicy(this.getClientName());
retryTemplate.setBackOffPolicy(backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
RetryListener[] retryListeners = this.loadBalancedRetryFactory.createRetryListeners(this.getClientName());
if (retryListeners != null && retryListeners.length != 0) {
retryTemplate.setListeners(retryListeners);
}
retryTemplate.setRetryPolicy(retryPolicy == null ? new NeverRetryPolicy()
: new FeignRetryPolicy(request.toHttpRequest(), retryPolicy, this, this.getClientName()));
return retryTemplate.execute(new RetryCallback<RibbonResponse, IOException>() {
@Override
public RibbonResponse doWithRetry(RetryContext retryContext) throws IOException {
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.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));
}
}
@@ -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;
}
}

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