Compare commits

...
193 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
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
197 changed files with 2931 additions and 1243 deletions
+6 -11
View File
@@ -16,21 +16,16 @@ jobs:
strategy: strategy:
matrix: matrix:
java: ["8", "11", "16"] java: ["17"]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Set up JDK 1.8 - name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v1 uses: actions/setup-java@v2
with: with:
java-version: 1.8 distribution: 'zulu'
- name: Cache local Maven repository java-version: ${{ matrix.java }}
uses: actions/cache@v2 cache: 'maven'
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Build with Maven - name: Build with Maven
run: ./mvnw clean install -B -U -P sonar run: ./mvnw clean install -B -U -P sonar
- uses: codecov/codecov-action@v1 - uses: codecov/codecov-action@v1
-1
View File
@@ -20,5 +20,4 @@ _site/
*.swo *.swo
.vscode/ .vscode/
.flattened-pom.xml .flattened-pom.xml
.sdkmanrc
+3
View File
@@ -0,0 +1,3 @@
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=17.0.1-tem
+55 -17
View File
@@ -40,7 +40,8 @@ and binding to the Spring Environment and other Spring programming model idioms.
== Building == Building
:jdkversion: 1.8
:jdkversion: 17
=== Basic Compile and Test === Basic Compile and Test
@@ -66,23 +67,9 @@ the `.mvn` configuration, so if you find you have to do it to make a
build succeed, please raise a ticket to get the settings added to build succeed, please raise a ticket to get the settings added to
source control. source control.
For hints on how to build the project look in `.travis.yml` if there The projects that require middleware (i.e. Redis) for testing generally
is one. There should be a "script" and maybe "install" command. Also require that a local instance of [Docker](https://www.docker.com/get-started) is installed and running.
look at the "services" section to see if any services need to be
running locally (e.g. mongo or rabbit). Ignore the git-related bits
that you might find in "before_install" since they're related to setting git
credentials and you already have those.
The projects that require middleware generally include a
`docker-compose.yml`, so consider using
https://docs.docker.com/compose/[Docker Compose] to run the middeware servers
in Docker containers. See the README in the
https://github.com/spring-cloud-samples/scripts[scripts demo
repository] for specific instructions about the common cases of mongo,
rabbit and redis.
NOTE: If all else fails, build with the command from `.travis.yml` (usually
`./mvnw install`).
=== Documentation === Documentation
@@ -317,6 +304,57 @@ Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on t
IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources. IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources.
=== Duplicate Finder
Spring Cloud Build brings along the `basepom:duplicate-finder-maven-plugin`, that enables flagging duplicate and conflicting classes and resources on the java classpath.
==== Duplicate Finder configuration
Duplicate finder is *enabled by default* and will run in the `verify` phase of your Maven build, but it will only take effect in your project if you add the `duplicate-finder-maven-plugin` to the `build` section of the projecst's `pom.xml`.
.pom.xml
[source,xml]
----
<build>
<plugins>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
----
For other properties, we have set defaults as listed in the https://github.com/basepom/duplicate-finder-maven-plugin/wiki[plugin documentation].
You can easily override them but setting the value of the selected property prefixed with `duplicate-finder-maven-plugin`. For example, set `duplicate-finder-maven-plugin.skip` to `true` in order to skip duplicates check in your build.
If you need to add `ignoredClassPatterns` or `ignoredResourcePatterns` to your setup, make sure to add them in the plugin configuration section of your project:
[source,xml]
----
<build>
<plugins>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
<configuration>
<ignoredClassPatterns>
<ignoredClassPattern>org.joda.time.base.BaseDateTime</ignoredClassPattern>
<ignoredClassPattern>.*module-info</ignoredClassPattern>
</ignoredClassPatterns>
<ignoredResourcePatterns>
<ignoredResourcePattern>changelog.txt</ignoredResourcePattern>
</ignoredResourcePatterns>
</configuration>
</plugin>
</plugins>
</build>
----
== License == License
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/main/LICENSE.txt[here]. The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/main/LICENSE.txt[here].
+3 -1
View File
@@ -6,7 +6,7 @@
<parent> <parent>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId> <artifactId>spring-cloud-openfeign</artifactId>
<version>3.1.0-M1</version> <version>4.0.0-SNAPSHOT</version>
</parent> </parent>
<artifactId>spring-cloud-openfeign-docs</artifactId> <artifactId>spring-cloud-openfeign-docs</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
@@ -17,6 +17,8 @@
<main.basedir>${basedir}/..</main.basedir> <main.basedir>${basedir}/..</main.basedir>
<configprops.inclusionPattern>feign.*</configprops.inclusionPattern> <configprops.inclusionPattern>feign.*</configprops.inclusionPattern>
<upload-docs-zip.phase>deploy</upload-docs-zip.phase> <upload-docs-zip.phase>deploy</upload-docs-zip.phase>
<!-- Don't upload docs jar to central / repo.spring.io -->
<maven-deploy-plugin-default.phase>none</maven-deploy-plugin-default.phase>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
+32 -29
View File
@@ -1,34 +1,37 @@
|=== |===
|Name | Default | Description |Name | Default | Description
|feign.autoconfiguration.jackson.enabled | `false` | If true, PageJacksonModule and SortJacksonModule bean will be provided for Jackson page decoding. |spring.cloud.openfeign.autoconfiguration.jackson.enabled | `false` | If true, PageJacksonModule and SortJacksonModule bean will be provided for Jackson page decoding.
|feign.circuitbreaker.enabled | `false` | If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker. |spring.cloud.openfeign.circuitbreaker.enabled | `false` | If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker.
|feign.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.circuitbreaker.group.enabled | `false` | If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker with with group.
|feign.client.config | | |spring.cloud.openfeign.client.config | |
|feign.client.decode-slash | `true` | Feign clients do not encode slash `/` characters by default. To change this behavior, set the `decodeSlash` to `false`. |spring.cloud.openfeign.client.decode-slash | `true` | Feign clients do not encode slash `/` characters by default. To change this behavior, set the `decodeSlash` to `false`.
|feign.client.default-config | `default` | |spring.cloud.openfeign.client.default-config | `default` |
|feign.client.default-to-properties | `true` | |spring.cloud.openfeign.client.default-to-properties | `true` |
|feign.client.refresh-enabled | `false` | Enables options value refresh capability for Feign. |spring.cloud.openfeign.client.refresh-enabled | `false` | Enables options value refresh capability for Feign.
|feign.compression.request.enabled | `false` | Enables the request sent by Feign to be compressed. |spring.cloud.openfeign.compression.request.enabled | `false` | Enables the request sent by Feign to be compressed.
|feign.compression.request.mime-types | `[text/xml, application/xml, application/json]` | The list of supported mime types. |spring.cloud.openfeign.compression.request.mime-types | `[text/xml, application/xml, application/json]` | The list of supported mime types.
|feign.compression.request.min-request-size | `2048` | The minimum threshold content size. |spring.cloud.openfeign.compression.request.min-request-size | `2048` | The minimum threshold content size.
|feign.compression.response.enabled | `false` | Enables the response from Feign to be compressed. |spring.cloud.openfeign.compression.response.enabled | `false` | Enables the response from Feign to be compressed.
|feign.encoder.charset-from-content-type | `false` | Indicates whether the charset should be derived from the {@code Content-Type} header. |spring.cloud.openfeign.encoder.charset-from-content-type | `false` | Indicates whether the charset should be derived from the {@code Content-Type} header.
|feign.httpclient.connection-timeout | `2000` | |spring.cloud.openfeign.httpclient.connection-timeout | `2000` |
|feign.httpclient.connection-timer-repeat | `3000` | |spring.cloud.openfeign.httpclient.connection-timer-repeat | `3000` |
|feign.httpclient.disable-ssl-validation | `false` | |spring.cloud.openfeign.httpclient.disable-ssl-validation | `false` |
|feign.httpclient.enabled | `true` | Enables the use of the Apache HTTP Client by Feign. |spring.cloud.openfeign.httpclient.enabled | `true` | Enables the use of the Apache HTTP Client by Feign.
|feign.httpclient.follow-redirects | `true` | |spring.cloud.openfeign.httpclient.follow-redirects | `true` |
|feign.httpclient.hc5.enabled | `false` | Enables the use of the Apache HTTP Client 5 by Feign. |spring.cloud.openfeign.httpclient.hc5.enabled | `false` | Enables the use of the Apache HTTP Client 5 by Feign.
|feign.httpclient.hc5.pool-concurrency-policy | | Pool concurrency policies. |spring.cloud.openfeign.httpclient.hc5.pool-concurrency-policy | | Pool concurrency policies.
|feign.httpclient.hc5.pool-reuse-policy | | Pool connection re-use policies. |spring.cloud.openfeign.httpclient.hc5.pool-reuse-policy | | Pool connection re-use policies.
|feign.httpclient.hc5.socket-timeout | `5` | Default value for socket timeout. |spring.cloud.openfeign.httpclient.hc5.socket-timeout | `5` | Default value for socket timeout.
|feign.httpclient.hc5.socket-timeout-unit | | Default value for socket timeout unit. |spring.cloud.openfeign.httpclient.hc5.socket-timeout-unit | | Default value for socket timeout unit.
|feign.httpclient.max-connections | `200` | |spring.cloud.openfeign.httpclient.max-connections | `200` |
|feign.httpclient.max-connections-per-route | `50` | |spring.cloud.openfeign.httpclient.max-connections-per-route | `50` |
|feign.httpclient.time-to-live | `900` | |spring.cloud.openfeign.httpclient.ok-http.read-timeout | `60s` | {@link OkHttpClient} read timeout; defaults to 60 seconds.
|feign.httpclient.time-to-live-unit | | |spring.cloud.openfeign.httpclient.time-to-live | `900` |
|feign.metrics.enabled | `true` | Enables metrics capability for Feign. |spring.cloud.openfeign.httpclient.time-to-live-unit | |
|feign.okhttp.enabled | `false` | Enables the use of the OK HTTP Client by Feign. |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.
|=== |===
@@ -69,7 +69,7 @@ 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 configure a list of servers don't want to use Eureka, you can configure a list of servers
in your external configuration using https://cloud.spring.io/spring-cloud-static/spring-cloud-commons/current/reference/html/#simplediscoveryclient[`SimpleDiscoveryClient`]. in your external configuration using https://docs.spring.io/spring-cloud-commons/docs/current/reference/html/#simplediscoveryclient[`SimpleDiscoveryClient`].
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]. 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].
@@ -122,6 +122,7 @@ Spring Cloud OpenFeign provides the following beans by default for feign (`BeanT
* `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 * `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: `FeignCircuitBreaker.Builder` * `Feign.Builder` feignBuilder: `FeignCircuitBreaker.Builder`
* `Client` feignClient: If Spring Cloud LoadBalancer is on the classpath, `FeignBlockingLoadBalancerClient` is used. * `Client` feignClient: If Spring Cloud LoadBalancer is on the classpath, `FeignBlockingLoadBalancerClient` is used.
@@ -129,7 +130,7 @@ If none of them is on the classpath, the default feign client is used.
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. NOTE: `spring-cloud-starter-openfeign` supports `spring-cloud-starter-loadbalancer`. However, as is an optional dependency, you need to make sure it been added to your project if you want to use it.
The OkHttpClient and ApacheHttpClient and ApacheHC5 feign clients can be used by setting `feign.okhttp.enabled` or `feign.httpclient.enabled` or `feign.httpclient.hc5.enabled` to `true`, respectively, and having them on the classpath. The OkHttpClient and ApacheHttpClient and ApacheHC5 feign clients can be used by setting `spring.cloud.openfeign.okhttp.enabled` or `spring.cloud.openfeign.httpclient.enabled` or `spring.cloud.openfeign.httpclient.hc5.enabled` to `true`, respectively, and having them on the classpath.
You can customize the HTTP client used by providing a bean of either `org.apache.http.impl.client.CloseableHttpClient` when using Apache or `okhttp3.OkHttpClient` when using OK HTTP or `org.apache.hc.client5.http.impl.classic.CloseableHttpClient` when using Apache HC5. You can customize the HTTP client used by providing a bean of either `org.apache.http.impl.client.CloseableHttpClient` when using Apache or `okhttp3.OkHttpClient` when using OK HTTP or `org.apache.hc.client5.http.impl.classic.CloseableHttpClient` when using Apache HC5.
Spring Cloud OpenFeign _does not_ provide the following beans by default for feign, but still looks up beans of these types from the application context to create the feign client: Spring Cloud OpenFeign _does not_ provide the following beans by default for feign, but still looks up beans of these types from the application context to create the feign client:
@@ -141,7 +142,7 @@ Spring Cloud OpenFeign _does not_ provide the following beans by default for fei
* `Collection<RequestInterceptor>` * `Collection<RequestInterceptor>`
* `SetterFactory` * `SetterFactory`
* `QueryMapEncoder` * `QueryMapEncoder`
* `Capability` (`MicrometerCapability` is provided by default) * `Capability` (`MicrometerCapability` and `CachingCapability` are provided by default)
A bean of `Retryer.NEVER_RETRY` with the type `Retryer` is created by default, which will disable retrying. A bean of `Retryer.NEVER_RETRY` with the type `Retryer` is created by default, which will disable retrying.
Notice this retrying behavior is different from the Feign default one, where it will automatically retry IOExceptions, Notice this retrying behavior is different from the Feign default one, where it will automatically retry IOExceptions,
@@ -172,7 +173,9 @@ This replaces the `SpringMvcContract` with `feign.Contract.Default` and adds a `
application.yml application.yml
[source,yaml] [source,yaml]
---- ----
feign: spring:
cloud:
openfeign:
client: client:
config: config:
feignName: feignName:
@@ -195,19 +198,22 @@ feign:
capabilities: capabilities:
- com.example.FooCapability - com.example.FooCapability
- com.example.BarCapability - com.example.BarCapability
queryMapEncoder: com.example.SimpleQueryMapEncoder
metrics.enabled: false metrics.enabled: false
---- ----
Default configurations can be specified in the `@EnableFeignClients` attribute `defaultConfiguration` in a similar manner as described above. The difference is that this configuration will apply to _all_ feign clients. Default configurations can be specified in the `@EnableFeignClients` attribute `defaultConfiguration` in a similar manner as described above. The difference is that this configuration will apply to _all_ feign clients.
If you prefer using configuration properties to configured all `@FeignClient`, you can create configuration properties with `default` feign name. If you prefer using configuration properties to configure all `@FeignClient`, you can create configuration properties with `default` feign name.
You can use `feign.client.config.feignName.defaultQueryParameters` and `feign.client.config.feignName.defaultRequestHeaders` to specify query parameters and headers that will be sent with every request of the client named `feignName`. You can use `spring.cloud.openfeign.client.config.feignName.defaultQueryParameters` and `spring.cloud.openfeign.client.config.feignName.defaultRequestHeaders` to specify query parameters and headers that will be sent with every request of the client named `feignName`.
application.yml application.yml
[source,yaml] [source,yaml]
---- ----
feign: spring:
cloud:
openfeign:
client: client:
config: config:
default: default:
@@ -218,7 +224,7 @@ feign:
If we create both `@Configuration` bean and configuration properties, configuration properties will win. If we create both `@Configuration` bean and configuration properties, configuration properties will win.
It will override `@Configuration` values. But if you want to change the priority to `@Configuration`, It will override `@Configuration` values. But if you want to change the priority to `@Configuration`,
you can change `feign.client.default-to-properties` to `false`. you can change `spring.cloud.openfeign.client.default-to-properties` to `false`.
If we want to create multiple feign clients with the same name or url If we want to create multiple feign clients with the same name or url
so that they would point to the same server but each with a different custom configuration then so that they would point to the same server but each with a different custom configuration then
@@ -264,13 +270,13 @@ public FeignClientConfigurer feignClientConfigurer() {
} }
---- ----
TIP: By default, Feign clients do not encode slash `/` characters. You can change this behaviour, by setting the value of `feign.client.decodeSlash` to `false`. TIP: By default, Feign clients do not encode slash `/` characters. You can change this behaviour, by setting the value of `spring.cloud.openfeign.client.decodeSlash` to `false`.
==== `SpringEncoder` configuration ==== `SpringEncoder` configuration
In the `SpringEncoder` that we provide, we set `null` charset for binary content types and `UTF-8` for all the other ones. In the `SpringEncoder` that we provide, we set `null` charset for binary content types and `UTF-8` for all the other ones.
You can modify this behaviour to derive the charset from the `Content-Type` header charset instead by setting the value of `feign.encoder.charset-from-content-type` to `true`. You can modify this behaviour to derive the charset from the `Content-Type` header charset instead by setting the value of `spring.cloud.openfeign.encoder.charset-from-content-type` to `true`.
[[timeout-handling]] [[timeout-handling]]
=== Timeout Handling === Timeout Handling
@@ -335,7 +341,7 @@ You can do this by overriding calling `inheritParentContext(false)` on the `Buil
[[spring-cloud-feign-circuitbreaker]] [[spring-cloud-feign-circuitbreaker]]
=== Feign Spring Cloud CircuitBreaker Support === Feign Spring Cloud CircuitBreaker Support
If Spring Cloud CircuitBreaker is on the classpath and `feign.circuitbreaker.enabled=true`, Feign will wrap all methods with a circuit breaker. If Spring Cloud CircuitBreaker is on the classpath and `spring.cloud.openfeign.circuitbreaker.enabled=true`, Feign will wrap all methods with a circuit breaker.
To disable Spring Cloud CircuitBreaker support on a per-client basis create a vanilla `Feign.Builder` with the "prototype" scope, e.g.: To disable Spring Cloud CircuitBreaker support on a per-client basis create a vanilla `Feign.Builder` with the "prototype" scope, e.g.:
@@ -368,8 +374,47 @@ public class FooConfiguration {
} }
---- ----
To enable Spring Cloud CircuitBreaker group set the `feign.circuitbreaker.group.enabled` property to `true` (by default `false`). To enable Spring Cloud CircuitBreaker group set the `spring.cloud.openfeign.circuitbreaker.group.enabled` property to `true` (by default `false`).
[[spring-clou-feign-circuitbreaker-configurationproperties]]
=== Configuring CircuitBreakers With Configuration Properties
You can configure CircuitBreakers via configuration properties.
For example, if you had this Feign client
[source,java,indent=0]
----
@FeignClient(url = "http://localhost:8080")
public interface DemoClient {
@GetMapping("demo")
String getDemo();
}
----
You could configure it using configuration properties by doing the following
[source,yaml,indent=0]
----
feign:
circuitbreaker:
enabled: true
alphanumeric-ids:
enabled: true
resilience4j:
circuitbreaker:
instances:
DemoClientgetDemo:
minimumNumberOfCalls: 69
timelimiter:
instances:
DemoClientgetDemo:
timeoutDuration: 10s
----
NOTE: If you want to switch back to the circuit breaker names used prior to Spring Cloud
2022.0.0 you can set `spring.cloud.openfeign.circuitbreaker.alphanumeric-ids.enabled` to `false`.
[[spring-cloud-feign-circuitbreaker-fallback]] [[spring-cloud-feign-circuitbreaker-fallback]]
=== Feign Spring Cloud CircuitBreaker Fallbacks === Feign Spring Cloud CircuitBreaker Fallbacks
@@ -494,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
@@ -506,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.
@@ -577,8 +619,8 @@ If all of the following conditions are true, a `MicrometerCapability` bean is cr
* `feign-micrometer` is on the classpath * `feign-micrometer` is on the classpath
* A `MeterRegistry` bean is available * A `MeterRegistry` bean is available
* feign metrics properties are set to `true` (by default) * feign metrics properties are set to `true` (by default)
- `feign.metrics.enabled=true` (for all clients) - `spring.cloud.openfeign.metrics.enabled=true` (for all clients)
- `feign.client.config.feignName.metrics.enabled=true` (for a single client) - `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. NOTE: If your application already uses Micrometer, enabling metrics is as simple as putting `feign-micrometer` onto your classpath.
@@ -586,11 +628,11 @@ You can also disable the feature by either:
* excluding `feign-micrometer` from your classpath * excluding `feign-micrometer` from your classpath
* setting one of the feign metrics properties to `false` * setting one of the feign metrics properties to `false`
- `feign.metrics.enabled=false` - `spring.cloud.openfeign.metrics.enabled=false`
- `feign.client.config.feignName.metrics.enabled=false` - `spring.cloud.openfeign.client.config.feignName.metrics.enabled=false`
NOTE: `feign.metrics.enabled=false` disables metrics support for *all* Feign clients regardless of the value of the client-level flags: `feign.client.config.feignName.metrics.enabled`. 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 `feign.metrics.enabled` and use `feign.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: You can also customize the `MicrometerCapability` by registering your own bean:
@@ -605,6 +647,22 @@ public class FooConfiguration {
} }
---- ----
=== Feign Caching
If `@EnableCaching` annotation is used, a `CachingCapability` bean is created and registered so that your Feign client recognizes `@Cache*` annotations on its interface:
[source,java,indent=0]
----
public interface DemoClient {
@GetMapping("/demo/{filterParam}")
@Cacheable(cacheNames = "demo-cache", key = "#keyParam")
String demoEndpoint(String keyParam, @PathVariable String filterParam);
}
----
You can also disable the feature via property `spring.cloud.openfeign.cache.enabled=false`.
=== Feign @QueryMap support === Feign @QueryMap support
The OpenFeign `@QueryMap` annotation provides support for POJOs to be used as The OpenFeign `@QueryMap` annotation provides support for POJOs to be used as
@@ -692,20 +750,21 @@ public interface DemoTemplate {
---- ----
=== Feign `CollectionFormat` support === Feign `CollectionFormat` support
We support `feign.CollectionFormat` by providing the `@CollectionFormat` annotation.You can annotate a Feign client method with it by passing the desired `feign.CollectionFormat` as annotation value. We support `feign.CollectionFormat` by providing the `@CollectionFormat` annotation.
You can annotate a Feign client method (or the whole class to affect all methods) with it by passing the desired `feign.CollectionFormat` as annotation value.
In the following example, the `CSV` format is used instead of the default `EXPLODED` to process the method. In the following example, the `CSV` format is used instead of the default `EXPLODED` to process the method.
[source,java,indent=0] [source,java,indent=0]
---- ----
@FeignClient(name = "demo") @FeignClient(name = "demo")
protected interface PageableFeignClient { protected interface PageableFeignClient {
@CollectionFormat(feign.CollectionFormat.CSV) @CollectionFormat(feign.CollectionFormat.CSV)
@GetMapping(path = "/page") @GetMapping(path = "/page")
ResponseEntity performRequest(Pageable page); ResponseEntity performRequest(Pageable page);
} }
---- ----
TIP: Set the `CSV` format while sending `Pageable` as a query parameter in order for it to be encoded correctly. TIP: Set the `CSV` format while sending `Pageable` as a query parameter in order for it to be encoded correctly.
@@ -723,7 +782,7 @@ To work around this problem you can use an `ObjectProvider` when autowiring your
[source,java,indent=0] [source,java,indent=0]
---- ----
@Autowired @Autowired
ObjectProvider<TestFeginClient> testFeginClient; ObjectProvider<TestFeignClient> testFeignClient;
---- ----
=== Spring Data Support === Spring Data Support
@@ -732,7 +791,7 @@ You may consider enabling Jackson Modules for the support `org.springframework.d
[source,java] [source,java]
---- ----
feign.autoconfiguration.jackson.enabled=true spring.cloud.openfeign.autoconfiguration.jackson.enabled=true
---- ----
=== Spring `@RefreshScope` Support === Spring `@RefreshScope` Support
@@ -741,10 +800,47 @@ If Feign client refresh is enabled, each feign client is created with `feign.Req
By default, refresh behavior in Feign clients is disabled. Use the following property to enable refresh behavior: By default, refresh behavior in Feign clients is disabled. Use the following property to enable refresh behavior:
[source,java] [source,java]
---- ----
feign.client.refresh-enabled=true spring.cloud.openfeign.client.refresh-enabled=true
---- ----
TIP: DO NOT annotate the `@FeignClient` interface with the `@RefreshScope` annotation. TIP: DO NOT annotate the `@FeignClient` interface with the `@RefreshScope` annotation.
=== OAuth2 Support
OAuth2 support can be enabled by setting following flag:
----
spring.cloud.openfeign.oauth2.enabled=true
----
When the flag is set to true, and the oauth2 client context resource details are present, a bean of class `OAuth2FeignRequestInterceptor` is created. Before each request, the interceptor resolves the required access token and includes it as a header.
Sometimes, when load balancing is enabled for Feign clients, you may want to use load balancing for fetching access tokens, too. To do so, you should ensure that the load balancer is on the classpath (spring-cloud-starter-loadbalancer) and explicitly enable load balancing for OAuth2FeignRequestInterceptor by setting the following flag:
----
spring.cloud.openfeign.oauth2.load-balanced=true
----
=== Transform the load-balanced HTTP request
You can use the selected `ServiceInstance` to transform the load-balanced HTTP Request.
For `Request`, you need to implement and define `LoadBalancerFeignRequestTransformer`, as follows:
[source,java,indent=0]
----
@Bean
public LoadBalancerFeignRequestTransformer transformer() {
return new LoadBalancerFeignRequestTransformer() {
@Override
public Request transformRequest(Request request, ServiceInstance instance) {
Map<String, Collection<String>> headers = new HashMap<>(request.headers());
headers.put("X-ServiceId", Collections.singletonList(instance.getServiceId()));
headers.put("X-InstanceId", Collections.singletonList(instance.getInstanceId()));
return Request.create(request.httpMethod(), request.url(), headers, request.body(), request.charset(),
request.requestTemplate());
}
};
}
----
If multiple transformers are defined, they are applied in the order in which beans are defined.
Alternatively, you can use `LoadBalancerFeignRequestTransformer.DEFAULT_ORDER` to specify the order.
== Configuration properties == Configuration properties
+17 -15
View File
@@ -4,14 +4,14 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-openfeign</artifactId> <artifactId>spring-cloud-openfeign</artifactId>
<version>3.1.0-M1</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>3.1.0-M1</version> <version>4.0.0-SNAPSHOT</version>
<relativePath/> <relativePath/>
</parent> </parent>
<scm> <scm>
@@ -26,7 +26,7 @@
<properties> <properties>
<main.basedir>${basedir}</main.basedir> <main.basedir>${basedir}</main.basedir>
<jackson.version>2.11.3</jackson.version> <jackson.version>2.11.3</jackson.version>
<spring-cloud-commons.version>3.1.0-M1</spring-cloud-commons.version> <spring-cloud-commons.version>4.0.0-SNAPSHOT</spring-cloud-commons.version>
<!-- Plugin versions --> <!-- Plugin versions -->
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version> <maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
@@ -64,13 +64,6 @@
</additionalConfig> </additionalConfig>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId> <artifactId>maven-checkstyle-plugin</artifactId>
@@ -79,6 +72,15 @@
<groupId>io.spring.javaformat</groupId> <groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId> <artifactId>spring-javaformat-maven-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
<configuration>
<ignoredResourcePatterns>
<ignoredResourcePattern>mozilla/public-suffix-list.txt</ignoredResourcePattern>
</ignoredResourcePatterns>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
@@ -133,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>
@@ -144,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>
@@ -162,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>
@@ -173,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>
@@ -181,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>
+36 -18
View File
@@ -6,7 +6,7 @@
<parent> <parent>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId> <artifactId>spring-cloud-openfeign</artifactId>
<version>3.1.0-M1</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>
@@ -61,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>
@@ -93,6 +94,13 @@
<dependency> <dependency>
<groupId>io.github.openfeign.form</groupId> <groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId> <artifactId>feign-form-spring</artifactId>
<exclusions>
<!-- Vulnerable in 3.8.0-->
<exclusion>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.github.openfeign</groupId> <groupId>io.github.openfeign</groupId>
@@ -119,11 +127,6 @@
<artifactId>feign-okhttp</artifactId> <artifactId>feign-okhttp</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava</artifactId>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>com.squareup.okhttp3</groupId> <groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId> <artifactId>okhttp</artifactId>
@@ -133,6 +136,20 @@
<groupId>org.springframework.security.oauth.boot</groupId> <groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId> <artifactId>spring-security-oauth2-autoconfigure</artifactId>
<optional>true</optional> <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> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
@@ -149,11 +166,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-test-support</artifactId> <artifactId>spring-cloud-test-support</artifactId>
@@ -183,13 +195,13 @@
<dependency> <dependency>
<groupId>com.google.protobuf</groupId> <groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId> <artifactId>protobuf-java</artifactId>
<version>3.14.0</version> <version>3.19.3</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.vavr</groupId> <groupId>io.vavr</groupId>
<artifactId>vavr</artifactId> <artifactId>vavr</artifactId>
<version>0.10.3</version> <version>0.10.4</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@@ -197,6 +209,12 @@
<artifactId>spring-cloud-loadbalancer</artifactId> <artifactId>spring-cloud-loadbalancer</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<profiles> <profiles>
<profile> <profile>
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -0,0 +1,42 @@
/*
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign;
import feign.Capability;
import feign.InvocationHandlerFactory;
import org.springframework.cache.interceptor.CacheInterceptor;
/**
* Allows Spring's @Cache* annotations to be declared on the feign client's methods.
*
* @author Sam Kruglov
*/
public class CachingCapability implements Capability {
private final CacheInterceptor cacheInterceptor;
public CachingCapability(CacheInterceptor cacheInterceptor) {
this.cacheInterceptor = cacheInterceptor;
}
@Override
public InvocationHandlerFactory enrich(InvocationHandlerFactory invocationHandlerFactory) {
return new FeignCachingInvocationHandlerFactory(invocationHandlerFactory, cacheInterceptor);
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -25,9 +25,10 @@ import java.lang.annotation.Target;
* Indicates which collection format should be used while processing the annotated method. * Indicates which collection format should be used while processing the annotated method.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Sam Kruglov
* @see feign.CollectionFormat * @see feign.CollectionFormat
*/ */
@Target(ElementType.METHOD) @Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface CollectionFormat { public @interface CollectionFormat {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2016-2020 the original author or authors. * Copyright 2016-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -18,15 +18,15 @@ package org.springframework.cloud.openfeign;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;
import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.Module;
import feign.Capability;
import feign.Client; import feign.Client;
import feign.Feign; import feign.Feign;
import feign.RequestInterceptor; import feign.RequestInterceptor;
@@ -34,6 +34,7 @@ import feign.Target;
import feign.hc5.ApacheHttp5Client; import feign.hc5.ApacheHttp5Client;
import feign.httpclient.ApacheHttpClient; import feign.httpclient.ApacheHttpClient;
import feign.okhttp.OkHttpClient; import feign.okhttp.OkHttpClient;
import jakarta.annotation.PreDestroy;
import okhttp3.ConnectionPool; import okhttp3.ConnectionPool;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@@ -50,14 +51,18 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.interceptor.CacheInterceptor;
import org.springframework.cloud.client.actuator.HasFeatures; import org.springframework.cloud.client.actuator.HasFeatures;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker; import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory; import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.cloud.client.loadbalancer.RetryLoadBalancerInterceptor;
import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory; import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory;
import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory; import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory;
import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory; import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory;
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory; import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptor; import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptor;
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptorConfigurer;
import org.springframework.cloud.openfeign.support.FeignEncoderProperties; import org.springframework.cloud.openfeign.support.FeignEncoderProperties;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties; import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.cloud.openfeign.support.PageJacksonModule; import org.springframework.cloud.openfeign.support.PageJacksonModule;
@@ -71,6 +76,8 @@ import org.springframework.data.domain.Sort;
import org.springframework.security.oauth2.client.OAuth2ClientContext; import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails; import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import static org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptorBuilder.buildWithConfigurers;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
* @author Julien Roy * @author Julien Roy
@@ -81,6 +88,8 @@ import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResour
* @author Nguyen Ky Thanh * @author Nguyen Ky Thanh
* @author Andrii Bohutskyi * @author Andrii Bohutskyi
* @author Kwangyong Kim * @author Kwangyong Kim
* @author Sam Kruglov
* @author Wojciech Mąka
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Feign.class) @ConditionalOnClass(Feign.class)
@@ -105,9 +114,16 @@ public class FeignAutoConfiguration {
return context; return context;
} }
@Bean
@ConditionalOnProperty(value = "spring.cloud.openfeign.cache.enabled", matchIfMissing = true)
@ConditionalOnBean(CacheInterceptor.class)
public Capability cachingCapability(CacheInterceptor cacheInterceptor) {
return new CachingCapability(cacheInterceptor);
}
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Module.class, Page.class, Sort.class }) @ConditionalOnClass({ Module.class, Page.class, Sort.class })
@ConditionalOnProperty(value = "feign.autoconfiguration.jackson.enabled", havingValue = "true") @ConditionalOnProperty(value = "spring.cloud.openfeign.autoconfiguration.jackson.enabled", havingValue = "true")
protected static class FeignJacksonConfiguration { protected static class FeignJacksonConfiguration {
@Bean @Bean
@@ -138,7 +154,7 @@ public class FeignAutoConfiguration {
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(CircuitBreaker.class) @ConditionalOnClass(CircuitBreaker.class)
@ConditionalOnProperty(value = "feign.circuitbreaker.enabled", havingValue = "true") @ConditionalOnProperty(value = "spring.cloud.openfeign.circuitbreaker.enabled", havingValue = "true")
protected static class CircuitBreakerPresentFeignTargeterConfiguration { protected static class CircuitBreakerPresentFeignTargeterConfiguration {
@Bean @Bean
@@ -149,15 +165,25 @@ public class FeignAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean(CircuitBreakerNameResolver.class) @ConditionalOnMissingBean(CircuitBreakerNameResolver.class)
@ConditionalOnProperty(value = "spring.cloud.openfeign.circuitbreaker.alphanumeric-ids.enabled",
havingValue = "false")
public CircuitBreakerNameResolver circuitBreakerNameResolver() { public CircuitBreakerNameResolver circuitBreakerNameResolver() {
return new DefaultCircuitBreakerNameResolver(); 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 @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnBean(CircuitBreakerFactory.class) @ConditionalOnBean(CircuitBreakerFactory.class)
public Targeter circuitBreakerFeignTargeter(CircuitBreakerFactory circuitBreakerFactory, public Targeter circuitBreakerFeignTargeter(CircuitBreakerFactory circuitBreakerFactory,
@Value("${feign.circuitbreaker.group.enabled:false}") boolean circuitBreakerGroupEnabled, @Value("${spring.cloud.openfeign.circuitbreaker.group.enabled:false}") boolean circuitBreakerGroupEnabled,
CircuitBreakerNameResolver circuitBreakerNameResolver) { CircuitBreakerNameResolver circuitBreakerNameResolver) {
return new FeignCircuitBreakerTargeter(circuitBreakerFactory, circuitBreakerGroupEnabled, return new FeignCircuitBreakerTargeter(circuitBreakerFactory, circuitBreakerGroupEnabled,
circuitBreakerNameResolver); circuitBreakerNameResolver);
@@ -167,7 +193,16 @@ public class FeignAutoConfiguration {
@Override @Override
public String resolveCircuitBreakerName(String feignClientName, Target<?> target, Method method) { public String resolveCircuitBreakerName(String feignClientName, Target<?> target, Method method) {
return Feign.configKey(target.getClass(), 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]", "");
} }
} }
@@ -181,7 +216,7 @@ public class FeignAutoConfiguration {
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttpClient.class) @ConditionalOnClass(ApacheHttpClient.class)
@ConditionalOnMissingBean(CloseableHttpClient.class) @ConditionalOnMissingBean(CloseableHttpClient.class)
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true) @ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.enabled", matchIfMissing = true)
@Conditional(HttpClient5DisabledConditions.class) @Conditional(HttpClient5DisabledConditions.class)
protected static class HttpClientFeignConfiguration { protected static class HttpClientFeignConfiguration {
@@ -249,7 +284,7 @@ public class FeignAutoConfiguration {
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OkHttpClient.class) @ConditionalOnClass(OkHttpClient.class)
@ConditionalOnMissingBean(okhttp3.OkHttpClient.class) @ConditionalOnMissingBean(okhttp3.OkHttpClient.class)
@ConditionalOnProperty("feign.okhttp.enabled") @ConditionalOnProperty("spring.cloud.openfeign.okhttp.enabled")
protected static class OkHttpFeignConfiguration { protected static class OkHttpFeignConfiguration {
private okhttp3.OkHttpClient okHttpClient; private okhttp3.OkHttpClient okHttpClient;
@@ -258,8 +293,8 @@ public class FeignAutoConfiguration {
@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);
} }
@@ -267,12 +302,13 @@ public class FeignAutoConfiguration {
@Bean @Bean
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, ConnectionPool connectionPool, public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, ConnectionPool connectionPool,
FeignHttpClientProperties httpClientProperties) { FeignHttpClientProperties httpClientProperties) {
Boolean followRedirects = httpClientProperties.isFollowRedirects(); boolean followRedirects = httpClientProperties.isFollowRedirects();
Integer connectTimeout = httpClientProperties.getConnectionTimeout(); int connectTimeout = httpClientProperties.getConnectionTimeout();
Boolean disableSslValidation = httpClientProperties.isDisableSslValidation(); boolean disableSslValidation = httpClientProperties.isDisableSslValidation();
Duration readTimeout = httpClientProperties.getOkHttp().getReadTimeout();
this.okHttpClient = httpClientFactory.createBuilder(disableSslValidation) this.okHttpClient = httpClientFactory.createBuilder(disableSslValidation)
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects) .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects)
.connectionPool(connectionPool).build(); .readTimeout(readTimeout).connectionPool(connectionPool).build();
return this.okHttpClient; return this.okHttpClient;
} }
@@ -295,7 +331,7 @@ public class FeignAutoConfiguration {
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttp5Client.class) @ConditionalOnClass(ApacheHttp5Client.class)
@ConditionalOnMissingBean(org.apache.hc.client5.http.impl.classic.CloseableHttpClient.class) @ConditionalOnMissingBean(org.apache.hc.client5.http.impl.classic.CloseableHttpClient.class)
@ConditionalOnProperty(value = "feign.httpclient.hc5.enabled", havingValue = "true") @ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.hc5.enabled", havingValue = "true")
@Import(org.springframework.cloud.openfeign.clientconfig.HttpClient5FeignConfiguration.class) @Import(org.springframework.cloud.openfeign.clientconfig.HttpClient5FeignConfiguration.class)
protected static class HttpClient5FeignConfiguration { protected static class HttpClient5FeignConfiguration {
@@ -309,15 +345,34 @@ public class FeignAutoConfiguration {
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OAuth2ClientContext.class) @ConditionalOnClass(OAuth2ClientContext.class)
@ConditionalOnProperty("feign.oauth2.enabled") @ConditionalOnProperty("spring.cloud.openfeign.oauth2.enabled")
@Deprecated // spring-security-oauth2 reached EOL
protected static class Oauth2FeignConfiguration { 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 @Bean
@ConditionalOnMissingBean(OAuth2FeignRequestInterceptor.class) @ConditionalOnMissingBean(OAuth2FeignRequestInterceptor.class)
@ConditionalOnBean({ OAuth2ClientContext.class, OAuth2ProtectedResourceDetails.class }) @ConditionalOnBean({ OAuth2ClientContext.class, OAuth2ProtectedResourceDetails.class })
public RequestInterceptor oauth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext, public RequestInterceptor oauth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext,
OAuth2ProtectedResourceDetails resource) { OAuth2ProtectedResourceDetails resource, List<OAuth2FeignRequestInterceptorConfigurer> configurers) {
return new OAuth2FeignRequestInterceptor(oAuth2ClientContext, resource); return buildWithConfigurers(oAuth2ClientContext, resource, configurers);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -0,0 +1,82 @@
/*
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Optional;
import feign.InvocationHandlerFactory;
import feign.Target;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.cache.interceptor.CacheInterceptor;
/**
* Allows Spring's @Cache* annotations to be declared on the feign client's methods.
*
* @author Sam Kruglov
*/
public class FeignCachingInvocationHandlerFactory implements InvocationHandlerFactory {
private final InvocationHandlerFactory delegateFactory;
private final CacheInterceptor cacheInterceptor;
public FeignCachingInvocationHandlerFactory(InvocationHandlerFactory delegateFactory,
CacheInterceptor cacheInterceptor) {
this.delegateFactory = delegateFactory;
this.cacheInterceptor = cacheInterceptor;
}
@Override
public InvocationHandler create(Target target, Map<Method, MethodHandler> dispatch) {
final InvocationHandler delegateHandler = delegateFactory.create(target, dispatch);
return (proxy, method, argsNullable) -> {
Object[] args = Optional.ofNullable(argsNullable).orElseGet(() -> new Object[0]);
return cacheInterceptor.invoke(new MethodInvocation() {
@Override
public Method getMethod() {
return method;
}
@Override
public Object[] getArguments() {
return args;
}
@Override
public Object proceed() throws Throwable {
return delegateHandler.invoke(proxy, method, args);
}
@Override
public Object getThis() {
return target;
}
@Override
public AccessibleObject getStaticPart() {
return method;
}
});
};
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -31,7 +31,8 @@ class FeignCircuitBreakerDisabledConditions extends AnyNestedCondition {
} }
@ConditionalOnProperty(value = "feign.circuitbreaker.enabled", havingValue = "false", matchIfMissing = true) @ConditionalOnProperty(value = "spring.cloud.openfeign.circuitbreaker.enabled", havingValue = "false",
matchIfMissing = true)
static class CircuitBreakerDisabled { static class CircuitBreakerDisabled {
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Proxy; import java.lang.reflect.Proxy;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@@ -29,6 +30,7 @@ import feign.Target;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker; import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory; import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.NoFallbackAvailableException;
import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
@@ -95,15 +97,29 @@ class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
try { try {
return this.fallbackMethodMap.get(method).invoke(fallback, args); return this.fallbackMethodMap.get(method).invoke(fallback, args);
} }
catch (Exception e) { catch (Exception exception) {
throw new IllegalStateException(e); unwrapAndRethrow(exception);
} }
return null;
}; };
return circuitBreaker.run(supplier, fallbackFunction); return circuitBreaker.run(supplier, fallbackFunction);
} }
return circuitBreaker.run(supplier); return circuitBreaker.run(supplier);
} }
private void unwrapAndRethrow(Exception exception) {
if (exception instanceof InvocationTargetException || exception instanceof NoFallbackAvailableException) {
Throwable underlyingException = exception.getCause();
if (underlyingException instanceof RuntimeException) {
throw (RuntimeException) underlyingException;
}
if (underlyingException != null) {
throw new IllegalStateException(underlyingException);
}
throw new IllegalStateException(exception);
}
}
private Supplier<Object> asSupplier(final Method method, final Object[] args) { private Supplier<Object> asSupplier(final Method method, final Object[] args) {
final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return () -> { return () -> {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
@@ -67,6 +68,8 @@ import org.springframework.util.StringUtils;
* @author Jonatan Ivanov * @author Jonatan Ivanov
* @author Sam Kruglov * @author Sam Kruglov
* @author Jasbir Singh * @author Jasbir Singh
* @author Hyeonmin Park
* @author Felix Dittrich
*/ */
public class FeignClientFactoryBean public class FeignClientFactoryBean
implements FactoryBean<Object>, InitializingBean, ApplicationContextAware, BeanFactoryAware { implements FactoryBean<Object>, InitializingBean, ApplicationContextAware, BeanFactoryAware {
@@ -130,7 +133,6 @@ public class FeignClientFactoryBean
// @formatter:on // @formatter:on
configureFeign(context, builder); configureFeign(context, builder);
applyBuildCustomizers(context, builder);
return builder; return builder;
} }
@@ -276,13 +278,8 @@ public class FeignClientFactoryBean
builder.encoder(getOrInstantiate(config.getEncoder())); builder.encoder(getOrInstantiate(config.getEncoder()));
} }
if (Objects.nonNull(config.getDefaultRequestHeaders())) { addDefaultRequestHeaders(config, builder);
builder.requestInterceptor(requestTemplate -> requestTemplate.headers(config.getDefaultRequestHeaders())); addDefaultQueryParams(config, builder);
}
if (Objects.nonNull(config.getDefaultQueryParameters())) {
builder.requestInterceptor(requestTemplate -> requestTemplate.queries(config.getDefaultQueryParameters()));
}
if (Objects.nonNull(config.getDecoder())) { if (Objects.nonNull(config.getDecoder())) {
builder.decoder(getOrInstantiate(config.getDecoder())); builder.decoder(getOrInstantiate(config.getDecoder()));
@@ -299,6 +296,39 @@ public class FeignClientFactoryBean
if (config.getCapabilities() != null) { if (config.getCapabilities() != null) {
config.getCapabilities().stream().map(this::getOrInstantiate).forEach(builder::addCapability); 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) {
@@ -344,6 +374,7 @@ public class FeignClientFactoryBean
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);
} }
@@ -413,11 +444,17 @@ public class FeignClientFactoryBean
} }
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<>(type, name, url)); return (T) targeter.target(this, builder, context, new HardCodedTarget<>(type, name, url));
} }
private String cleanPath() { private String cleanPath() {
if (path == null) {
return "";
}
String path = this.path.trim(); String path = this.path.trim();
if (StringUtils.hasLength(path)) { if (StringUtils.hasLength(path)) {
if (!path.startsWith("/")) { if (!path.startsWith("/")) {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2021-2021 the original author or authors. * Copyright 2021-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.
@@ -36,7 +36,7 @@ class FeignClientMetricsEnabledCondition implements Condition {
.getConfig(); .getConfig();
if (feignClientConfigMap != null) { if (feignClientConfigMap != null) {
FeignClientProperties.FeignClientConfiguration feignClientConfig = feignClientConfigMap FeignClientProperties.FeignClientConfiguration feignClientConfig = feignClientConfigMap
.get(context.getEnvironment().getProperty("feign.client.name")); .get(context.getEnvironment().getProperty("spring.cloud.openfeign.client.name"));
if (feignClientConfig != null) { if (feignClientConfig != null) {
FeignClientProperties.MetricsProperties metrics = feignClientConfig.getMetrics(); FeignClientProperties.MetricsProperties metrics = feignClientConfig.getMetrics();
if (metrics != null && metrics.getEnabled() != null) { if (metrics != null && metrics.getEnabled() != null) {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -26,6 +26,7 @@ import feign.Capability;
import feign.Contract; import feign.Contract;
import feign.ExceptionPropagationPolicy; import feign.ExceptionPropagationPolicy;
import feign.Logger; import feign.Logger;
import feign.QueryMapEncoder;
import feign.RequestInterceptor; import feign.RequestInterceptor;
import feign.Retryer; import feign.Retryer;
import feign.codec.Decoder; import feign.codec.Decoder;
@@ -40,8 +41,9 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
* @author Ram Anaswara * @author Ram Anaswara
* @author Jonatan Ivanov * @author Jonatan Ivanov
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Hyeonmin Park
*/ */
@ConfigurationProperties("feign.client") @ConfigurationProperties("spring.cloud.openfeign.client")
public class FeignClientProperties { public class FeignClientProperties {
private boolean defaultToProperties = true; private boolean defaultToProperties = true;
@@ -139,6 +141,8 @@ public class FeignClientProperties {
private List<Class<Capability>> capabilities; private List<Class<Capability>> capabilities;
private Class<QueryMapEncoder> queryMapEncoder;
private MetricsProperties metrics; private MetricsProperties metrics;
private Boolean followRedirects; private Boolean followRedirects;
@@ -255,6 +259,14 @@ public class FeignClientProperties {
this.capabilities = capabilities; this.capabilities = capabilities;
} }
public Class<QueryMapEncoder> getQueryMapEncoder() {
return queryMapEncoder;
}
public void setQueryMapEncoder(Class<QueryMapEncoder> queryMapEncoder) {
this.queryMapEncoder = queryMapEncoder;
}
public MetricsProperties getMetrics() { public MetricsProperties getMetrics() {
return metrics; return metrics;
} }
@@ -289,7 +301,8 @@ public class FeignClientProperties {
&& Objects.equals(exceptionPropagationPolicy, that.exceptionPropagationPolicy) && Objects.equals(exceptionPropagationPolicy, that.exceptionPropagationPolicy)
&& Objects.equals(defaultRequestHeaders, that.defaultRequestHeaders) && Objects.equals(defaultRequestHeaders, that.defaultRequestHeaders)
&& Objects.equals(defaultQueryParameters, that.defaultQueryParameters) && Objects.equals(defaultQueryParameters, that.defaultQueryParameters)
&& Objects.equals(capabilities, that.capabilities) && Objects.equals(metrics, that.metrics) && Objects.equals(capabilities, that.capabilities)
&& Objects.equals(queryMapEncoder, that.queryMapEncoder) && Objects.equals(metrics, that.metrics)
&& Objects.equals(followRedirects, that.followRedirects); && Objects.equals(followRedirects, that.followRedirects);
} }
@@ -297,7 +310,7 @@ public class FeignClientProperties {
public int hashCode() { public int hashCode() {
return Objects.hash(loggerLevel, connectTimeout, readTimeout, retryer, errorDecoder, requestInterceptors, return Objects.hash(loggerLevel, connectTimeout, readTimeout, retryer, errorDecoder, requestInterceptors,
decode404, encoder, decoder, contract, exceptionPropagationPolicy, defaultQueryParameters, decode404, encoder, decoder, contract, exceptionPropagationPolicy, defaultQueryParameters,
defaultRequestHeaders, capabilities, metrics, followRedirects); defaultRequestHeaders, capabilities, queryMapEncoder, metrics, followRedirects);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -25,7 +25,7 @@ import org.springframework.cloud.context.named.NamedContextFactory;
* @author Dave Syer * @author Dave Syer
* @author Gregor Zurowski * @author Gregor Zurowski
*/ */
class FeignClientSpecification implements NamedContextFactory.Specification { public class FeignClientSpecification implements NamedContextFactory.Specification {
private String name; private String name;
@@ -34,7 +34,7 @@ class FeignClientSpecification implements NamedContextFactory.Specification {
FeignClientSpecification() { FeignClientSpecification() {
} }
FeignClientSpecification(String name, Class<?>[] configuration) { public FeignClientSpecification(String name, Class<?>[] configuration) {
this.name = name; this.name = name;
this.configuration = configuration; this.configuration = configuration;
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -214,7 +214,7 @@ public class FeignClientsConfiguration {
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(CircuitBreaker.class) @ConditionalOnClass(CircuitBreaker.class)
@ConditionalOnProperty("feign.circuitbreaker.enabled") @ConditionalOnProperty("spring.cloud.openfeign.circuitbreaker.enabled")
protected static class CircuitBreakerPresentFeignBuilderConfiguration { protected static class CircuitBreakerPresentFeignBuilderConfiguration {
@Bean @Bean
@@ -237,7 +237,7 @@ public class FeignClientsConfiguration {
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnBean(type = "io.micrometer.core.instrument.MeterRegistry") @ConditionalOnBean(type = "io.micrometer.core.instrument.MeterRegistry")
@ConditionalOnClass(name = "feign.micrometer.MicrometerCapability") @ConditionalOnClass(name = "feign.micrometer.MicrometerCapability")
@ConditionalOnProperty(name = "feign.metrics.enabled", matchIfMissing = true) @ConditionalOnProperty(name = "spring.cloud.openfeign.metrics.enabled", matchIfMissing = true)
@Conditional(FeignClientMetricsEnabledCondition.class) @Conditional(FeignClientMetricsEnabledCondition.class)
protected static class MetricsConfiguration { protected static class MetricsConfiguration {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -302,7 +302,11 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar, ResourceLo
if (resolver == null) { if (resolver == null) {
return resolved; return resolved;
} }
return String.valueOf(resolver.evaluate(resolved, new BeanExpressionContext(beanFactory, null))); Object evaluateValue = resolver.evaluate(resolved, new BeanExpressionContext(beanFactory, null));
if (evaluateValue != null) {
return String.valueOf(evaluateValue);
}
return null;
} }
return value; return value;
} }
@@ -436,7 +440,7 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar, ResourceLo
} }
private boolean isClientRefreshEnabled() { private boolean isClientRefreshEnabled() {
return environment.getProperty("feign.client.refresh-enabled", Boolean.class, false); return environment.getProperty("spring.cloud.openfeign.client.refresh-enabled", Boolean.class, false);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -35,7 +35,7 @@ import org.springframework.lang.Nullable;
public class FeignContext extends NamedContextFactory<FeignClientSpecification> { public class FeignContext extends NamedContextFactory<FeignClientSpecification> {
public FeignContext() { public FeignContext() {
super(FeignClientsConfiguration.class, "feign", "feign.client.name"); super(FeignClientsConfiguration.class, "spring.cloud.openfeign", "spring.cloud.openfeign.client.name");
} }
@Nullable @Nullable
@@ -1,5 +1,5 @@
/* /*
* Copyright 2020-2020 the original author or authors. * Copyright 2020-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2016-2020 the original author or authors. * Copyright 2016-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -34,7 +34,8 @@ public class HttpClient5DisabledConditions extends AnyNestedCondition {
} }
@ConditionalOnProperty(value = "feign.httpclient.hc5.enabled", havingValue = "false", matchIfMissing = true) @ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.hc5.enabled", havingValue = "false",
matchIfMissing = true)
static class HttpClient5Disabled { static class HttpClient5Disabled {
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -0,0 +1,67 @@
/*
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import feign.MethodMetadata;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.CookieValue;
import static feign.Util.checkState;
import static feign.Util.emptyToNull;
/**
* @{link CookieValue} annotation processor.
* @author Gong Yi
*
*/
public class CookieValueParameterProcessor implements AnnotatedParameterProcessor {
private static final Class<CookieValue> ANNOTATION = CookieValue.class;
@Override
public Class<? extends Annotation> getAnnotationType() {
return ANNOTATION;
}
@Override
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
int parameterIndex = context.getParameterIndex();
MethodMetadata data = context.getMethodMetadata();
CookieValue cookie = ANNOTATION.cast(annotation);
String name = cookie.value().trim();
checkState(emptyToNull(name) != null, "Cookie.name() was empty on parameter %s", parameterIndex);
context.setParameterName(name);
String cookieExpression = data.template().headers().getOrDefault(HttpHeaders.COOKIE, Arrays.asList("")).stream()
.findFirst().orElse("");
if (cookieExpression.length() == 0) {
cookieExpression = String.format("%s={%s}", name, name);
}
else {
cookieExpression += String.format("; %s={%s}", name, name);
}
data.template().removeHeader(HttpHeaders.COOKIE);
data.template().header(HttpHeaders.COOKIE, cookieExpression);
return true;
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2019 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -23,11 +23,11 @@ import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import jakarta.annotation.PreDestroy;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.config.RequestConfig;
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -20,8 +20,7 @@ import java.io.IOException;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import javax.annotation.PreDestroy; import jakarta.annotation.PreDestroy;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
@@ -80,7 +79,7 @@ public class HttpClientFeignConfiguration {
} }
@Bean @Bean
@ConditionalOnProperty(value = "feign.compression.response.enabled", havingValue = "true") @ConditionalOnProperty(value = "spring.cloud.openfeign.compression.response.enabled", havingValue = "true")
public CloseableHttpClient customHttpClient(HttpClientConnectionManager httpClientConnectionManager, public CloseableHttpClient customHttpClient(HttpClientConnectionManager httpClientConnectionManager,
FeignHttpClientProperties httpClientProperties) { FeignHttpClientProperties httpClientProperties) {
HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement().useSystemProperties(); HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement().useSystemProperties();
@@ -89,7 +88,8 @@ public class HttpClientFeignConfiguration {
} }
@Bean @Bean
@ConditionalOnProperty(value = "feign.compression.response.enabled", havingValue = "false", matchIfMissing = true) @ConditionalOnProperty(value = "spring.cloud.openfeign.compression.response.enabled", havingValue = "false",
matchIfMissing = true)
public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory, public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory,
HttpClientConnectionManager httpClientConnectionManager, FeignHttpClientProperties httpClientProperties) { HttpClientConnectionManager httpClientConnectionManager, FeignHttpClientProperties httpClientProperties) {
this.httpClient = createClient(httpClientFactory.createBuilder(), httpClientConnectionManager, this.httpClient = createClient(httpClientFactory.createBuilder(), httpClientConnectionManager,
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,10 +16,10 @@
package org.springframework.cloud.openfeign.clientconfig; package org.springframework.cloud.openfeign.clientconfig;
import java.time.Duration;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy; import jakarta.annotation.PreDestroy;
import okhttp3.ConnectionPool; import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
@@ -48,8 +48,8 @@ public class OkHttpFeignConfiguration {
@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);
} }
@@ -57,11 +57,12 @@ public class OkHttpFeignConfiguration {
@Bean @Bean
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, ConnectionPool connectionPool, public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, ConnectionPool connectionPool,
FeignHttpClientProperties httpClientProperties) { FeignHttpClientProperties httpClientProperties) {
Boolean followRedirects = httpClientProperties.isFollowRedirects(); boolean followRedirects = httpClientProperties.isFollowRedirects();
Integer connectTimeout = httpClientProperties.getConnectionTimeout(); int connectTimeout = httpClientProperties.getConnectionTimeout();
Duration reaTimeout = httpClientProperties.getOkHttp().getReadTimeout();
this.okHttpClient = httpClientFactory.createBuilder(httpClientProperties.isDisableSslValidation()) this.okHttpClient = httpClientFactory.createBuilder(httpClientProperties.isDisableSslValidation())
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects) .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects)
.connectionPool(connectionPool).build(); .readTimeout(reaTimeout).connectionPool(connectionPool).build();
return this.okHttpClient; return this.okHttpClient;
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -39,7 +39,7 @@ import org.springframework.context.annotation.Configuration;
@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")
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -26,7 +26,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
* *
* @author Jakub Narloch * @author Jakub Narloch
*/ */
@ConfigurationProperties("feign.compression.request") @ConfigurationProperties("spring.cloud.openfeign.compression.request")
public class FeignClientEncodingProperties { public class FeignClientEncodingProperties {
/** /**
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -39,7 +39,7 @@ import org.springframework.context.annotation.Configuration;
// The OK HTTP client uses "transparent" compression. // The OK HTTP client uses "transparent" compression.
// If the content-encoding header is present it disable transparent compression // If the content-encoding header is present it disable transparent compression
@ConditionalOnMissingBean(type = "okhttp3.OkHttpClient") @ConditionalOnMissingBean(type = "okhttp3.OkHttpClient")
@ConditionalOnProperty("feign.compression.request.enabled") @ConditionalOnProperty("spring.cloud.openfeign.compression.request.enabled")
@AutoConfigureAfter(FeignAutoConfiguration.class) @AutoConfigureAfter(FeignAutoConfiguration.class)
public class FeignContentGzipEncodingAutoConfiguration { public class FeignContentGzipEncodingAutoConfiguration {
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -83,7 +83,7 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
} }
/** /**
* Returns whether the content mime types matches the configures mime types. * Returns whether the content mime types matches the configured mime types.
* @param contentTypes the content types * @param contentTypes the content types
* @return true if any specified content type matches the request content types * @return true if any specified content type matches the request content types
*/ */
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2016-2021 the original author or authors. * Copyright 2016-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2016-2021 the original author or authors. * Copyright 2016-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign.loadbalancer; package org.springframework.cloud.openfeign.loadbalancer;
import java.util.List;
import feign.Client; import feign.Client;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
@@ -25,7 +27,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties; import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory; import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Conditional;
@@ -36,19 +38,21 @@ import org.springframework.context.annotation.Configuration;
* that uses {@link Client.Default} under the hood. * that uses {@link Client.Default} under the hood.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author changjin wei(魏昌进)
* @since 2.2.0 * @since 2.2.0
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(LoadBalancerProperties.class) @EnableConfigurationProperties(LoadBalancerClientsProperties.class)
class DefaultFeignLoadBalancerConfiguration { class DefaultFeignLoadBalancerConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class) @Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(LoadBalancerClient loadBalancerClient, LoadBalancerProperties properties, public Client feignClient(LoadBalancerClient loadBalancerClient,
LoadBalancerClientFactory loadBalancerClientFactory) { LoadBalancerClientFactory loadBalancerClientFactory,
return new FeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient, properties, List<LoadBalancerFeignRequestTransformer> transformers) {
loadBalancerClientFactory); return new FeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient,
loadBalancerClientFactory, transformers);
} }
@Bean @Bean
@@ -58,10 +62,10 @@ class DefaultFeignLoadBalancerConfiguration {
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true", @ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
matchIfMissing = true) matchIfMissing = true)
public Client feignRetryClient(LoadBalancerClient loadBalancerClient, public Client feignRetryClient(LoadBalancerClient loadBalancerClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties, LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
LoadBalancerClientFactory loadBalancerClientFactory) { List<LoadBalancerFeignRequestTransformer> transformers) {
return new RetryableFeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient, return new RetryableFeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient,
loadBalancedRetryFactory, properties, loadBalancerClientFactory); loadBalancedRetryFactory, loadBalancerClientFactory, transformers);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -19,6 +19,8 @@ package org.springframework.cloud.openfeign.loadbalancer;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Set; import java.util.Set;
import feign.Client; import feign.Client;
@@ -49,6 +51,7 @@ import static org.springframework.cloud.openfeign.loadbalancer.LoadBalancerUtils
* {@link ServiceInstance} to use while resolving the request host. * {@link ServiceInstance} to use while resolving the request host.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author changjin wei(魏昌进)
* @since 2.2.0 * @since 2.2.0
*/ */
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
@@ -60,16 +63,43 @@ public class FeignBlockingLoadBalancerClient implements Client {
private final LoadBalancerClient loadBalancerClient; private final LoadBalancerClient loadBalancerClient;
private final LoadBalancerProperties properties;
private final LoadBalancerClientFactory loadBalancerClientFactory; 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, public FeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancerProperties properties, LoadBalancerClientFactory loadBalancerClientFactory) { LoadBalancerProperties properties, LoadBalancerClientFactory loadBalancerClientFactory) {
this.delegate = delegate; this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient; this.loadBalancerClient = loadBalancerClient;
this.properties = properties;
this.loadBalancerClientFactory = loadBalancerClientFactory; this.loadBalancerClientFactory = loadBalancerClientFactory;
this.transformers = Collections.emptyList();
}
/**
* @deprecated in favour of
* {@link FeignBlockingLoadBalancerClient#FeignBlockingLoadBalancerClient(Client, LoadBalancerClient, LoadBalancerClientFactory, List)}
*/
@Deprecated
public FeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancerClientFactory loadBalancerClientFactory) {
this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient;
this.loadBalancerClientFactory = loadBalancerClientFactory;
this.transformers = Collections.emptyList();
}
public FeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient;
this.loadBalancerClientFactory = loadBalancerClientFactory;
this.transformers = transformers;
} }
@Override @Override
@@ -100,7 +130,7 @@ public class FeignBlockingLoadBalancerClient implements Client {
.body(message, StandardCharsets.UTF_8).build(); .body(message, StandardCharsets.UTF_8).build();
} }
String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri).toString(); String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri).toString();
Request newRequest = buildRequest(request, reconstructedUrl); Request newRequest = buildRequest(request, reconstructedUrl, instance);
return executeWithLoadBalancerLifecycleProcessing(delegate, options, newRequest, lbRequest, lbResponse, return executeWithLoadBalancerLifecycleProcessing(delegate, options, newRequest, lbRequest, lbResponse,
supportedLifecycleProcessors); supportedLifecycleProcessors);
} }
@@ -110,12 +140,23 @@ public class FeignBlockingLoadBalancerClient implements Client {
request.charset(), request.requestTemplate()); request.charset(), request.requestTemplate());
} }
protected Request buildRequest(Request request, String reconstructedUrl, ServiceInstance instance) {
Request newRequest = buildRequest(request, reconstructedUrl);
if (transformers != null) {
for (LoadBalancerFeignRequestTransformer transformer : transformers) {
newRequest = transformer.transformRequest(newRequest, instance);
}
}
return newRequest;
}
// Visible for Sleuth instrumentation // Visible for Sleuth instrumentation
public Client getDelegate() { public Client getDelegate() {
return delegate; return delegate;
} }
private String getHint(String serviceId) { private String getHint(String serviceId) {
LoadBalancerProperties properties = loadBalancerClientFactory.getProperties(serviceId);
String defaultHint = properties.getHint().getOrDefault("default", "default"); String defaultHint = properties.getHint().getOrDefault("default", "default");
String hintPropertyValue = properties.getHint().get(serviceId); String hintPropertyValue = properties.getHint().get(serviceId);
return hintPropertyValue != null ? hintPropertyValue : defaultHint; return hintPropertyValue != null ? hintPropertyValue : defaultHint;
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign.loadbalancer; package org.springframework.cloud.openfeign.loadbalancer;
import java.util.List;
import feign.Client; import feign.Client;
import feign.hc5.ApacheHttp5Client; import feign.hc5.ApacheHttp5Client;
import org.apache.hc.client5.http.classic.HttpClient; import org.apache.hc.client5.http.classic.HttpClient;
@@ -27,7 +29,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties; import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory; import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.openfeign.clientconfig.HttpClient5FeignConfiguration; import org.springframework.cloud.openfeign.clientconfig.HttpClient5FeignConfiguration;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
@@ -40,22 +42,25 @@ import org.springframework.context.annotation.Import;
* that uses {@link ApacheHttp5Client} under the hood. * that uses {@link ApacheHttp5Client} under the hood.
* *
* @author Nguyen Ky Thanh * @author Nguyen Ky Thanh
* @author changjin wei(魏昌进)
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttp5Client.class) @ConditionalOnClass(ApacheHttp5Client.class)
@ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class }) @ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@ConditionalOnProperty(value = "feign.httpclient.hc5.enabled", havingValue = "true") @ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.hc5.enabled", havingValue = "true")
@Import(HttpClient5FeignConfiguration.class) @Import(HttpClient5FeignConfiguration.class)
@EnableConfigurationProperties(LoadBalancerProperties.class) @EnableConfigurationProperties(LoadBalancerClientsProperties.class)
class HttpClient5FeignLoadBalancerConfiguration { class HttpClient5FeignLoadBalancerConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class) @Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient5, public Client feignClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient5,
LoadBalancerProperties properties, LoadBalancerClientFactory loadBalancerClientFactory) { LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
Client delegate = new ApacheHttp5Client(httpClient5); Client delegate = new ApacheHttp5Client(httpClient5);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, properties, loadBalancerClientFactory); return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancerClientFactory,
transformers);
} }
@Bean @Bean
@@ -65,11 +70,11 @@ class HttpClient5FeignLoadBalancerConfiguration {
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true", @ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
matchIfMissing = true) matchIfMissing = true)
public Client feignRetryClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient5, public Client feignRetryClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient5,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties, LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
LoadBalancerClientFactory loadBalancerClientFactory) { List<LoadBalancerFeignRequestTransformer> transformers) {
Client delegate = new ApacheHttp5Client(httpClient5); Client delegate = new ApacheHttp5Client(httpClient5);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory, return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
properties, loadBalancerClientFactory); loadBalancerClientFactory, transformers);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign.loadbalancer; package org.springframework.cloud.openfeign.loadbalancer;
import java.util.List;
import feign.Client; import feign.Client;
import feign.httpclient.ApacheHttpClient; import feign.httpclient.ApacheHttpClient;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
@@ -27,7 +29,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties; import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory; import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.openfeign.HttpClient5DisabledConditions; import org.springframework.cloud.openfeign.HttpClient5DisabledConditions;
import org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration; import org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration;
@@ -42,24 +44,27 @@ import org.springframework.context.annotation.Import;
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh * @author Nguyen Ky Thanh
* @author changjin wei(魏昌进)
* @since 2.2.0 * @since 2.2.0
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttpClient.class) @ConditionalOnClass(ApacheHttpClient.class)
@ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class }) @ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true) @ConditionalOnProperty(value = "spring.cloud.openfeign.httpclient.enabled", matchIfMissing = true)
@Conditional(HttpClient5DisabledConditions.class) @Conditional(HttpClient5DisabledConditions.class)
@Import(HttpClientFeignConfiguration.class) @Import(HttpClientFeignConfiguration.class)
@EnableConfigurationProperties(LoadBalancerProperties.class) @EnableConfigurationProperties(LoadBalancerClientsProperties.class)
class HttpClientFeignLoadBalancerConfiguration { class HttpClientFeignLoadBalancerConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class) @Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient, public Client feignClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient,
LoadBalancerProperties properties, LoadBalancerClientFactory loadBalancerClientFactory) { LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
ApacheHttpClient delegate = new ApacheHttpClient(httpClient); ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, properties, loadBalancerClientFactory); return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancerClientFactory,
transformers);
} }
@Bean @Bean
@@ -69,11 +74,11 @@ class HttpClientFeignLoadBalancerConfiguration {
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true", @ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
matchIfMissing = true) matchIfMissing = true)
public Client feignRetryClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient, public Client feignRetryClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties, LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
LoadBalancerClientFactory loadBalancerClientFactory) { List<LoadBalancerFeignRequestTransformer> transformers) {
ApacheHttpClient delegate = new ApacheHttpClient(httpClient); ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory, return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
properties, loadBalancerClientFactory); loadBalancerClientFactory, transformers);
} }
} }
@@ -0,0 +1,47 @@
/*
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.loadbalancer;
import feign.Request;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.core.annotation.Order;
/**
* Allows applications to transform the load-balanced {@link Request} given the chosen
* {@link org.springframework.cloud.client.ServiceInstance}.
*
* @author changjin wei(魏昌进)
*/
@Order(LoadBalancerFeignRequestTransformer.DEFAULT_ORDER)
public interface LoadBalancerFeignRequestTransformer {
/**
* Order for the {@link LoadBalancerFeignRequestTransformer}.
*/
int DEFAULT_ORDER = 0;
/**
* Allows transforming load-balanced requests based on the provided
* {@link ServiceInstance}.
* @param request Original request.
* @param instance ServiceInstance returned from LoadBalancer.
* @return New request or original request
*/
Request transformRequest(Request request, ServiceInstance instance);
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -33,7 +33,7 @@ import org.springframework.cloud.client.loadbalancer.RequestData;
import org.springframework.cloud.client.loadbalancer.ResponseData; import org.springframework.cloud.client.loadbalancer.ResponseData;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode;
/** /**
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
@@ -73,7 +73,7 @@ final class LoadBalancerUtils {
static ResponseData buildResponseData(Response response) { static ResponseData buildResponseData(Response response) {
HttpHeaders responseHeaders = new HttpHeaders(); HttpHeaders responseHeaders = new HttpHeaders();
response.headers().forEach((key, value) -> responseHeaders.put(key, new ArrayList<>(value))); response.headers().forEach((key, value) -> responseHeaders.put(key, new ArrayList<>(value)));
return new ResponseData(HttpStatus.resolve(response.status()), responseHeaders, null, return new ResponseData(HttpStatusCode.valueOf(response.status()), responseHeaders, null,
buildRequestData(response.request())); buildRequestData(response.request()));
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign.loadbalancer; package org.springframework.cloud.openfeign.loadbalancer;
import java.util.List;
import feign.Client; import feign.Client;
import feign.okhttp.OkHttpClient; import feign.okhttp.OkHttpClient;
@@ -26,7 +28,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties; import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory; import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.openfeign.clientconfig.OkHttpFeignConfiguration; import org.springframework.cloud.openfeign.clientconfig.OkHttpFeignConfiguration;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
@@ -39,23 +41,26 @@ import org.springframework.context.annotation.Import;
* that uses {@link OkHttpClient} under the hood. * that uses {@link OkHttpClient} under the hood.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author changjin wei(魏昌进)
* @since 2.2.0 * @since 2.2.0
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OkHttpClient.class) @ConditionalOnClass(OkHttpClient.class)
@ConditionalOnProperty("feign.okhttp.enabled") @ConditionalOnProperty("spring.cloud.openfeign.okhttp.enabled")
@ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class }) @ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@Import(OkHttpFeignConfiguration.class) @Import(OkHttpFeignConfiguration.class)
@EnableConfigurationProperties(LoadBalancerProperties.class) @EnableConfigurationProperties(LoadBalancerClientsProperties.class)
class OkHttpFeignLoadBalancerConfiguration { class OkHttpFeignLoadBalancerConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class) @Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(okhttp3.OkHttpClient okHttpClient, LoadBalancerClient loadBalancerClient, public Client feignClient(okhttp3.OkHttpClient okHttpClient, LoadBalancerClient loadBalancerClient,
LoadBalancerProperties properties, LoadBalancerClientFactory loadBalancerClientFactory) { LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
OkHttpClient delegate = new OkHttpClient(okHttpClient); OkHttpClient delegate = new OkHttpClient(okHttpClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, properties, loadBalancerClientFactory); return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancerClientFactory,
transformers);
} }
@Bean @Bean
@@ -65,11 +70,11 @@ class OkHttpFeignLoadBalancerConfiguration {
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true", @ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
matchIfMissing = true) matchIfMissing = true)
public Client feignRetryClient(LoadBalancerClient loadBalancerClient, okhttp3.OkHttpClient okHttpClient, public Client feignRetryClient(LoadBalancerClient loadBalancerClient, okhttp3.OkHttpClient okHttpClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties, LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
LoadBalancerClientFactory loadBalancerClientFactory) { List<LoadBalancerFeignRequestTransformer> transformers) {
OkHttpClient delegate = new OkHttpClient(okHttpClient); OkHttpClient delegate = new OkHttpClient(okHttpClient);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory, return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
properties, loadBalancerClientFactory); loadBalancerClientFactory, transformers);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@ import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -65,12 +66,13 @@ import static org.springframework.cloud.openfeign.loadbalancer.LoadBalancerUtils
* load-balanced with Spring Cloud LoadBalancer. * load-balanced with Spring Cloud LoadBalancer.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author changjin wei(魏昌进)
* @since 2.2.6 * @since 2.2.6
*/ */
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
public class RetryableFeignBlockingLoadBalancerClient implements Client { public class RetryableFeignBlockingLoadBalancerClient implements Client {
private static final Log LOG = LogFactory.getLog(FeignBlockingLoadBalancerClient.class); private static final Log LOG = LogFactory.getLog(RetryableFeignBlockingLoadBalancerClient.class);
private final Client delegate; private final Client delegate;
@@ -78,18 +80,47 @@ public class RetryableFeignBlockingLoadBalancerClient implements Client {
private final LoadBalancedRetryFactory loadBalancedRetryFactory; private final LoadBalancedRetryFactory loadBalancedRetryFactory;
private final LoadBalancerProperties properties;
private final LoadBalancerClientFactory loadBalancerClientFactory; 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, public RetryableFeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties, LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties,
LoadBalancerClientFactory loadBalancerClientFactory) { LoadBalancerClientFactory loadBalancerClientFactory) {
this.delegate = delegate; this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient; this.loadBalancerClient = loadBalancerClient;
this.loadBalancedRetryFactory = loadBalancedRetryFactory; this.loadBalancedRetryFactory = loadBalancedRetryFactory;
this.properties = properties;
this.loadBalancerClientFactory = loadBalancerClientFactory; this.loadBalancerClientFactory = loadBalancerClientFactory;
this.transformers = Collections.emptyList();
}
/**
* @deprecated in favour of
* {@link RetryableFeignBlockingLoadBalancerClient#RetryableFeignBlockingLoadBalancerClient(Client, LoadBalancerClient, LoadBalancedRetryFactory, LoadBalancerClientFactory, List)}
*/
@Deprecated
public RetryableFeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory) {
this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient;
this.loadBalancedRetryFactory = loadBalancedRetryFactory;
this.loadBalancerClientFactory = loadBalancerClientFactory;
this.transformers = Collections.emptyList();
}
public RetryableFeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory,
List<LoadBalancerFeignRequestTransformer> transformers) {
this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient;
this.loadBalancedRetryFactory = loadBalancedRetryFactory;
this.loadBalancerClientFactory = loadBalancerClientFactory;
this.transformers = transformers;
} }
@Override @Override
@@ -148,7 +179,7 @@ public class RetryableFeignBlockingLoadBalancerClient implements Client {
} }
String reconstructedUrl = loadBalancerClient.reconstructURI(retrievedServiceInstance, originalUri) String reconstructedUrl = loadBalancerClient.reconstructURI(retrievedServiceInstance, originalUri)
.toString(); .toString();
feignRequest = buildRequest(request, reconstructedUrl); feignRequest = buildRequest(request, reconstructedUrl, retrievedServiceInstance);
} }
} }
org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse = new DefaultResponse( org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse = new DefaultResponse(
@@ -181,6 +212,16 @@ public class RetryableFeignBlockingLoadBalancerClient implements Client {
request.charset(), request.requestTemplate()); request.charset(), request.requestTemplate());
} }
protected Request buildRequest(Request request, String reconstructedUrl, ServiceInstance instance) {
Request newRequest = buildRequest(request, reconstructedUrl);
if (transformers != null) {
for (LoadBalancerFeignRequestTransformer transformer : transformers) {
newRequest = transformer.transformRequest(newRequest, instance);
}
}
return newRequest;
}
private RetryTemplate buildRetryTemplate(String serviceId, Request request, LoadBalancedRetryPolicy retryPolicy) { private RetryTemplate buildRetryTemplate(String serviceId, Request request, LoadBalancedRetryPolicy retryPolicy) {
RetryTemplate retryTemplate = new RetryTemplate(); RetryTemplate retryTemplate = new RetryTemplate();
BackOffPolicy backOffPolicy = this.loadBalancedRetryFactory.createBackOffPolicy(serviceId); BackOffPolicy backOffPolicy = this.loadBalancedRetryFactory.createBackOffPolicy(serviceId);
@@ -232,6 +273,7 @@ public class RetryableFeignBlockingLoadBalancerClient implements Client {
} }
private String getHint(String serviceId) { private String getHint(String serviceId) {
LoadBalancerProperties properties = loadBalancerClientFactory.getProperties(serviceId);
String defaultHint = properties.getHint().getOrDefault("default", "default"); String defaultHint = properties.getHint().getOrDefault("default", "default");
String hintPropertyValue = properties.getHint().get(serviceId); String hintPropertyValue = properties.getHint().get(serviceId);
return hintPropertyValue != null ? hintPropertyValue : defaultHint; return hintPropertyValue != null ? hintPropertyValue : defaultHint;
@@ -1,5 +1,5 @@
/* /*
* Copyright 2015-2019 the original author or authors. * Copyright 2015-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -43,6 +43,7 @@ import org.springframework.security.oauth2.common.OAuth2AccessToken;
* @author Tim Ysewyn * @author Tim Ysewyn
* @since 3.0.0 * @since 3.0.0
*/ */
@Deprecated // spring-security-oauth2 reached EOL
public class OAuth2FeignRequestInterceptor implements RequestInterceptor { public class OAuth2FeignRequestInterceptor implements RequestInterceptor {
/** /**
@@ -0,0 +1,81 @@
/*
* Copyright 2015-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.AccessTokenProvider;
import org.springframework.security.oauth2.client.token.AccessTokenProviderChain;
import org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider;
/**
* Allows to customize pre-defined {@link OAuth2FeignRequestInterceptor} using configurer
* beans of class {@link OAuth2FeignRequestInterceptorConfigurer}. Each configurer
* instance can add {@link AccessTokenProvider} new {@link ClientHttpRequestInterceptor}
* instances.
*
* @author Wojciech Mąka
* @since 3.1.1
*/
public class OAuth2FeignRequestInterceptorBuilder {
private AccessTokenProvider accessTokenProvider;
private final List<ClientHttpRequestInterceptor> accessTokenProviderInterceptors = new ArrayList<>();
public OAuth2FeignRequestInterceptorBuilder() {
accessTokenProvider = new AccessTokenProviderChain(Arrays.<AccessTokenProvider>asList(
new AuthorizationCodeAccessTokenProvider(), new ImplicitAccessTokenProvider(),
new ResourceOwnerPasswordAccessTokenProvider(), new ClientCredentialsAccessTokenProvider()));
}
public OAuth2FeignRequestInterceptorBuilder withAccessTokenProviderInterceptors(
ClientHttpRequestInterceptor... interceptors) {
accessTokenProviderInterceptors.addAll(Arrays.asList(interceptors));
return this;
}
OAuth2FeignRequestInterceptor build(OAuth2ClientContext oAuth2ClientContext,
OAuth2ProtectedResourceDetails resource) {
if (OAuth2AccessTokenSupport.class.isAssignableFrom(accessTokenProvider.getClass())) {
((OAuth2AccessTokenSupport) accessTokenProvider).setInterceptors(accessTokenProviderInterceptors);
}
final OAuth2FeignRequestInterceptor feignRequestInterceptor = new OAuth2FeignRequestInterceptor(
oAuth2ClientContext, resource);
feignRequestInterceptor.setAccessTokenProvider(accessTokenProvider);
return feignRequestInterceptor;
}
public static OAuth2FeignRequestInterceptor buildWithConfigurers(OAuth2ClientContext oAuth2ClientContext,
OAuth2ProtectedResourceDetails resource, List<OAuth2FeignRequestInterceptorConfigurer> buildConfigurers) {
final OAuth2FeignRequestInterceptorBuilder builder = new OAuth2FeignRequestInterceptorBuilder();
for (OAuth2FeignRequestInterceptorConfigurer configurer : buildConfigurers) {
configurer.customize(builder);
}
return builder.build(oAuth2ClientContext, resource);
}
}
@@ -0,0 +1,35 @@
/*
* Copyright 2015-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.security;
import org.springframework.security.oauth2.client.token.AccessTokenProvider;
/**
* Interface for configurer beans working with
* {@link OAuth2FeignRequestInterceptorBuilder} in order to provide custom interceptors
* for {@link AccessTokenProvider} managed internally by
* {@link OAuth2FeignRequestInterceptor}.
*
* @author Wojciech Mąka
* @since 3.1.1
*/
@FunctionalInterface
public interface OAuth2FeignRequestInterceptorConfigurer {
void customize(OAuth2FeignRequestInterceptorBuilder requestInterceptorBuilder);
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @since 2.2.8 * @since 2.2.8
*/ */
@ConfigurationProperties("feign.encoder") @ConfigurationProperties("spring.cloud.openfeign.encoder")
public class FeignEncoderProperties { public class FeignEncoderProperties {
/** /**
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,15 +16,19 @@
package org.springframework.cloud.openfeign.support; package org.springframework.cloud.openfeign.support;
import java.time.Duration;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import feign.okhttp.OkHttpClient;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
/** /**
* @author Ryan Baxter * @author Ryan Baxter
* @author Nguyen Ky Thanh * @author Nguyen Ky Thanh
* @author Olga Maciaszek-Sharma
*/ */
@ConfigurationProperties(prefix = "feign.httpclient") @ConfigurationProperties(prefix = "spring.cloud.openfeign.httpclient")
public class FeignHttpClientProperties { public class FeignHttpClientProperties {
/** /**
@@ -88,8 +92,13 @@ public class FeignHttpClientProperties {
*/ */
private Hc5Properties hc5 = new Hc5Properties(); private Hc5Properties hc5 = new Hc5Properties();
/**
* Additional {@link OkHttpClient}-specific properties.
*/
private OkHttp okHttp = new OkHttp();
public int getConnectionTimerRepeat() { public int getConnectionTimerRepeat() {
return this.connectionTimerRepeat; return connectionTimerRepeat;
} }
public void setConnectionTimerRepeat(int connectionTimerRepeat) { public void setConnectionTimerRepeat(int connectionTimerRepeat) {
@@ -97,7 +106,7 @@ public class FeignHttpClientProperties {
} }
public boolean isDisableSslValidation() { public boolean isDisableSslValidation() {
return this.disableSslValidation; return disableSslValidation;
} }
public void setDisableSslValidation(boolean disableSslValidation) { public void setDisableSslValidation(boolean disableSslValidation) {
@@ -105,7 +114,7 @@ public class FeignHttpClientProperties {
} }
public int getMaxConnections() { public int getMaxConnections() {
return this.maxConnections; return maxConnections;
} }
public void setMaxConnections(int maxConnections) { public void setMaxConnections(int maxConnections) {
@@ -113,7 +122,7 @@ public class FeignHttpClientProperties {
} }
public int getMaxConnectionsPerRoute() { public int getMaxConnectionsPerRoute() {
return this.maxConnectionsPerRoute; return maxConnectionsPerRoute;
} }
public void setMaxConnectionsPerRoute(int maxConnectionsPerRoute) { public void setMaxConnectionsPerRoute(int maxConnectionsPerRoute) {
@@ -121,7 +130,7 @@ public class FeignHttpClientProperties {
} }
public long getTimeToLive() { public long getTimeToLive() {
return this.timeToLive; return timeToLive;
} }
public void setTimeToLive(long timeToLive) { public void setTimeToLive(long timeToLive) {
@@ -129,7 +138,7 @@ public class FeignHttpClientProperties {
} }
public TimeUnit getTimeToLiveUnit() { public TimeUnit getTimeToLiveUnit() {
return this.timeToLiveUnit; return timeToLiveUnit;
} }
public void setTimeToLiveUnit(TimeUnit timeToLiveUnit) { public void setTimeToLiveUnit(TimeUnit timeToLiveUnit) {
@@ -137,7 +146,7 @@ public class FeignHttpClientProperties {
} }
public boolean isFollowRedirects() { public boolean isFollowRedirects() {
return this.followRedirects; return followRedirects;
} }
public void setFollowRedirects(boolean followRedirects) { public void setFollowRedirects(boolean followRedirects) {
@@ -145,7 +154,7 @@ public class FeignHttpClientProperties {
} }
public int getConnectionTimeout() { public int getConnectionTimeout() {
return this.connectionTimeout; return connectionTimeout;
} }
public void setConnectionTimeout(int connectionTimeout) { public void setConnectionTimeout(int connectionTimeout) {
@@ -160,6 +169,14 @@ public class FeignHttpClientProperties {
this.hc5 = hc5; this.hc5 = hc5;
} }
public OkHttp getOkHttp() {
return okHttp;
}
public void setOkHttp(OkHttp okHttp) {
this.okHttp = okHttp;
}
public static class Hc5Properties { public static class Hc5Properties {
/** /**
@@ -203,7 +220,7 @@ public class FeignHttpClientProperties {
private TimeUnit socketTimeoutUnit = DEFAULT_SOCKET_TIMEOUT_UNIT; private TimeUnit socketTimeoutUnit = DEFAULT_SOCKET_TIMEOUT_UNIT;
public PoolConcurrencyPolicy getPoolConcurrencyPolicy() { public PoolConcurrencyPolicy getPoolConcurrencyPolicy() {
return this.poolConcurrencyPolicy; return poolConcurrencyPolicy;
} }
public void setPoolConcurrencyPolicy(PoolConcurrencyPolicy poolConcurrencyPolicy) { public void setPoolConcurrencyPolicy(PoolConcurrencyPolicy poolConcurrencyPolicy) {
@@ -272,4 +289,24 @@ public class FeignHttpClientProperties {
} }
/**
* {@link OkHttpClient}-specific properties.
*/
public static class OkHttp {
/**
* {@link OkHttpClient} read timeout; defaults to 60 seconds.
*/
private Duration readTimeout = Duration.ofSeconds(60);
public Duration getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
}
}
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2016-2021 the original author or authors. * Copyright 2016-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -22,6 +22,7 @@ import java.util.function.Function;
import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.Module;
@@ -38,6 +39,8 @@ import org.springframework.data.domain.Sort;
* *
* @author Pascal Büttiker * @author Pascal Büttiker
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Pedro Mendes
* @author Nikita Konev
*/ */
public class PageJacksonModule extends Module { public class PageJacksonModule extends Module {
@@ -57,6 +60,7 @@ public class PageJacksonModule extends Module {
} }
@JsonDeserialize(as = SimplePageImpl.class) @JsonDeserialize(as = SimplePageImpl.class)
@JsonIgnoreProperties(ignoreUnknown = true)
private interface PageMixIn { private interface PageMixIn {
} }
@@ -69,6 +73,7 @@ public class PageJacksonModule extends Module {
@JsonProperty("size") int size, @JsonProperty("totalElements") @JsonAlias({ "total-elements", @JsonProperty("size") int size, @JsonProperty("totalElements") @JsonAlias({ "total-elements",
"total_elements", "totalelements", "TotalElements" }) long totalElements, "total_elements", "totalelements", "TotalElements" }) long totalElements,
@JsonProperty("sort") Sort sort) { @JsonProperty("sort") Sort sort) {
if (size > 0) {
PageRequest pageRequest; PageRequest pageRequest;
if (sort != null) { if (sort != null) {
pageRequest = PageRequest.of(number, size, sort); pageRequest = PageRequest.of(number, size, sort);
@@ -77,7 +82,10 @@ public class PageJacksonModule extends Module {
pageRequest = PageRequest.of(number, size); pageRequest = PageRequest.of(number, size);
} }
delegate = new PageImpl<>(content, pageRequest, totalElements); delegate = new PageImpl<>(content, pageRequest, totalElements);
}
else {
delegate = new PageImpl<>(content);
}
} }
@JsonProperty @JsonProperty
@@ -176,6 +184,33 @@ public class PageJacksonModule extends Module {
return delegate.iterator(); return delegate.iterator();
} }
@JsonIgnore
@Override
public Pageable getPageable() {
return delegate.getPageable();
}
@JsonIgnore
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public boolean equals(Object obj) {
return delegate.equals(obj);
}
@Override
public String toString() {
return delegate.toString();
}
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -247,7 +247,7 @@ public class SpringEncoder implements Encoder {
return Objects.equals(APPLICATION_FORM_URLENCODED, requestContentType); return Objects.equals(APPLICATION_FORM_URLENCODED, requestContentType);
} }
private boolean binaryContentType(FeignOutputMessage outputMessage) { protected boolean binaryContentType(FeignOutputMessage outputMessage) {
MediaType contentType = outputMessage.getHeaders().getContentType(); MediaType contentType = outputMessage.getHeaders().getContentType();
return contentType == null || Stream return contentType == null || Stream
.of(MediaType.APPLICATION_CBOR, MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_PDF, .of(MediaType.APPLICATION_CBOR, MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_PDF,
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -35,9 +35,12 @@ import feign.Feign;
import feign.MethodMetadata; import feign.MethodMetadata;
import feign.Param; import feign.Param;
import feign.Request; import feign.Request;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor; import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.cloud.openfeign.CollectionFormat; import org.springframework.cloud.openfeign.CollectionFormat;
import org.springframework.cloud.openfeign.annotation.CookieValueParameterProcessor;
import org.springframework.cloud.openfeign.annotation.MatrixVariableParameterProcessor; import org.springframework.cloud.openfeign.annotation.MatrixVariableParameterProcessor;
import org.springframework.cloud.openfeign.annotation.PathVariableParameterProcessor; import org.springframework.cloud.openfeign.annotation.PathVariableParameterProcessor;
import org.springframework.cloud.openfeign.annotation.QueryMapParameterProcessor; import org.springframework.cloud.openfeign.annotation.QueryMapParameterProcessor;
@@ -79,9 +82,12 @@ import static org.springframework.core.annotation.AnnotatedElementUtils.findMerg
* @author Artyom Romanenko * @author Artyom Romanenko
* @author Darren Foong * @author Darren Foong
* @author Ram Anaswara * @author Ram Anaswara
* @author Sam Kruglov
*/ */
public class SpringMvcContract extends Contract.BaseContract implements ResourceLoaderAware { public class SpringMvcContract extends Contract.BaseContract implements ResourceLoaderAware {
private static final Log LOG = LogFactory.getLog(SpringMvcContract.class);
private static final String ACCEPT = "Accept"; private static final String ACCEPT = "Accept";
private static final String CONTENT_TYPE = "Content-Type"; private static final String CONTENT_TYPE = "Content-Type";
@@ -169,47 +175,22 @@ public class SpringMvcContract extends Contract.BaseContract implements Resource
@Override @Override
protected void processAnnotationOnClass(MethodMetadata data, Class<?> clz) { protected void processAnnotationOnClass(MethodMetadata data, Class<?> clz) {
if (clz.getInterfaces().length == 0) {
RequestMapping classAnnotation = findMergedAnnotation(clz, RequestMapping.class); RequestMapping classAnnotation = findMergedAnnotation(clz, RequestMapping.class);
if (classAnnotation != null) { if (classAnnotation != null) {
// Prepend path from class annotation if specified LOG.error("Cannot process class: " + clz.getName()
if (classAnnotation.value().length > 0) { + ". @RequestMapping annotation is not allowed on @FeignClient interfaces.");
String pathValue = emptyToNull(classAnnotation.value()[0]); throw new IllegalArgumentException("@RequestMapping annotation not allowed on @FeignClient interfaces");
pathValue = resolve(pathValue);
if (!pathValue.startsWith("/")) {
pathValue = "/" + pathValue;
}
data.template().uri(pathValue);
if (data.template().decodeSlash() != decodeSlash) {
data.template().decodeSlash(decodeSlash);
}
}
} }
CollectionFormat collectionFormat = findMergedAnnotation(clz, CollectionFormat.class);
if (collectionFormat != null) {
data.template().collectionFormat(collectionFormat.value());
} }
} }
@Override @Override
public MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method method) { public MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method method) {
processedMethods.put(Feign.configKey(targetType, method), method); processedMethods.put(Feign.configKey(targetType, method), method);
MethodMetadata md = super.parseAndValidateMetadata(targetType, method); return super.parseAndValidateMetadata(targetType, method);
RequestMapping classAnnotation = findMergedAnnotation(targetType, RequestMapping.class);
if (classAnnotation != null) {
// produces - use from class annotation only if method has not specified this
if (!md.template().headers().containsKey(ACCEPT)) {
parseProduces(md, method, classAnnotation);
}
// consumes -- use from class annotation only if method has not specified this
if (!md.template().headers().containsKey(CONTENT_TYPE)) {
parseConsumes(md, method, classAnnotation);
}
// headers -- class annotation is inherited to methods, always write these if
// present
parseHeaders(md, method, classAnnotation);
}
return md;
} }
@Override @Override
@@ -360,6 +341,7 @@ public class SpringMvcContract extends Contract.BaseContract implements Resource
annotatedArgumentResolvers.add(new RequestHeaderParameterProcessor()); annotatedArgumentResolvers.add(new RequestHeaderParameterProcessor());
annotatedArgumentResolvers.add(new QueryMapParameterProcessor()); annotatedArgumentResolvers.add(new QueryMapParameterProcessor());
annotatedArgumentResolvers.add(new RequestPartParameterProcessor()); annotatedArgumentResolvers.add(new RequestPartParameterProcessor());
annotatedArgumentResolvers.add(new CookieValueParameterProcessor());
return annotatedArgumentResolvers; return annotatedArgumentResolvers;
} }
@@ -3,64 +3,82 @@
], ],
"properties": [ "properties": [
{ {
"name": "feign.autoconfiguration.jackson.enabled", "name": "spring.cloud.openfeign.autoconfiguration.jackson.enabled",
"type": "java.lang.Boolean", "type": "java.lang.Boolean",
"description": "If true, PageJacksonModule and SortJacksonModule bean will be provided for Jackson page decoding.", "description": "If true, PageJacksonModule and SortJacksonModule bean will be provided for Jackson page decoding.",
"defaultValue": "false" "defaultValue": "false"
}, },
{ {
"name": "feign.circuitbreaker.enabled", "name": "spring.cloud.openfeign.circuitbreaker.enabled",
"type": "java.lang.Boolean", "type": "java.lang.Boolean",
"description": "If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker.", "description": "If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker.",
"defaultValue": "false" "defaultValue": "false"
}, },
{ {
"name": "feign.circuitbreaker.group.enabled", "name": "spring.cloud.openfeign.circuitbreaker.group.enabled",
"type": "java.lang.Boolean", "type": "java.lang.Boolean",
"description": "If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker with with group.", "description": "If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker with with group.",
"defaultValue": "false" "defaultValue": "false"
}, },
{ {
"name": "feign.httpclient.enabled", "name": "spring.cloud.openfeign.circuitbreaker.alphanumeric-ids.enabled",
"type": "java.lang.Boolean",
"description": "If true, Circuit Breaker ids will only contain alphanumeric characters to allow for configuration via configuration properties.",
"defaultValue": "false"
},
{
"name": "spring.cloud.openfeign.httpclient.enabled",
"type": "java.lang.Boolean", "type": "java.lang.Boolean",
"description": "Enables the use of the Apache HTTP Client by Feign.", "description": "Enables the use of the Apache HTTP Client by Feign.",
"defaultValue": "true" "defaultValue": "true"
}, },
{ {
"name": "feign.httpclient.hc5.enabled", "name": "spring.cloud.openfeign.httpclient.hc5.enabled",
"type": "java.lang.Boolean", "type": "java.lang.Boolean",
"description": "Enables the use of the Apache HTTP Client 5 by Feign.", "description": "Enables the use of the Apache HTTP Client 5 by Feign.",
"defaultValue": "false" "defaultValue": "false"
}, },
{ {
"name": "feign.okhttp.enabled", "name": "spring.cloud.openfeign.okhttp.enabled",
"type": "java.lang.Boolean", "type": "java.lang.Boolean",
"description": "Enables the use of the OK HTTP Client by Feign.", "description": "Enables the use of the OK HTTP Client by Feign.",
"defaultValue": "false" "defaultValue": "false"
}, },
{ {
"name": "feign.compression.response.enabled", "name": "spring.cloud.openfeign.compression.response.enabled",
"type": "java.lang.Boolean", "type": "java.lang.Boolean",
"description": "Enables the response from Feign to be compressed.", "description": "Enables the response from Feign to be compressed.",
"defaultValue": "false" "defaultValue": "false"
}, },
{ {
"name": "feign.compression.request.enabled", "name": "spring.cloud.openfeign.compression.request.enabled",
"type": "java.lang.Boolean", "type": "java.lang.Boolean",
"description": "Enables the request sent by Feign to be compressed.", "description": "Enables the request sent by Feign to be compressed.",
"defaultValue": "false" "defaultValue": "false"
}, },
{ {
"name": "feign.metrics.enabled", "name": "spring.cloud.openfeign.metrics.enabled",
"type": "java.lang.Boolean", "type": "java.lang.Boolean",
"description": "Enables metrics capability for Feign.", "description": "Enables metrics capability for Feign.",
"defaultValue": "true" "defaultValue": "true"
}, },
{ {
"name": "feign.client.refresh-enabled", "name": "spring.cloud.openfeign.client.refresh-enabled",
"type": "java.lang.Boolean", "type": "java.lang.Boolean",
"description": "Enables options value refresh capability for Feign.", "description": "Enables options value refresh capability for Feign.",
"defaultValue": "false" "defaultValue": "false"
},
{
"name": "spring.cloud.openfeign.oauth2.enabled",
"type": "java.lang.Boolean",
"description": "Enables feign interceptor for managing oauth2 access token.",
"defaultValue": "false"
},
{
"name": "spring.cloud.openfeign.oauth2.load-balanced",
"type": "java.lang.Boolean",
"description": "Enables load balancing for oauth2 access token provider.",
"defaultValue": "false"
} }
] ]
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -17,8 +17,7 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import feign.codec.Encoder; import feign.codec.Encoder;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -26,22 +25,19 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.openfeign.support.PageableSpringEncoder; import org.springframework.cloud.openfeign.support.PageableSpringEncoder;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
*/ */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = EnableFeignClientsSpringDataTests.PlainConfiguration.class) @SpringBootTest(classes = EnableFeignClientsSpringDataTests.PlainConfiguration.class)
@DirtiesContext @DirtiesContext
public class EnableFeignClientsSpringDataTests { class EnableFeignClientsSpringDataTests {
@Autowired @Autowired
private FeignContext feignContext; private FeignContext feignContext;
@Test @Test
public void encoderDefaultCorrect() { void encoderDefaultCorrect() {
PageableSpringEncoder.class.cast(this.feignContext.getInstance("foo", Encoder.class)); PageableSpringEncoder.class.cast(this.feignContext.getInstance("foo", Encoder.class));
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -23,17 +23,15 @@ import feign.codec.Decoder;
import feign.codec.Encoder; import feign.codec.Encoder;
import feign.optionals.OptionalDecoder; import feign.optionals.OptionalDecoder;
import feign.slf4j.Slf4jLogger; import feign.slf4j.Slf4jLogger;
import org.junit.After; import org.junit.jupiter.api.AfterEach;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.WebApplicationType; import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.builder.SpringApplicationBuilder;
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.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ClassPathExclusions;
import org.springframework.cloud.test.ModifiedClassPathRunner;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
@@ -41,48 +39,47 @@ import org.springframework.context.annotation.Import;
/** /**
* @author Spencer Gibb * @author Spencer Gibb
*/ */
@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions({ "spring-data-commons-*.jar" }) @ClassPathExclusions({ "spring-data-commons-*.jar" })
public class EnableFeignClientsTests { class EnableFeignClientsTests {
private ConfigurableApplicationContext context; private ConfigurableApplicationContext context;
@Before @BeforeEach
public void setUp() { void setUp() {
context = new SpringApplicationBuilder().web(WebApplicationType.NONE) context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties("debug=true", "feign.httpclient.enabled=false") .properties("debug=true", "spring.cloud.openfeign.httpclient.enabled=false")
.sources(EnableFeignClientsTests.PlainConfiguration.class).run(); .sources(EnableFeignClientsTests.PlainConfiguration.class).run();
} }
@After @AfterEach
public void tearDown() { void tearDown() {
if (context != null) { if (context != null) {
context.close(); context.close();
} }
} }
@Test @Test
public void decoderDefaultCorrect() { void decoderDefaultCorrect() {
OptionalDecoder.class.cast(this.context.getBeansOfType(Decoder.class).get(0)); OptionalDecoder.class.cast(this.context.getBeansOfType(Decoder.class).get(0));
} }
@Test @Test
public void encoderDefaultCorrect() { void encoderDefaultCorrect() {
SpringEncoder.class.cast(this.context.getBeansOfType(Encoder.class).get(0)); SpringEncoder.class.cast(this.context.getBeansOfType(Encoder.class).get(0));
} }
@Test @Test
public void loggerDefaultCorrect() { void loggerDefaultCorrect() {
Slf4jLogger.class.cast(this.context.getBeansOfType(Logger.class).get(0)); Slf4jLogger.class.cast(this.context.getBeansOfType(Logger.class).get(0));
} }
@Test @Test
public void contractDefaultCorrect() { void contractDefaultCorrect() {
SpringMvcContract.class.cast(this.context.getBeansOfType(Contract.class).get(0)); SpringMvcContract.class.cast(this.context.getBeansOfType(Contract.class).get(0));
} }
@Test @Test
public void builderDefaultCorrect() { void builderDefaultCorrect() {
Feign.Builder.class.cast(this.context.getBeansOfType(Feign.Builder.class).get(0)); Feign.Builder.class.cast(this.context.getBeansOfType(Feign.Builder.class).get(0));
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -23,10 +23,19 @@ import org.assertj.core.api.Condition;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory; import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.openfeign.FeignAutoConfiguration.CircuitBreakerPresentFeignTargeterConfiguration.DefaultCircuitBreakerNameResolver; import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.cloud.openfeign.FeignAutoConfiguration.CircuitBreakerPresentFeignTargeterConfiguration.AlphanumericCircuitBreakerNameResolver;
import org.springframework.cloud.openfeign.security.MockOAuth2ClientContext;
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptor;
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptorBuilder;
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptorConfigurer;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@@ -36,35 +45,36 @@ import static org.mockito.Mockito.mock;
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
* @author Andrii Bohutskyi * @author Andrii Bohutskyi
* @author Kwangyong Kim * @author Kwangyong Kim
* @author Wojciech Mąka
*/ */
class FeignAutoConfigurationTests { class FeignAutoConfigurationTests {
private final ApplicationContextRunner runner = new ApplicationContextRunner() private final ApplicationContextRunner runner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(FeignAutoConfiguration.class)) .withConfiguration(AutoConfigurations.of(FeignAutoConfiguration.class))
.withPropertyValues("feign.httpclient.enabled=false"); .withPropertyValues("spring.cloud.openfeign.httpclient.enabled=false");
@Test @Test
void shouldInstantiateDefaultTargeterWhenFeignCircuitBreakerIsDisabled() { void shouldInstantiateDefaultTargeterWhenFeignCircuitBreakerIsDisabled() {
runner.withPropertyValues("feign.circuitbreaker.enabled=false") runner.withPropertyValues("spring.cloud.openfeign.circuitbreaker.enabled=false")
.run(ctx -> assertOnlyOneTargeterPresent(ctx, DefaultTargeter.class)); .run(ctx -> assertOnlyOneTargeterPresent(ctx, DefaultTargeter.class));
} }
@Test @Test
void shouldInstantiateFeignCircuitBreakerTargeterWhenEnabled() { void shouldInstantiateFeignCircuitBreakerTargeterWhenEnabled() {
runner.withBean(CircuitBreakerFactory.class, () -> mock(CircuitBreakerFactory.class)) runner.withBean(CircuitBreakerFactory.class, () -> mock(CircuitBreakerFactory.class))
.withPropertyValues("feign.circuitbreaker.enabled=true").run(ctx -> { .withPropertyValues("spring.cloud.openfeign.circuitbreaker.enabled=true").run(ctx -> {
assertOnlyOneTargeterPresent(ctx, FeignCircuitBreakerTargeter.class); assertOnlyOneTargeterPresent(ctx, FeignCircuitBreakerTargeter.class);
assertThatFeignCircuitBreakerTargeterHasGroupEnabledPropertyWithValue(ctx, false); assertThatFeignCircuitBreakerTargeterHasGroupEnabledPropertyWithValue(ctx, false);
assertThatFeignCircuitBreakerTargeterHasSameCircuitBreakerNameResolver(ctx, assertThatFeignCircuitBreakerTargeterHasSameCircuitBreakerNameResolver(ctx,
DefaultCircuitBreakerNameResolver.class); AlphanumericCircuitBreakerNameResolver.class);
}); });
} }
@Test @Test
void shouldInstantiateFeignCircuitBreakerTargeterWithEnabledGroup() { void shouldInstantiateFeignCircuitBreakerTargeterWithEnabledGroup() {
runner.withBean(CircuitBreakerFactory.class, () -> mock(CircuitBreakerFactory.class)) runner.withBean(CircuitBreakerFactory.class, () -> mock(CircuitBreakerFactory.class))
.withPropertyValues("feign.circuitbreaker.enabled=true") .withPropertyValues("spring.cloud.openfeign.circuitbreaker.enabled=true")
.withPropertyValues("feign.circuitbreaker.group.enabled=true").run(ctx -> { .withPropertyValues("spring.cloud.openfeign.circuitbreaker.group.enabled=true").run(ctx -> {
assertOnlyOneTargeterPresent(ctx, FeignCircuitBreakerTargeter.class); assertOnlyOneTargeterPresent(ctx, FeignCircuitBreakerTargeter.class);
assertThatFeignCircuitBreakerTargeterHasGroupEnabledPropertyWithValue(ctx, true); assertThatFeignCircuitBreakerTargeterHasGroupEnabledPropertyWithValue(ctx, true);
}); });
@@ -74,13 +84,74 @@ class FeignAutoConfigurationTests {
void shouldInstantiateFeignCircuitBreakerTargeterWhenEnabledWithCustomCircuitBreakerNameResolver() { void shouldInstantiateFeignCircuitBreakerTargeterWhenEnabledWithCustomCircuitBreakerNameResolver() {
runner.withBean(CircuitBreakerFactory.class, () -> mock(CircuitBreakerFactory.class)) runner.withBean(CircuitBreakerFactory.class, () -> mock(CircuitBreakerFactory.class))
.withBean(CircuitBreakerNameResolver.class, CustomCircuitBreakerNameResolver::new) .withBean(CircuitBreakerNameResolver.class, CustomCircuitBreakerNameResolver::new)
.withPropertyValues("feign.circuitbreaker.enabled=true").run(ctx -> { .withPropertyValues("spring.cloud.openfeign.circuitbreaker.enabled=true").run(ctx -> {
assertOnlyOneTargeterPresent(ctx, FeignCircuitBreakerTargeter.class); assertOnlyOneTargeterPresent(ctx, FeignCircuitBreakerTargeter.class);
assertThatFeignCircuitBreakerTargeterHasSameCircuitBreakerNameResolver(ctx, assertThatFeignCircuitBreakerTargeterHasSameCircuitBreakerNameResolver(ctx,
CustomCircuitBreakerNameResolver.class); CustomCircuitBreakerNameResolver.class);
}); });
} }
@Test
void shouldInstantiateFeignOAuth2FeignRequestInterceptorWithoutInterceptors() {
runner.withPropertyValues("spring.cloud.openfeign.oauth2.enabled=true")
.withBean(MockOAuth2ClientContext.class, "token").withBean(BaseOAuth2ProtectedResourceDetails.class)
.withBean(LoadBalancerInterceptor.class, () -> mock(LoadBalancerInterceptor.class)).run(ctx -> {
assertOauth2FeignRequestInterceptorExists(ctx);
assertAccessTokenProviderInterceptorNotExists(ctx, LoadBalancerInterceptor.class);
});
}
@Test
void shouldInstantiateFeignOAuth2FeignRequestInterceptorWithLoadBalancedInterceptor() {
runner.withPropertyValues("spring.cloud.openfeign.oauth2.enabled=true",
"spring.cloud.openfeign.oauth2.load-balanced=true").withBean(MockOAuth2ClientContext.class, "token")
.withBean(BaseOAuth2ProtectedResourceDetails.class)
.withBean(LoadBalancerInterceptor.class, () -> mock(LoadBalancerInterceptor.class)).run(ctx -> {
assertOauth2FeignRequestInterceptorExists(ctx);
assertAccessTokenProviderInterceptorExists(ctx, LoadBalancerInterceptor.class);
});
}
@Test
void shouldInstantiateFeignOAuth2FeignRequestInterceptorWithoutLoadBalancedInterceptorIfNoBeanPresent() {
runner.withPropertyValues("spring.cloud.openfeign.oauth2.enabled=true",
"spring.cloud.openfeign.oauth2.load-balanced=true").withBean(MockOAuth2ClientContext.class, "token")
.withBean(BaseOAuth2ProtectedResourceDetails.class).run(ctx -> {
assertOauth2FeignRequestInterceptorExists(ctx);
assertAccessTokenProviderInterceptorNotExists(ctx, LoadBalancerInterceptor.class);
});
}
@Test
void shouldInstantiateFeignOAuth2FeignRequestInterceptorWithCustomAccessTokenProviderInterceptor() {
runner.withPropertyValues("spring.cloud.openfeign.oauth2.enabled=true")
.withBean(MockOAuth2ClientContext.class, "token").withBean(BaseOAuth2ProtectedResourceDetails.class)
.withBean(CustomOAuth2FeignRequestInterceptorConfigurer.class).run(ctx -> {
assertOauth2FeignRequestInterceptorExists(ctx);
assertAccessTokenProviderInterceptorExists(ctx, BasicAuthenticationInterceptor.class);
});
}
private void assertOauth2FeignRequestInterceptorExists(ConfigurableApplicationContext ctx) {
AssertableApplicationContext context = AssertableApplicationContext.get(() -> ctx);
assertThat(context).hasSingleBean(OAuth2FeignRequestInterceptor.class);
}
private void assertAccessTokenProviderInterceptorExists(ConfigurableApplicationContext ctx,
Class<? extends ClientHttpRequestInterceptor> clazz) {
AssertableApplicationContext context = AssertableApplicationContext.get(() -> ctx);
assertThat(context).getBean(OAuth2FeignRequestInterceptor.class).extracting("accessTokenProvider")
.extracting("interceptors").asList().first().isInstanceOf(clazz);
}
private void assertAccessTokenProviderInterceptorNotExists(ConfigurableApplicationContext ctx,
Class<? extends ClientHttpRequestInterceptor> clazz) {
AssertableApplicationContext context = AssertableApplicationContext.get(() -> ctx);
assertThat(context).getBean(OAuth2FeignRequestInterceptor.class).extracting("accessTokenProvider")
.extracting("interceptors").asList().filteredOn(obj -> clazz.isAssignableFrom(obj.getClass()))
.isEmpty();
}
private void assertOnlyOneTargeterPresent(ConfigurableApplicationContext ctx, Class<?> beanClass) { private void assertOnlyOneTargeterPresent(ConfigurableApplicationContext ctx, Class<?> beanClass) {
assertThat(ctx.getBeansOfType(Targeter.class)).hasSize(1).hasValueSatisfying(new Condition<>( assertThat(ctx.getBeansOfType(Targeter.class)).hasSize(1).hasValueSatisfying(new Condition<>(
beanClass::isInstance, String.format("Targeter should be an instance of %s", beanClass))); beanClass::isInstance, String.format("Targeter should be an instance of %s", beanClass)));
@@ -108,4 +179,14 @@ class FeignAutoConfigurationTests {
} }
static class CustomOAuth2FeignRequestInterceptorConfigurer implements OAuth2FeignRequestInterceptorConfigurer {
@Override
public void customize(OAuth2FeignRequestInterceptorBuilder requestInterceptorBuilder) {
requestInterceptorBuilder
.withAccessTokenProviderInterceptors(new BasicAuthenticationInterceptor("username", "password"));
}
}
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2020 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -17,35 +17,56 @@
package org.springframework.cloud.openfeign; package org.springframework.cloud.openfeign;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.stream.Stream;
import feign.Client;
import feign.Feign; import feign.Feign;
import feign.Logger; import feign.Logger;
import org.junit.Test; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
/** /**
* @author Matt King * @author Matt King
* @author Sam Kruglov * @author Sam Kruglov
* @author Felix Dittrich
* @author Olga Maciaszek-Sharma
*/ */
public class FeignBuilderCustomizerTests { class FeignBuilderCustomizerTests {
private static final Targeter targeterSpy = spy(DefaultTargeter.class);
private static final Client defaultClient = mock(Client.class);
@Test @Test
public void testBuilderCustomizer() { void testBuilderCustomizer() {
ArgumentCaptor<Feign.Builder> feignBuilderCaptor = ArgumentCaptor.forClass(Feign.Builder.class);
doCallRealMethod().when(targeterSpy).target(any(), feignBuilderCaptor.capture(), any(), any());
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
FeignBuilderCustomizerTests.SampleConfiguration2.class); FeignBuilderCustomizerTests.SampleConfiguration2.class);
FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class); FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class);
FeignContext feignContext = context.getBean(FeignContext.class); clientFactoryBean.getTarget();
Feign.Builder builder = clientFactoryBean.feign(feignContext); Assertions.assertNotNull(feignBuilderCaptor.getValue());
Feign.Builder builder = feignBuilderCaptor.getValue();
assertFeignBuilderField(builder, "logLevel", Logger.Level.HEADERS); assertFeignBuilderField(builder, "logLevel", Logger.Level.HEADERS);
assertFeignBuilderField(builder, "decode404", true); assertFeignBuilderField(builder, "decode404", true);
@@ -61,14 +82,18 @@ public class FeignBuilderCustomizerTests {
} }
@Test @Test
public void testBuildCustomizerOrdered() { void testBuildCustomizerOrdered() {
ArgumentCaptor<Feign.Builder> feignBuilderCaptor = ArgumentCaptor.forClass(Feign.Builder.class);
doCallRealMethod().when(targeterSpy).target(any(), feignBuilderCaptor.capture(), any(), any());
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
FeignBuilderCustomizerTests.SampleConfiguration3.class); FeignBuilderCustomizerTests.SampleConfiguration3.class);
FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class); FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class);
FeignContext feignContext = context.getBean(FeignContext.class); clientFactoryBean.getTarget();
Feign.Builder builder = clientFactoryBean.feign(feignContext); Assertions.assertNotNull(feignBuilderCaptor.getValue());
Feign.Builder builder = feignBuilderCaptor.getValue();
assertFeignBuilderField(builder, "logLevel", Logger.Level.FULL); assertFeignBuilderField(builder, "logLevel", Logger.Level.FULL);
assertFeignBuilderField(builder, "decode404", true); assertFeignBuilderField(builder, "decode404", true);
@@ -76,16 +101,20 @@ public class FeignBuilderCustomizerTests {
} }
@Test @Test
public void testBuildCustomizerOrderedWithAdditional() { void testBuildCustomizerOrderedWithAdditional() {
ArgumentCaptor<Feign.Builder> feignBuilderCaptor = ArgumentCaptor.forClass(Feign.Builder.class);
doCallRealMethod().when(targeterSpy).target(any(), feignBuilderCaptor.capture(), any(), any());
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
FeignBuilderCustomizerTests.SampleConfiguration3.class); FeignBuilderCustomizerTests.SampleConfiguration3.class);
FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class); FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class);
clientFactoryBean.addCustomizer(builder -> builder.logLevel(Logger.Level.BASIC)); clientFactoryBean.addCustomizer(builder -> builder.logLevel(Logger.Level.BASIC));
clientFactoryBean.addCustomizer(Feign.Builder::doNotCloseAfterDecode); clientFactoryBean.addCustomizer(Feign.Builder::doNotCloseAfterDecode);
FeignContext feignContext = context.getBean(FeignContext.class); clientFactoryBean.getTarget();
Feign.Builder builder = clientFactoryBean.feign(feignContext); Assertions.assertNotNull(feignBuilderCaptor.getValue());
Feign.Builder builder = feignBuilderCaptor.getValue();
assertFeignBuilderField(builder, "logLevel", Logger.Level.BASIC); assertFeignBuilderField(builder, "logLevel", Logger.Level.BASIC);
assertFeignBuilderField(builder, "decode404", true); assertFeignBuilderField(builder, "decode404", true);
assertFeignBuilderField(builder, "closeAfterDecode", false); assertFeignBuilderField(builder, "closeAfterDecode", false);
@@ -93,16 +122,41 @@ public class FeignBuilderCustomizerTests {
context.close(); context.close();
} }
private static FeignClientFactoryBean defaultFeignClientFactoryBean() { @ParameterizedTest(name = "should use custom HttpClient with config: {0}")
@MethodSource("testConfiguration")
void testBuildCustomizerWithCustomHttpClient(Class configClass) {
ArgumentCaptor<Feign.Builder> feignBuilderCaptor = ArgumentCaptor.forClass(Feign.Builder.class);
doCallRealMethod().when(targeterSpy).target(any(), feignBuilderCaptor.capture(), any(), any());
Client customClientMock = mock(Client.class);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClass);
FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class);
clientFactoryBean.addCustomizer(builder -> builder.client(customClientMock));
clientFactoryBean.getTarget();
Assertions.assertNotNull(feignBuilderCaptor.getValue());
Feign.Builder builder = feignBuilderCaptor.getValue();
assertFeignBuilderField(builder, "client", customClientMock);
context.close();
}
private static FeignClientFactoryBean defaultFeignClientFactoryBean(String url) {
FeignClientFactoryBean feignClientFactoryBean = new FeignClientFactoryBean(); FeignClientFactoryBean feignClientFactoryBean = new FeignClientFactoryBean();
feignClientFactoryBean.setContextId("test"); feignClientFactoryBean.setContextId("test");
feignClientFactoryBean.setName("test"); feignClientFactoryBean.setName("test");
feignClientFactoryBean.setType(FeignClientFactoryTests.TestType.class); feignClientFactoryBean.setType(FeignClientFactoryTests.TestType.class);
feignClientFactoryBean.setPath(""); feignClientFactoryBean.setPath("");
feignClientFactoryBean.setUrl("http://some.absolute.url"); if (url != null) {
feignClientFactoryBean.setUrl(url);
}
return feignClientFactoryBean; return feignClientFactoryBean;
} }
private static Stream<Class> testConfiguration() {
return Stream.of(SampleConfiguration3.class, LoadBalancedSampleConfiguration.class);
}
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@Import(FeignClientsConfiguration.class) @Import(FeignClientsConfiguration.class)
protected static class SampleConfiguration2 { protected static class SampleConfiguration2 {
@@ -129,7 +183,12 @@ public class FeignBuilderCustomizerTests {
@Bean @Bean
FeignClientFactoryBean feignClientFactoryBean() { FeignClientFactoryBean feignClientFactoryBean() {
return defaultFeignClientFactoryBean(); return defaultFeignClientFactoryBean("http://some.absolute.url");
}
@Bean
Targeter targeter() {
return targeterSpy;
} }
} }
@@ -167,7 +226,29 @@ public class FeignBuilderCustomizerTests {
@Bean @Bean
FeignClientFactoryBean feignClientFactoryBean() { FeignClientFactoryBean feignClientFactoryBean() {
return defaultFeignClientFactoryBean(); return defaultFeignClientFactoryBean("http://some.absolute.url");
}
@Bean
Targeter targeter() {
return targeterSpy;
}
@Bean
Client client() {
return defaultClient;
}
}
@Configuration(proxyBeanMethods = false)
@Import(SampleConfiguration3.class)
protected static class LoadBalancedSampleConfiguration {
@Primary
@Bean
FeignClientFactoryBean feignClientFactoryBean() {
return defaultFeignClientFactoryBean(null);
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2021 the original author or authors. * Copyright 2013-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -25,11 +25,8 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import feign.Feign; import feign.Feign;
import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.springframework.cloud.openfeign.testclients.TestClient; import org.springframework.cloud.openfeign.testclients.TestClient;
@@ -37,15 +34,14 @@ import org.springframework.context.ApplicationContext;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Sven Döring * @author Sven Döring
* @author Sam Kruglov * @author Sam Kruglov
* @author Szymon Linowski
*/ */
public class FeignClientBuilderTests { class FeignClientBuilderTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private FeignClientBuilder feignClientBuilder; private FeignClientBuilder feignClientBuilder;
@@ -75,14 +71,14 @@ public class FeignClientBuilderTests {
return (T) ReflectionUtils.getField(field, factoryBean); return (T) ReflectionUtils.getField(field, factoryBean);
} }
@Before @BeforeEach
public void setUp() { void setUp() {
this.applicationContext = Mockito.mock(ApplicationContext.class); this.applicationContext = Mockito.mock(ApplicationContext.class);
this.feignClientBuilder = new FeignClientBuilder(this.applicationContext); this.feignClientBuilder = new FeignClientBuilder(this.applicationContext);
} }
@Test @Test
public void safetyCheckForNewFieldsOnTheFeignClientAnnotation() { void safetyCheckForNewFieldsOnTheFeignClientAnnotation() {
final List<String> methodNames = new ArrayList(); final List<String> methodNames = new ArrayList();
for (final Method method : FeignClient.class.getMethods()) { for (final Method method : FeignClient.class.getMethods()) {
methodNames.add(method.getName()); methodNames.add(method.getName());
@@ -101,7 +97,7 @@ public class FeignClientBuilderTests {
} }
@Test @Test
public void forType_preinitializedBuilder() { void forType_preinitializedBuilder() {
// when: // when:
final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestFeignClient.class, "TestClient"); final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestFeignClient.class, "TestClient");
@@ -120,7 +116,7 @@ public class FeignClientBuilderTests {
} }
@Test @Test
public void forType_allFieldsSetOnBuilder() { void forType_allFieldsSetOnBuilder() {
// when: // when:
final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestFeignClient.class, "TestClient") final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestFeignClient.class, "TestClient")
.decode404(true).url("Url/").path("/Path").contextId("TestContext"); .decode404(true).url("Url/").path("/Path").contextId("TestContext");
@@ -139,7 +135,7 @@ public class FeignClientBuilderTests {
} }
@Test @Test
public void forType_clientFactoryBeanProvided() { void forType_clientFactoryBeanProvided() {
// when: // when:
final FeignClientBuilder.Builder builder = this.feignClientBuilder final FeignClientBuilder.Builder builder = this.feignClientBuilder
.forType(TestFeignClient.class, new FeignClientFactoryBean(), "TestClient").decode404(true) .forType(TestFeignClient.class, new FeignClientFactoryBean(), "TestClient").decode404(true)
@@ -160,7 +156,7 @@ public class FeignClientBuilderTests {
} }
@Test @Test
public void forType_build() { void forType_build() {
// given: // given:
Mockito.when(this.applicationContext.getBean(FeignContext.class)).thenThrow(new ClosedFileSystemException()); // throw Mockito.when(this.applicationContext.getBean(FeignContext.class)).thenThrow(new ClosedFileSystemException()); // throw
// an // an
@@ -170,11 +166,9 @@ public class FeignClientBuilderTests {
// the // the
// FeignClientFactoryBean // FeignClientFactoryBean
final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestClient.class, "TestClient"); final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestClient.class, "TestClient");
// expect: 'the build will fail right after calling build() with the mocked // expect: 'the build will fail right after calling build() with the mocked
// unusual exception' // unusual exception'
this.thrown.expect(Matchers.isA(ClosedFileSystemException.class)); assertThatExceptionOfType(ClosedFileSystemException.class).isThrownBy(() -> builder.build());
builder.build();
} }
private interface TestFeignClient { private interface TestFeignClient {
@@ -0,0 +1,123 @@
/*
* 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 java.net.UnknownHostException;
import feign.Contract;
import feign.RequestLine;
import feign.RetryableException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.SimpleKey;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Sam Kruglov
*/
@SpringBootTest(classes = FeignClientCacheTests.TestConfiguration.class)
@DirtiesContext
public class FeignClientCacheTests {
private static final String CACHE_NAME = "foo-cache";
@Autowired
private FooClient foo;
@Test
void cacheExists(@Autowired CacheManager cacheManager) {
assertThat(cacheManager.getCache(CACHE_NAME)).isNotNull();
}
@Test
void interceptedCallsReal() {
assertThatExceptionOfType(RetryableException.class).isThrownBy(foo::getWithCache)
.withRootCauseInstanceOf(UnknownHostException.class);
}
@Test
void nonInterceptedCallsReal() {
assertThatExceptionOfType(RetryableException.class).isThrownBy(foo::getWithoutCache)
.withRootCauseInstanceOf(UnknownHostException.class);
}
@Nested
class givenCached {
String cachedValue = "cached";
@BeforeEach
void setUp(@Autowired CacheManager cacheManager) {
cacheManager.getCache(CACHE_NAME).put(SimpleKey.EMPTY, cachedValue);
}
@Test
void interceptedReturnsCached() {
assertThat(foo.getWithCache()).isSameAs(cachedValue);
}
@Test
void nonInterceptedCallsReal() {
assertThatExceptionOfType(RetryableException.class).isThrownBy(foo::getWithoutCache)
.withRootCauseInstanceOf(UnknownHostException.class);
}
}
@Configuration(proxyBeanMethods = false)
@EnableFeignClients(clients = FooClient.class)
@EnableAutoConfiguration
@EnableCaching
protected static class TestConfiguration {
}
@FeignClient(name = "foo", url = "http://foo", configuration = FooConfiguration.class)
interface FooClient {
@RequestLine("GET /with-cache")
@Cacheable(cacheNames = CACHE_NAME)
String getWithCache();
@RequestLine("GET /without-cache")
String getWithoutCache();
}
public static class FooConfiguration {
@Bean
Contract feignContract() {
return new Contract.Default();
}
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright 2021-2021 the original author or authors. * Copyright 2021-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -24,6 +24,7 @@ import feign.Capability;
import feign.Contract; import feign.Contract;
import feign.ExceptionPropagationPolicy; import feign.ExceptionPropagationPolicy;
import feign.Logger; import feign.Logger;
import feign.QueryMapEncoder;
import feign.RequestInterceptor; import feign.RequestInterceptor;
import feign.Retryer; import feign.Retryer;
import feign.codec.Decoder; import feign.codec.Decoder;
@@ -43,6 +44,7 @@ import static org.springframework.cloud.openfeign.test.EqualsAndHashCodeAssert.a
/** /**
* @author Jonatan Ivanov * @author Jonatan Ivanov
* @author Hyeonmin Park
*/ */
class FeignClientConfigurationTests { class FeignClientConfigurationTests {
@@ -64,6 +66,7 @@ class FeignClientConfigurationTests {
assertThat(config.getContract()).isNull(); assertThat(config.getContract()).isNull();
assertThat(config.getExceptionPropagationPolicy()).isNull(); assertThat(config.getExceptionPropagationPolicy()).isNull();
assertThat(config.getCapabilities()).isNull(); assertThat(config.getCapabilities()).isNull();
assertThat(config.getQueryMapEncoder()).isNull();
assertThat(config.getMetrics()).isNull(); assertThat(config.getMetrics()).isNull();
} }
@@ -88,6 +91,7 @@ class FeignClientConfigurationTests {
config.setExceptionPropagationPolicy(ExceptionPropagationPolicy.UNWRAP); config.setExceptionPropagationPolicy(ExceptionPropagationPolicy.UNWRAP);
List<Class<Capability>> capabilities = Lists.list(Capability.class); List<Class<Capability>> capabilities = Lists.list(Capability.class);
config.setCapabilities(capabilities); config.setCapabilities(capabilities);
config.setQueryMapEncoder(QueryMapEncoder.class);
FeignClientProperties.MetricsProperties metrics = new FeignClientProperties.MetricsProperties(); FeignClientProperties.MetricsProperties metrics = new FeignClientProperties.MetricsProperties();
config.setMetrics(metrics); config.setMetrics(metrics);
@@ -105,6 +109,7 @@ class FeignClientConfigurationTests {
assertThat(config.getContract()).isSameAs(Contract.class); assertThat(config.getContract()).isSameAs(Contract.class);
assertThat(config.getExceptionPropagationPolicy()).isSameAs(ExceptionPropagationPolicy.UNWRAP); assertThat(config.getExceptionPropagationPolicy()).isSameAs(ExceptionPropagationPolicy.UNWRAP);
assertThat(config.getCapabilities()).isSameAs(capabilities); assertThat(config.getCapabilities()).isSameAs(capabilities);
assertThat(config.getQueryMapEncoder()).isSameAs(QueryMapEncoder.class);
assertThat(config.getMetrics()).isSameAs(metrics); assertThat(config.getMetrics()).isSameAs(metrics);
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2021-2021 the original author or authors. * Copyright 2021-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -1,5 +1,5 @@
/* /*
* Copyright 2021-2021 the original author or authors. * Copyright 2021-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

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