Compare commits
155
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10c6992935 | ||
|
|
d87375e835 | ||
|
|
cc9af41dfe | ||
|
|
9bb8b43d58 | ||
|
|
60558c46ef | ||
|
|
89db04d7d0 | ||
|
|
27a3967975 | ||
|
|
0c4c19bfcd | ||
|
|
c672d205d7 | ||
|
|
6b29a1f7df | ||
|
|
bbef08205d | ||
|
|
0799f3dd7c | ||
|
|
7ef5c0ce96 | ||
|
|
14914b4c97 | ||
|
|
6bfb1edcf1 | ||
|
|
01a3898e83 | ||
|
|
286360cf7b | ||
|
|
14eb8a7bb1 | ||
|
|
a79d82584e | ||
|
|
ae3e3efb26 | ||
|
|
e32b10b60f | ||
|
|
89fb98daf7 | ||
|
|
1a7917e2bb | ||
|
|
49d3830276 | ||
|
|
d419826ca0 | ||
|
|
64d3f05e70 | ||
|
|
4d021fd3f8 | ||
|
|
a8bcda0b5b | ||
|
|
1b42820c3a | ||
|
|
e31defb2dd | ||
|
|
f4ca971253 | ||
|
|
a8a2a0155f | ||
|
|
cf4fa54ac8 | ||
|
|
93327fcace | ||
|
|
bc6c3b7bf2 | ||
|
|
f410385237 | ||
|
|
a5ab3383c9 | ||
|
|
dd518a812b | ||
|
|
c3dcb1f376 | ||
|
|
27e2775c5f | ||
|
|
83ef242406 | ||
|
|
6534950ed2 | ||
|
|
e83593651c | ||
|
|
4cbf6da17b | ||
|
|
5fea4f3b35 | ||
|
|
36c06c97a6 | ||
|
|
d6b021eaa4 | ||
|
|
c2430c0e29 | ||
|
|
b66e08fda8 | ||
|
|
84819e1328 | ||
|
|
b6422db8e9 | ||
|
|
4bf010e810 | ||
|
|
bd671efed9 | ||
|
|
bfd473cb8f | ||
|
|
2f5d63a061 | ||
|
|
14929cbfee | ||
|
|
d3da7e16e8 | ||
|
|
4e89dd1523 | ||
|
|
63ba4d40ff | ||
|
|
06862ab090 | ||
|
|
72784920d8 | ||
|
|
bf13ae95c9 | ||
|
|
af06086c30 | ||
|
|
5497f5a37c | ||
|
|
12084de3a9 | ||
|
|
84cf97b391 | ||
|
|
3002643ee7 | ||
|
|
b1ec55cb01 | ||
|
|
f0e0e7ea64 | ||
|
|
7311e4abc8 | ||
|
|
ad776a43b5 | ||
|
|
c85853ac9d | ||
|
|
21986f5e92 | ||
|
|
1929dae2d2 | ||
|
|
fc9b47c3b3 | ||
|
|
e7932a6aae | ||
|
|
25a988e1bf | ||
|
|
af103e0137 | ||
|
|
06a55b8bcd | ||
|
|
090c85c7ed | ||
|
|
88633c7f54 | ||
|
|
bb499ea823 | ||
|
|
0e1a579de5 | ||
|
|
b538d7f88c | ||
|
|
525bb603f7 | ||
|
|
ea3fb86690 | ||
|
|
f6cf14f257 | ||
|
|
59ba6b1bc6 | ||
|
|
dd91dcdf8d | ||
|
|
397130a935 | ||
|
|
f49db7233a | ||
|
|
c281800ccd | ||
|
|
1de832e472 | ||
|
|
db2e84ef06 | ||
|
|
cd1cead7fd | ||
|
|
1ad9a8a24f | ||
|
|
06769c4705 | ||
|
|
f3c3b9073b | ||
|
|
df5d1d5079 | ||
|
|
8666006bf4 | ||
|
|
b5c8e6619e | ||
|
|
6f09ae0824 | ||
|
|
c82b577d00 | ||
|
|
eca40256d8 | ||
|
|
a85294a835 | ||
|
|
db778b5c74 | ||
|
|
73a75fd8b2 | ||
|
|
892e65e303 | ||
|
|
422dda0a75 | ||
|
|
3eabb0237e | ||
|
|
ada2cb7913 | ||
|
|
05b58e087e | ||
|
|
80ecc9ac09 | ||
|
|
bee97b8611 | ||
|
|
01d05227c8 | ||
|
|
90400b9e43 | ||
|
|
b1e38db1e2 | ||
|
|
d77337bc79 | ||
|
|
80d2067134 | ||
|
|
887ceefa60 | ||
|
|
2b364367cb | ||
|
|
8aa4729537 | ||
|
|
41e9b55869 | ||
|
|
8a25b8bd63 | ||
|
|
774017db85 | ||
|
|
d1b50ec2ae | ||
|
|
bde804c6a4 | ||
|
|
0888d9ce8d | ||
|
|
1bc7542dc5 | ||
|
|
68689182be | ||
|
|
d5c176c5f4 | ||
|
|
38733043ae | ||
|
|
1b21e3b639 | ||
|
|
14e6806c1c | ||
|
|
dd95dae352 | ||
|
|
c1c211efdb | ||
|
|
ea69c30496 | ||
|
|
f71b419d8d | ||
|
|
35bbb32e03 | ||
|
|
f97cbb9a73 | ||
|
|
de39e67e18 | ||
|
|
78037a1161 | ||
|
|
1ce5ca1ba8 | ||
|
|
59b34b23e9 | ||
|
|
f01c46ab2e | ||
|
|
6dc78c99c2 | ||
|
|
3046af2b42 | ||
|
|
8973f4286b | ||
|
|
ef5f9d6858 | ||
|
|
f661105e63 | ||
|
|
bc10583bf3 | ||
|
|
cb1ea20f3f | ||
|
|
6bfc684967 | ||
|
|
63a9245f13 | ||
|
|
64d63cbb39 |
@@ -9,7 +9,6 @@ jobs:
|
|||||||
branches:
|
branches:
|
||||||
ignore:
|
ignore:
|
||||||
- gh-pages # list of branches to ignore
|
- gh-pages # list of branches to ignore
|
||||||
resource_class: large
|
|
||||||
steps:
|
steps:
|
||||||
- checkout
|
- checkout
|
||||||
- restore_cache:
|
- restore_cache:
|
||||||
@@ -36,4 +35,4 @@ jobs:
|
|||||||
destination: artifacts
|
destination: artifacts
|
||||||
- store_test_results:
|
- store_test_results:
|
||||||
path: /junit/
|
path: /junit/
|
||||||
destination: testartifacts
|
destination: testartifacts
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
---
|
||||||
|
name: Bug report
|
||||||
|
about: Create a report to help us improve
|
||||||
|
title: ''
|
||||||
|
labels: ''
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Describe the bug**
|
||||||
|
Please provide details of the problem, including the version of Spring Cloud that you
|
||||||
|
are using.
|
||||||
|
|
||||||
|
**Sample**
|
||||||
|
If possible, please provide a test case or sample application that reproduces
|
||||||
|
the problem. This makes it much easier for us to diagnose the problem and to verify that
|
||||||
|
we have fixed it.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
name: Feature request
|
||||||
|
about: Suggest an idea for this project
|
||||||
|
title: ''
|
||||||
|
labels: ''
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Is your feature request related to a problem? Please describe.**
|
||||||
|
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||||
|
|
||||||
|
**Describe the solution you'd like**
|
||||||
|
A clear and concise description of what you want to happen.
|
||||||
|
|
||||||
|
**Describe alternatives you've considered**
|
||||||
|
A clear and concise description of any alternative solutions or features you've considered.
|
||||||
|
|
||||||
|
**Additional context**
|
||||||
|
Add any other context or screenshots about the feature request here.
|
||||||
+4
-1
@@ -18,4 +18,7 @@ _site/
|
|||||||
.shelf
|
.shelf
|
||||||
*.swp
|
*.swp
|
||||||
*.swo
|
*.swo
|
||||||
.vscode/
|
.vscode/
|
||||||
|
.flattened-pom.xml
|
||||||
|
.sdkmanrc
|
||||||
|
|
||||||
|
|||||||
+13
-1
@@ -4,6 +4,7 @@ Manual changes to this file will be lost when it is generated again.
|
|||||||
Edit the files in the src/main/asciidoc/ directory instead.
|
Edit the files in the src/main/asciidoc/ directory instead.
|
||||||
////
|
////
|
||||||
|
|
||||||
|
|
||||||
image:https://circleci.com/gh/spring-cloud/spring-cloud-openfeign.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-openfeign"]
|
image:https://circleci.com/gh/spring-cloud/spring-cloud-openfeign.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-openfeign"]
|
||||||
|
|
||||||
image:https://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
|
image:https://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
|
||||||
@@ -27,6 +28,8 @@ image:https://api.codacy.com/project/badge/Grade/97b04c4e609c4b4f86b415e4437a648
|
|||||||
:project-full-name: Spring Cloud OpenFeign
|
:project-full-name: Spring Cloud OpenFeign
|
||||||
:all: {asterisk}{asterisk}
|
:all: {asterisk}{asterisk}
|
||||||
|
|
||||||
|
:core_path: {project-root}/spring-cloud-openfeign-core
|
||||||
|
|
||||||
This project provides OpenFeign integrations for Spring Boot apps through autoconfiguration
|
This project provides OpenFeign integrations for Spring Boot apps through autoconfiguration
|
||||||
and binding to the Spring Environment and other Spring programming model idioms.
|
and binding to the Spring Environment and other Spring programming model idioms.
|
||||||
|
|
||||||
@@ -99,6 +102,11 @@ https://eclipse.org[Eclipse] when working with the code. We use the
|
|||||||
https://eclipse.org/m2e/[m2eclipse] eclipse plugin for maven support. Other IDEs and tools
|
https://eclipse.org/m2e/[m2eclipse] eclipse plugin for maven support. Other IDEs and tools
|
||||||
should also work without issue as long as they use Maven 3.3.3 or better.
|
should also work without issue as long as they use Maven 3.3.3 or better.
|
||||||
|
|
||||||
|
==== Activate the Spring Maven profile
|
||||||
|
Spring Cloud projects require the 'spring' Maven profile to be activated to resolve
|
||||||
|
the spring milestone and snapshot repositories. Use your preferred IDE to set this
|
||||||
|
profile to be active, or you may experience build errors.
|
||||||
|
|
||||||
==== Importing into eclipse with m2eclipse
|
==== Importing into eclipse with m2eclipse
|
||||||
We recommend the https://eclipse.org/m2e/[m2eclipse] eclipse plugin when working with
|
We recommend the https://eclipse.org/m2e/[m2eclipse] eclipse plugin when working with
|
||||||
eclipse. If you don't already have m2eclipse installed it is available from the "eclipse
|
eclipse. If you don't already have m2eclipse installed it is available from the "eclipse
|
||||||
@@ -307,4 +315,8 @@ Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on t
|
|||||||
- `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` URL.
|
- `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` URL.
|
||||||
- `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`.
|
- `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`.
|
||||||
|
|
||||||
IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources.
|
IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources.
|
||||||
|
|
||||||
|
== License
|
||||||
|
|
||||||
|
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/master/LICENSE.txt[here].
|
||||||
|
|||||||
+5
-15
@@ -6,7 +6,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.cloud</groupId>
|
<groupId>org.springframework.cloud</groupId>
|
||||||
<artifactId>spring-cloud-openfeign</artifactId>
|
<artifactId>spring-cloud-openfeign</artifactId>
|
||||||
<version>2.2.0.M3</version>
|
<version>2.2.7.RELEASE</version>
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>spring-cloud-openfeign-docs</artifactId>
|
<artifactId>spring-cloud-openfeign-docs</artifactId>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
@@ -15,8 +15,8 @@
|
|||||||
<properties>
|
<properties>
|
||||||
<docs.main>spring-cloud-openfeign</docs.main>
|
<docs.main>spring-cloud-openfeign</docs.main>
|
||||||
<main.basedir>${basedir}/..</main.basedir>
|
<main.basedir>${basedir}/..</main.basedir>
|
||||||
<docs.whitelisted.branches>2.0.x,2.1.x</docs.whitelisted.branches>
|
|
||||||
<configprops.inclusionPattern>feign.*</configprops.inclusionPattern>
|
<configprops.inclusionPattern>feign.*</configprops.inclusionPattern>
|
||||||
|
<upload-docs-zip.phase>deploy</upload-docs-zip.phase>
|
||||||
</properties>
|
</properties>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
@@ -24,16 +24,6 @@
|
|||||||
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<artifactId>maven-deploy-plugin</artifactId>
|
|
||||||
<configuration>
|
|
||||||
<skip>true</skip>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
<profiles>
|
<profiles>
|
||||||
<profile>
|
<profile>
|
||||||
<id>docs</id>
|
<id>docs</id>
|
||||||
@@ -44,11 +34,9 @@
|
|||||||
<artifactId>git-commit-id-plugin</artifactId>
|
<artifactId>git-commit-id-plugin</artifactId>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-dependency-plugin</artifactId>
|
<artifactId>maven-dependency-plugin</artifactId>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-resources-plugin</artifactId>
|
<artifactId>maven-resources-plugin</artifactId>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
@@ -60,9 +48,11 @@
|
|||||||
<artifactId>asciidoctor-maven-plugin</artifactId>
|
<artifactId>asciidoctor-maven-plugin</artifactId>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-antrun-plugin</artifactId>
|
<artifactId>maven-antrun-plugin</artifactId>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-deploy-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
</profile>
|
</profile>
|
||||||
|
|||||||
@@ -19,3 +19,7 @@ include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/maste
|
|||||||
== Contributing
|
== Contributing
|
||||||
|
|
||||||
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[]
|
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[]
|
||||||
|
|
||||||
|
== License
|
||||||
|
|
||||||
|
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/master/LICENSE.txt[here].
|
||||||
|
|||||||
@@ -14,3 +14,5 @@
|
|||||||
:sc-ext: java
|
:sc-ext: java
|
||||||
:project-full-name: Spring Cloud OpenFeign
|
:project-full-name: Spring Cloud OpenFeign
|
||||||
:all: {asterisk}{asterisk}
|
:all: {asterisk}{asterisk}
|
||||||
|
|
||||||
|
:core_path: {project-root}/spring-cloud-openfeign-core
|
||||||
|
|||||||
@@ -1,23 +1,27 @@
|
|||||||
|===
|
|===
|
||||||
|Name | Default | Description
|
|Name | Default | Description
|
||||||
|
|
||||||
|
|feign.autoconfiguration.jackson.enabled | `false` | If true, PageJacksonModule and SortJacksonModule bean will be provided for Jackson page decoding.
|
||||||
|
|feign.circuitbreaker.enabled | `false` | If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker.
|
||||||
|feign.client.config | |
|
|feign.client.config | |
|
||||||
|feign.client.default-config | default |
|
|feign.client.decode-slash | `true` | Feign clients do not encode slash `/` characters by default. To change this behavior, set the `decodeSlash` to `false`.
|
||||||
|feign.client.default-to-properties | true |
|
|feign.client.default-config | `default` |
|
||||||
|feign.compression.request.enabled | false | Enables the request sent by Feign to be compressed.
|
|feign.client.default-to-properties | `true` |
|
||||||
|feign.compression.request.mime-types | [text/xml, application/xml, application/json] | The list of supported mime types.
|
|feign.compression.request.enabled | `false` | Enables the request sent by Feign to be compressed.
|
||||||
|feign.compression.request.min-request-size | 2048 | The minimum threshold content size.
|
|feign.compression.request.mime-types | `[text/xml, application/xml, application/json]` | The list of supported mime types.
|
||||||
|feign.compression.response.enabled | false | Enables the response from Feign to be compressed.
|
|feign.compression.request.min-request-size | `2048` | The minimum threshold content size.
|
||||||
|feign.httpclient.connection-timeout | 2000 |
|
|feign.compression.response.enabled | `false` | Enables the response from Feign to be compressed.
|
||||||
|feign.httpclient.connection-timer-repeat | 3000 |
|
|feign.compression.response.useGzipDecoder | `false` | Enables the default gzip decoder to be used.
|
||||||
|feign.httpclient.disable-ssl-validation | false |
|
|feign.httpclient.connection-timeout | `2000` |
|
||||||
|feign.httpclient.enabled | true | Enables the use of the Apache HTTP Client by Feign.
|
|feign.httpclient.connection-timer-repeat | `3000` |
|
||||||
|feign.httpclient.follow-redirects | true |
|
|feign.httpclient.disable-ssl-validation | `false` |
|
||||||
|feign.httpclient.max-connections | 200 |
|
|feign.httpclient.enabled | `true` | Enables the use of the Apache HTTP Client by Feign.
|
||||||
|feign.httpclient.max-connections-per-route | 50 |
|
|feign.httpclient.follow-redirects | `true` |
|
||||||
|feign.httpclient.time-to-live | 900 |
|
|feign.httpclient.max-connections | `200` |
|
||||||
|
|feign.httpclient.max-connections-per-route | `50` |
|
||||||
|
|feign.httpclient.time-to-live | `900` |
|
||||||
|feign.httpclient.time-to-live-unit | |
|
|feign.httpclient.time-to-live-unit | |
|
||||||
|feign.hystrix.enabled | false | If true, an OpenFeign client will be wrapped with a Hystrix circuit breaker.
|
|feign.hystrix.enabled | `false` | If true, an OpenFeign client will be wrapped with a Hystrix circuit breaker.
|
||||||
|feign.okhttp.enabled | false | Enables the use of the OK HTTP Client by Feign.
|
|feign.okhttp.enabled | `false` | Enables the use of the OK HTTP Client by Feign.
|
||||||
|
|
||||||
|===
|
|===
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
:numbered!:
|
||||||
|
[appendix]
|
||||||
|
[[common-application-properties]]
|
||||||
|
== Common application properties
|
||||||
|
|
||||||
|
include::_attributes.adoc[]
|
||||||
|
|
||||||
|
Various properties can be specified inside your `application.properties` file, inside your `application.yml` file, or as command line switches.
|
||||||
|
This appendix provides a list of common {project-full-name} properties and references to the underlying classes that consume them.
|
||||||
|
|
||||||
|
NOTE: Property contributions can come from additional jar files on your classpath, so you should not consider this an exhaustive list.
|
||||||
|
Also, you can define your own properties.
|
||||||
|
|
||||||
|
include::_configprops.adoc[]
|
||||||
@@ -24,3 +24,18 @@ public class WebApplication {
|
|||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
We welcome contributions. You can read more on how to contribute to the project https://github.com/spring-cloud/spring-cloud-openfeign/blob/master/README.adoc#3-contributing[here].
|
||||||
|
|
||||||
|
## Community Support
|
||||||
|
|
||||||
|
* You can report issues through https://github.com/spring-cloud/spring-cloud-openfeign/issues[Github].
|
||||||
|
* We monitor https://stackoverflow.com/[StackOverflow] for questions with the `spring-cloud-feign` tag.
|
||||||
|
* You can contact our team at https://gitter.im/spring-cloud/spring-cloud[Gitter].
|
||||||
|
|
||||||
|
## Commercial Support
|
||||||
|
|
||||||
|
Commercial Support is provided as part of the https://spring.io/support[VMware Spring Runtime] offering.
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,13 @@ include::intro.adoc[]
|
|||||||
[[spring-cloud-feign]]
|
[[spring-cloud-feign]]
|
||||||
== Declarative REST Client: Feign
|
== Declarative REST Client: Feign
|
||||||
|
|
||||||
https://github.com/Netflix/feign[Feign] is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and for using the same `HttpMessageConverters` used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.
|
https://github.com/OpenFeign/feign[Feign] is a declarative web service client.
|
||||||
|
It makes writing web service clients easier.
|
||||||
|
To use Feign create an interface and annotate it.
|
||||||
|
It has pluggable annotation support including Feign annotations and JAX-RS annotations.
|
||||||
|
Feign also supports pluggable encoders and decoders.
|
||||||
|
Spring Cloud adds support for Spring MVC annotations and for using the same `HttpMessageConverters` used by default in Spring Web.
|
||||||
|
Spring Cloud integrates Ribbon and Eureka, Spring Cloud CircuitBreaker, as well as Spring Cloud LoadBalancer to provide a load-balanced http client when using Feign.
|
||||||
|
|
||||||
[[netflix-feign-starter]]
|
[[netflix-feign-starter]]
|
||||||
=== How to Include Feign
|
=== How to Include Feign
|
||||||
@@ -41,26 +47,30 @@ public interface StoreClient {
|
|||||||
@RequestMapping(method = RequestMethod.GET, value = "/stores")
|
@RequestMapping(method = RequestMethod.GET, value = "/stores")
|
||||||
List<Store> getStores();
|
List<Store> getStores();
|
||||||
|
|
||||||
|
@RequestMapping(method = RequestMethod.GET, value = "/stores")
|
||||||
|
Page<Store> getStores(Pageable pageable);
|
||||||
|
|
||||||
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
|
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
|
||||||
Store update(@PathVariable("storeId") Long storeId, Store store);
|
Store update(@PathVariable("storeId") Long storeId, Store store);
|
||||||
}
|
}
|
||||||
----
|
----
|
||||||
|
|
||||||
In the `@FeignClient` annotation the String value ("stores" above) is
|
In the `@FeignClient` annotation the String value ("stores" above) is an arbitrary client name, which is used to create either a https://github.com/Netflix/ribbon[Ribbon] load-balancer (see <<spring-cloud-ribbon,below for details of Ribbon support>> and <<spring-cloud-circuitbreaker,below for details of Spring Cloud CircuitBreaker support>>) or https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancer.java[Spring Cloud LoadBalancer].
|
||||||
an arbitrary client name, which is used to create a Ribbon load
|
You can also specify a URL using the `url` attribute
|
||||||
balancer (see <<spring-cloud-ribbon,below for details of Ribbon
|
|
||||||
support>>). You can also specify a URL using the `url` attribute
|
|
||||||
(absolute value or just a hostname). The name of the bean in the
|
(absolute value or just a hostname). The name of the bean in the
|
||||||
application context is the fully qualified name of the interface.
|
application context is the fully qualified name of the interface.
|
||||||
To specify your own alias value you can use the `qualifier` value
|
To specify your own alias value you can use the `qualifier` value
|
||||||
of the `@FeignClient` annotation.
|
of the `@FeignClient` annotation.
|
||||||
|
|
||||||
The Ribbon client above will want to discover the physical addresses
|
The load-balancer client above will want to discover the physical addresses
|
||||||
for the "stores" service. If your application is a Eureka client then
|
for the "stores" service. If your application is a Eureka client then
|
||||||
it will resolve the service in the Eureka service registry. If you
|
it will resolve the service in the Eureka service registry. If you
|
||||||
don't want to use Eureka, you can simply configure a list of servers
|
don't want to use Eureka, you can simply configure a list of servers
|
||||||
in your external configuration (see
|
in your external configuration using https://cloud.spring.io/spring-cloud-static/spring-cloud-commons/current/reference/html/#simplediscoveryclient[`SimpleDiscoveryClient`].
|
||||||
<<spring-cloud-ribbon-without-eureka,above for example>>).
|
|
||||||
|
WARNING: In order to maintain backward compatibility, is used as the default load-balancer implementation.
|
||||||
|
However, Spring Cloud Netflix Ribbon is now in maintenance mode, so we recommend using Spring Cloud LoadBalancer instead.
|
||||||
|
To do this, set the value of `spring.cloud.loadbalancer.ribbon.enabled` to `false`.
|
||||||
|
|
||||||
[[spring-cloud-feign-overriding-defaults]]
|
[[spring-cloud-feign-overriding-defaults]]
|
||||||
=== Overriding Feign Defaults
|
=== Overriding Feign Defaults
|
||||||
@@ -102,19 +112,23 @@ public interface StoreClient {
|
|||||||
}
|
}
|
||||||
----
|
----
|
||||||
|
|
||||||
Spring Cloud Netflix provides the following beans by default for feign (`BeanType` beanName: `ClassName`):
|
Spring Cloud OpenFeign provides the following beans by default for feign (`BeanType` beanName: `ClassName`):
|
||||||
|
|
||||||
* `Decoder` feignDecoder: `ResponseEntityDecoder` (which wraps a `SpringDecoder`)
|
* `Decoder` feignDecoder: `ResponseEntityDecoder` (which wraps a `SpringDecoder`)
|
||||||
* `Encoder` feignEncoder: `SpringEncoder`
|
* `Encoder` feignEncoder: `SpringEncoder`
|
||||||
* `Logger` feignLogger: `Slf4jLogger`
|
* `Logger` feignLogger: `Slf4jLogger`
|
||||||
* `Contract` feignContract: `SpringMvcContract`
|
* `Contract` feignContract: `SpringMvcContract`
|
||||||
* `Feign.Builder` feignBuilder: `HystrixFeign.Builder`
|
* `Feign.Builder` feignBuilder: `HystrixFeign.Builder`
|
||||||
* `Client` feignClient: if Ribbon is enabled it is a `LoadBalancerFeignClient`, otherwise the default feign client is used.
|
* `Feign.Builder` feignBuilder: `FeignCircuitBreaker.Builder`
|
||||||
|
* `Client` feignClient: if Ribbon is in the classpath and is enabled it is a `LoadBalancerFeignClient`, otherwise if Spring Cloud LoadBalancer is in the classpath, `FeignBlockingLoadBalancerClient` is used.
|
||||||
|
If none of them is in the classpath, the default feign client is used.
|
||||||
|
|
||||||
|
NOTE: `spring-cloud-starter-openfeign` supports both `spring-cloud-starter-netflix-ribbon` and `spring-cloud-starter-loadbalancer`. However, as they are optional dependencies, you need to make sure the one you want to use has been added to your project.
|
||||||
|
|
||||||
The OkHttpClient and ApacheHttpClient feign clients can be used by setting `feign.okhttp.enabled` or `feign.httpclient.enabled` to `true`, respectively, and having them on the classpath.
|
The OkHttpClient and ApacheHttpClient feign clients can be used by setting `feign.okhttp.enabled` or `feign.httpclient.enabled` to `true`, respectively, and having them on the classpath.
|
||||||
You can customize the HTTP client used by providing a bean of either `org.apache.http.impl.client.CloseableHttpClient` when using Apache or `okhttp3.OkHttpClient` when using OK HTTP.
|
You can customize the HTTP client used by providing a bean of either `org.apache.http.impl.client.CloseableHttpClient` when using Apache or `okhttp3.OkHttpClient` when using OK HTTP.
|
||||||
|
|
||||||
Spring Cloud Netflix _does not_ provide the following beans by default for feign, but still looks up beans of these types from the application context to create the feign client:
|
Spring Cloud OpenFeign _does not_ provide the following beans by default for feign, but still looks up beans of these types from the application context to create the feign client:
|
||||||
|
|
||||||
* `Logger.Level`
|
* `Logger.Level`
|
||||||
* `Retryer`
|
* `Retryer`
|
||||||
@@ -124,6 +138,10 @@ Spring Cloud Netflix _does not_ provide the following beans by default for feign
|
|||||||
* `SetterFactory`
|
* `SetterFactory`
|
||||||
* `QueryMapEncoder`
|
* `QueryMapEncoder`
|
||||||
|
|
||||||
|
A bean of `Retryer.NEVER_RETRY` with the type `Retryer` is created by default, which will disable retrying.
|
||||||
|
Notice this retrying behavior is different from the Feign default one, where it will automatically retry IOExceptions,
|
||||||
|
treating them as transient network related exceptions, and any RetryableException thrown from an ErrorDecoder.
|
||||||
|
|
||||||
Creating a bean of one of those type and placing it in a `@FeignClient` configuration (such as `FooConfiguration` above) allows you to override each one of the beans described. Example:
|
Creating a bean of one of those type and placing it in a `@FeignClient` configuration (such as `FooConfiguration` above) allows you to override each one of the beans described. Example:
|
||||||
|
|
||||||
[source,java,indent=0]
|
[source,java,indent=0]
|
||||||
@@ -158,6 +176,10 @@ feign:
|
|||||||
loggerLevel: full
|
loggerLevel: full
|
||||||
errorDecoder: com.example.SimpleErrorDecoder
|
errorDecoder: com.example.SimpleErrorDecoder
|
||||||
retryer: com.example.SimpleRetryer
|
retryer: com.example.SimpleRetryer
|
||||||
|
defaultQueryParameters:
|
||||||
|
query: queryValue
|
||||||
|
defaultRequestHeaders:
|
||||||
|
header: headerValue
|
||||||
requestInterceptors:
|
requestInterceptors:
|
||||||
- com.example.FooRequestInterceptor
|
- com.example.FooRequestInterceptor
|
||||||
- com.example.BarRequestInterceptor
|
- com.example.BarRequestInterceptor
|
||||||
@@ -171,6 +193,8 @@ Default configurations can be specified in the `@EnableFeignClients` attribute `
|
|||||||
|
|
||||||
If you prefer using configuration properties to configured all `@FeignClient`, you can create configuration properties with `default` feign name.
|
If you prefer using configuration properties to configured all `@FeignClient`, you can create configuration properties with `default` feign name.
|
||||||
|
|
||||||
|
You can use `feign.client.config.feignName.defaultQueryParameters` and `feign.client.config.feignName.defaultRequestHeaders` to specify query parameters and headers that will be sent with every request of the client named `feignName`.
|
||||||
|
|
||||||
application.yml
|
application.yml
|
||||||
[source,yaml]
|
[source,yaml]
|
||||||
----
|
----
|
||||||
@@ -228,6 +252,67 @@ public interface BarClient {
|
|||||||
}
|
}
|
||||||
----
|
----
|
||||||
|
|
||||||
|
It is also possible to configure FeignClient not to inherit beans from the parent context.
|
||||||
|
You can do this by overriding the `inheritParentConfiguration()` in a `FeignClientConfigurer`
|
||||||
|
bean to return `false`:
|
||||||
|
|
||||||
|
[source,java,indent=0]
|
||||||
|
----
|
||||||
|
@Configuration
|
||||||
|
public class CustomConfiguration{
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public FeignClientConfigurer feignClientConfigurer() {
|
||||||
|
return new FeignClientConfigurer() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean inheritParentConfiguration() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----
|
||||||
|
|
||||||
|
TIP: By default, Feign clients do not encode slash `/` characters. You can change this behaviour, by setting the value of `feign.client.decodeSlash` to `false`.
|
||||||
|
|
||||||
|
[[timeout-handling]]
|
||||||
|
=== Timeout Handling
|
||||||
|
|
||||||
|
We can configure timeouts on both the default and the named client. OpenFeign works with two timeout parameters:
|
||||||
|
|
||||||
|
- `connectTimeout` prevents blocking the caller due to the long server processing time.
|
||||||
|
- `readTimeout` is applied from the time of connection establishment and is triggered when returning the response takes too long.
|
||||||
|
|
||||||
|
NOTE: In case the server is not running or available a packet results in _connection refused_. The communication ends either with an error message or in a fallback. This can happen _before_ the `connectTimeout` if it is set very low. The time taken to perform a lookup and to receive such a packet causes a significant part of this delay. It is subject to change based on the remote host that involves a DNS lookup.
|
||||||
|
|
||||||
|
When Hystrix <<spring-cloud-openfeign#spring-cloud-feign-hystrix,is enabled>>, its timeout configuration link:https://github.com/Netflix/Hystrix/wiki/Configuration#execution.isolation.thread.timeoutInMilliseconds[defaults] to 1000 milliseconds. Hence, it might occur before the client timeout that we configured earlier. Increasing this timeout prevents it from happening.
|
||||||
|
|
||||||
|
[source,yaml]
|
||||||
|
----
|
||||||
|
feign:
|
||||||
|
client:
|
||||||
|
config:
|
||||||
|
default:
|
||||||
|
connectTimeout: 5000
|
||||||
|
readTimeout: 5000
|
||||||
|
hystrix:
|
||||||
|
enabled: true
|
||||||
|
|
||||||
|
hystrix:
|
||||||
|
command:
|
||||||
|
default:
|
||||||
|
execution:
|
||||||
|
timeout:
|
||||||
|
enabled: true
|
||||||
|
isolation:
|
||||||
|
thread:
|
||||||
|
timeoutInMilliseconds: 60000
|
||||||
|
----
|
||||||
|
|
||||||
|
NOTE: When the Hystrix timeout is enabled and its timeout is set longer than that of a feign client, `HystrixTimeoutException` wraps a feign exception. Otherwise, the only difference is the cause of the exception. The purpose of `HystrixTimeoutException` is to wrap any runtime exception that occurs first and throw an instance of itself.
|
||||||
|
|
||||||
=== Creating Feign Clients Manually
|
=== Creating Feign Clients Manually
|
||||||
|
|
||||||
In some cases it might be necessary to customize your Feign Clients in a way that is not
|
In some cases it might be necessary to customize your Feign Clients in a way that is not
|
||||||
@@ -265,7 +350,7 @@ class FooController {
|
|||||||
----
|
----
|
||||||
|
|
||||||
NOTE: In the above example `FeignClientsConfiguration.class` is the default configuration
|
NOTE: In the above example `FeignClientsConfiguration.class` is the default configuration
|
||||||
provided by Spring Cloud Netflix.
|
provided by Spring Cloud OpenFeign.
|
||||||
|
|
||||||
NOTE: `PROD-SVC` is the name of the service the Clients will be making requests to.
|
NOTE: `PROD-SVC` is the name of the service the Clients will be making requests to.
|
||||||
|
|
||||||
@@ -273,6 +358,9 @@ NOTE: The Feign `Contract` object defines what annotations and values are valid
|
|||||||
autowired `Contract` bean provides supports for SpringMVC annotations, instead of
|
autowired `Contract` bean provides supports for SpringMVC annotations, instead of
|
||||||
the default Feign native annotations.
|
the default Feign native annotations.
|
||||||
|
|
||||||
|
You can also use the `Builder`to configure FeignClient not to inherit beans from the parent context.
|
||||||
|
You can do this by overriding calling `inheritParentContext(false)` on the `Builder`.
|
||||||
|
|
||||||
[[spring-cloud-feign-hystrix]]
|
[[spring-cloud-feign-hystrix]]
|
||||||
=== Feign Hystrix Support
|
=== Feign Hystrix Support
|
||||||
|
|
||||||
@@ -343,9 +431,47 @@ static class HystrixClientFallbackFactory implements FallbackFactory<HystrixClie
|
|||||||
|
|
||||||
WARNING: There is a limitation with the implementation of fallbacks in Feign and how Hystrix fallbacks work. Fallbacks are currently not supported for methods that return `com.netflix.hystrix.HystrixCommand` and `rx.Observable`.
|
WARNING: There is a limitation with the implementation of fallbacks in Feign and how Hystrix fallbacks work. Fallbacks are currently not supported for methods that return `com.netflix.hystrix.HystrixCommand` and `rx.Observable`.
|
||||||
|
|
||||||
|
[[spring-cloud-feign-circuitbreaker]]
|
||||||
|
=== Feign Spring Cloud CircuitBreaker Support
|
||||||
|
|
||||||
|
If Spring Cloud CircuitBreaker is on the classpath and `feign.circuitbreaker.enabled=true`, Feign will wrap all methods with a circuit breaker.
|
||||||
|
|
||||||
|
To disable Spring Cloud CircuitBreaker support on a per-client basis create a vanilla `Feign.Builder` with the "prototype" scope, e.g.:
|
||||||
|
|
||||||
|
[source,java,indent=0]
|
||||||
|
----
|
||||||
|
@Configuration
|
||||||
|
public class FooConfiguration {
|
||||||
|
@Bean
|
||||||
|
@Scope("prototype")
|
||||||
|
public Feign.Builder feignBuilder() {
|
||||||
|
return Feign.builder();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----
|
||||||
|
|
||||||
|
The circuit breaker name follows this pattern `<feignClientName>_<calledMethod>`. When calling a `@FeignClient` with name `foo` and the called interface method is `bar` then the circuit breaker name will be `foo_bar`.
|
||||||
|
|
||||||
|
[[spring-cloud-feign-circuitbreaker-fallback]]
|
||||||
|
=== Feign Spring Cloud CircuitBreaker Fallbacks
|
||||||
|
|
||||||
|
Spring Cloud CircuitBreaker supports the notion of a fallback: a default code path that is executed when they circuit is open or there is an error. To enable fallbacks for a given `@FeignClient` set the `fallback` attribute to the class name that implements the fallback. You also need to declare your implementation as a Spring bean.
|
||||||
|
|
||||||
|
[source,java,indent=0]
|
||||||
|
----
|
||||||
|
include::{core_path}/src/test/java/org/springframework/cloud/openfeign/circuitbreaker/CircuitBreakerTests.java[tags=client_with_fallback, indent=0]
|
||||||
|
----
|
||||||
|
|
||||||
|
If one needs access to the cause that made the fallback trigger, one can use the `fallbackFactory` attribute inside `@FeignClient`.
|
||||||
|
|
||||||
|
[source,java,indent=0]
|
||||||
|
----
|
||||||
|
include::{core_path}/src/test/java/org/springframework/cloud/openfeign/circuitbreaker/CircuitBreakerTests.java[tags=client_with_fallback_factory, indent=0]
|
||||||
|
----
|
||||||
|
|
||||||
=== Feign and `@Primary`
|
=== Feign and `@Primary`
|
||||||
|
|
||||||
When using Feign with Hystrix fallbacks, there are multiple beans in the `ApplicationContext` of the same type. This will cause `@Autowired` to not work because there isn't exactly one bean, or one marked as primary. To work around this, Spring Cloud Netflix marks all Feign instances as `@Primary`, so Spring Framework will know which bean to inject. In some cases, this may not be desirable. To turn off this behavior set the `primary` attribute of `@FeignClient` to false.
|
When using Feign with Hystrix fallbacks, there are multiple beans in the `ApplicationContext` of the same type. This will cause `@Autowired` to not work because there isn't exactly one bean, or one marked as primary. To work around this, Spring Cloud OpenFeign marks all Feign instances as `@Primary`, so Spring Framework will know which bean to inject. In some cases, this may not be desirable. To turn off this behavior set the `primary` attribute of `@FeignClient` to false.
|
||||||
|
|
||||||
[source,java,indent=0]
|
[source,java,indent=0]
|
||||||
----
|
----
|
||||||
@@ -418,6 +544,14 @@ feign.compression.request.min-request-size=2048
|
|||||||
|
|
||||||
These properties allow you to be selective about the compressed media types and minimum request threshold length.
|
These properties allow you to be selective about the compressed media types and minimum request threshold length.
|
||||||
|
|
||||||
|
For http clients except OkHttpClient, default gzip decoder can be enabled to decode gzip response in UTF-8 encoding:
|
||||||
|
|
||||||
|
[source,java]
|
||||||
|
----
|
||||||
|
feign.compression.response.enabled=true
|
||||||
|
feign.compression.response.useGzipDecoder=true
|
||||||
|
----
|
||||||
|
|
||||||
=== Feign logging
|
=== Feign logging
|
||||||
|
|
||||||
A logger is created for each Feign client created. By default the name of the logger is the full class name of the interface used to create the Feign client. Feign logging only responds to the `DEBUG` level.
|
A logger is created for each Feign client created. By default the name of the logger is the full class name of the interface used to create the Feign client. Feign logging only responds to the `DEBUG` level.
|
||||||
@@ -505,6 +639,79 @@ public interface DemoTemplate {
|
|||||||
}
|
}
|
||||||
----
|
----
|
||||||
|
|
||||||
|
=== Spring @MatrixVariable Support
|
||||||
|
|
||||||
|
Spring Cloud OpenFeign provides support for the Spring `@MatrixVariable` annotation.
|
||||||
|
|
||||||
|
If a map is passed as the method argument, the `@MatrixVariable` path segment is created by joining key-value pairs from the map with a `=`.
|
||||||
|
|
||||||
|
If a different object is passed, either the `name` provided in the `@MatrixVariable` annotation (if defined) or the annotated variable name is
|
||||||
|
joined with the provided method argument using `=`.
|
||||||
|
|
||||||
|
IMPORTANT:: Even though, on the server side, Spring does not require the users to name the path segment placeholder same as the matrix variable name, since it would be too ambiguous on the client side, Spring Cloud OpenFeign requires that you add a path segment placeholder with a name matching either the `name` provided in the `@MatrixVariable` annotation (if defined) or the annotated variable name.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
[source,java,indent=0]
|
||||||
|
----
|
||||||
|
@GetMapping("/objects/links/{matrixVars}")
|
||||||
|
Map<String, List<String>> getObjects(@MatrixVariable Map<String, List<String>> matrixVars);
|
||||||
|
----
|
||||||
|
Note that both variable name and the path segment placeholder are called `matrixVars`.
|
||||||
|
|
||||||
|
[source,java,indent=0]
|
||||||
|
----
|
||||||
|
@FeignClient("demo")
|
||||||
|
public interface DemoTemplate {
|
||||||
|
|
||||||
|
@GetMapping(path = "/stores")
|
||||||
|
CollectionModel<Store> getStores();
|
||||||
|
}
|
||||||
|
----
|
||||||
|
|
||||||
|
=== Feign `CollectionFormat` support
|
||||||
|
We support `feign.CollectionFormat` by providing the `@CollectionFormat` annotation. You can annotate a Feign client method with it by passing the desired `feign.CollectionFormat` as annotation value.
|
||||||
|
|
||||||
|
In the following example, the `CSV` format is used instead of the default `EXPLODED` to process the method.
|
||||||
|
|
||||||
|
[source,java,indent=0]
|
||||||
|
----
|
||||||
|
@FeignClient(name = "demo")
|
||||||
|
protected interface PageableFeignClient {
|
||||||
|
|
||||||
|
@CollectionFormat(feign.CollectionFormat.CSV)
|
||||||
|
@GetMapping(path = "/page")
|
||||||
|
ResponseEntity performRequest(Pageable page);
|
||||||
|
|
||||||
|
}
|
||||||
|
----
|
||||||
|
|
||||||
|
TIP: Set the `CSV` format while sending `Pageable` as a query parameter in order for it to be encoded correctly.
|
||||||
|
|
||||||
|
=== Reactive Support
|
||||||
|
As the https://github.com/OpenFeign/feign[OpenFeign project] does not currently support reactive clients, such as https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html[Spring WebClient], neither does Spring Cloud OpenFeign. We will add support for it here as soon as it becomes available in the core project.
|
||||||
|
|
||||||
|
Until that is done, we recommend using https://github.com/Playtika/feign-reactive[feign-reactive] for Spring WebClient support.
|
||||||
|
|
||||||
|
==== Early Initialization Errors
|
||||||
|
|
||||||
|
Depending on how you are using your Feign clients you may see initialization errors when starting your application.
|
||||||
|
To work around this problem you can use an `ObjectProvider` when autowiring your client.
|
||||||
|
|
||||||
|
[source,java,indent=0]
|
||||||
|
----
|
||||||
|
@Autowired
|
||||||
|
ObjectProvider<TestFeginClient> testFeginClient;
|
||||||
|
----
|
||||||
|
|
||||||
|
=== Spring Data Support
|
||||||
|
You may consider enabling Jackson Modules for the support `org.springframework.data.domain.Page` and `org.springframework.data.domain.Sort` decoding.
|
||||||
|
|
||||||
|
[source,java]
|
||||||
|
----
|
||||||
|
feign.autoconfiguration.jackson.enabled=true
|
||||||
|
----
|
||||||
|
|
||||||
== Configuration properties
|
== Configuration properties
|
||||||
|
|
||||||
To see the list of all Sleuth related configuration properties please check link:appendix.html[the Appendix page].
|
To see the list of all Sleuth related configuration properties please check link:appendix.html[the Appendix page].
|
||||||
|
|||||||
@@ -4,14 +4,14 @@
|
|||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>spring-cloud-openfeign</artifactId>
|
<artifactId>spring-cloud-openfeign</artifactId>
|
||||||
<version>2.2.0.M3</version>
|
<version>2.2.7.RELEASE</version>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
<name>Spring Cloud OpenFeign</name>
|
<name>Spring Cloud OpenFeign</name>
|
||||||
<description>Spring Cloud OpenFeign</description>
|
<description>Spring Cloud OpenFeign</description>
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.cloud</groupId>
|
<groupId>org.springframework.cloud</groupId>
|
||||||
<artifactId>spring-cloud-build</artifactId>
|
<artifactId>spring-cloud-build</artifactId>
|
||||||
<version>2.2.0.M6</version>
|
<version>2.3.2.RELEASE</version>
|
||||||
<relativePath/>
|
<relativePath/>
|
||||||
</parent>
|
</parent>
|
||||||
<scm>
|
<scm>
|
||||||
@@ -25,12 +25,11 @@
|
|||||||
</scm>
|
</scm>
|
||||||
<properties>
|
<properties>
|
||||||
<main.basedir>${basedir}</main.basedir>
|
<main.basedir>${basedir}</main.basedir>
|
||||||
<jackson.version>2.7.3</jackson.version>
|
<jackson.version>2.11.3</jackson.version>
|
||||||
<spring-cloud-commons.version>2.2.0.M3</spring-cloud-commons.version>
|
<spring-cloud-commons.version>2.2.7.RELEASE</spring-cloud-commons.version>
|
||||||
<spring-cloud-netflix.version>2.2.0.M3</spring-cloud-netflix.version>
|
<spring-cloud-netflix.version>2.2.7.RELEASE</spring-cloud-netflix.version>
|
||||||
|
|
||||||
<!-- Plugin versions -->
|
<!-- Plugin versions -->
|
||||||
<maven-compiler-plugin.version>3.6.1</maven-compiler-plugin.version>
|
|
||||||
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
|
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
|
||||||
<!-- Sonar -->
|
<!-- Sonar -->
|
||||||
<surefire.plugin.version>2.19.1</surefire.plugin.version>
|
<surefire.plugin.version>2.19.1</surefire.plugin.version>
|
||||||
@@ -42,6 +41,10 @@
|
|||||||
</properties>
|
</properties>
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>flatten-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-eclipse-plugin</artifactId>
|
<artifactId>maven-eclipse-plugin</artifactId>
|
||||||
@@ -64,7 +67,6 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>${maven-compiler-plugin.version}</version>
|
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>1.8</source>
|
<source>1.8</source>
|
||||||
<target>1.8</target>
|
<target>1.8</target>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.cloud</groupId>
|
<groupId>org.springframework.cloud</groupId>
|
||||||
<artifactId>spring-cloud-openfeign</artifactId>
|
<artifactId>spring-cloud-openfeign</artifactId>
|
||||||
<version>2.2.0.M3</version>
|
<version>2.2.7.RELEASE</version>
|
||||||
<relativePath>..</relativePath> <!-- lookup parent from repository -->
|
<relativePath>..</relativePath> <!-- lookup parent from repository -->
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>spring-cloud-openfeign-core</artifactId>
|
<artifactId>spring-cloud-openfeign-core</artifactId>
|
||||||
@@ -123,11 +123,6 @@
|
|||||||
<artifactId>feign-okhttp</artifactId>
|
<artifactId>feign-okhttp</artifactId>
|
||||||
<optional>true</optional>
|
<optional>true</optional>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>io.github.openfeign</groupId>
|
|
||||||
<artifactId>feign-java8</artifactId>
|
|
||||||
<optional>true</optional>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.netflix.hystrix</groupId>
|
<groupId>com.netflix.hystrix</groupId>
|
||||||
<artifactId>hystrix-core</artifactId>
|
<artifactId>hystrix-core</artifactId>
|
||||||
@@ -222,15 +217,20 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.protobuf</groupId>
|
<groupId>com.google.protobuf</groupId>
|
||||||
<artifactId>protobuf-java</artifactId>
|
<artifactId>protobuf-java</artifactId>
|
||||||
<version>3.4.0</version>
|
<version>3.14.0</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.vavr</groupId>
|
<groupId>io.vavr</groupId>
|
||||||
<artifactId>vavr</artifactId>
|
<artifactId>vavr</artifactId>
|
||||||
<version>0.10.0</version>
|
<version>0.10.3</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-loadbalancer</artifactId>
|
||||||
|
<optional>true</optional>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<profiles>
|
<profiles>
|
||||||
<profile>
|
<profile>
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
|
|||||||
+41
@@ -0,0 +1,41 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates which collection format should be used while processing the annotated method.
|
||||||
|
*
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
|
* @see feign.CollectionFormat
|
||||||
|
*/
|
||||||
|
@Target(ElementType.METHOD)
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
public @interface CollectionFormat {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allows setting the {@link feign.CollectionFormat} to be used while processing the
|
||||||
|
* annotated method.
|
||||||
|
* @return the {@link feign.CollectionFormat} to be used
|
||||||
|
*/
|
||||||
|
feign.CollectionFormat value();
|
||||||
|
|
||||||
|
}
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2016-2019 the original author or authors.
|
* Copyright 2016-2020 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
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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.
|
||||||
|
|||||||
+87
@@ -0,0 +1,87 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
|
||||||
|
import static feign.Util.checkNotNull;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Used to control the fallback given its cause.
|
||||||
|
*
|
||||||
|
* Ex.
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* {@code
|
||||||
|
* // This instance will be invoked if there are errors of any kind.
|
||||||
|
* FallbackFactory<GitHub> fallbackFactory = cause -> (owner, repo) -> {
|
||||||
|
* if (cause instanceof FeignException && ((FeignException) cause).status() == 403) {
|
||||||
|
* return Collections.emptyList();
|
||||||
|
* } else {
|
||||||
|
* return Arrays.asList("yogi");
|
||||||
|
* }
|
||||||
|
* };
|
||||||
|
*
|
||||||
|
* GitHub github = FeignCircuitBreaker.builder()
|
||||||
|
* ...
|
||||||
|
* .target(GitHub.class, "https://api.github.com", fallbackFactory);
|
||||||
|
* }
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* @param <T> the feign interface type
|
||||||
|
*/
|
||||||
|
public interface FallbackFactory<T> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns an instance of the fallback appropriate for the given cause.
|
||||||
|
* @param cause cause of an exception.
|
||||||
|
* @return fallback
|
||||||
|
*/
|
||||||
|
T create(Throwable cause);
|
||||||
|
|
||||||
|
final class Default<T> implements FallbackFactory<T> {
|
||||||
|
|
||||||
|
final Log logger;
|
||||||
|
|
||||||
|
final T constant;
|
||||||
|
|
||||||
|
public Default(T constant) {
|
||||||
|
this(constant, LogFactory.getLog(Default.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
Default(T constant, Log logger) {
|
||||||
|
this.constant = checkNotNull(constant, "fallback");
|
||||||
|
this.logger = checkNotNull(logger, "logger");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public T create(Throwable cause) {
|
||||||
|
if (logger.isTraceEnabled()) {
|
||||||
|
logger.trace("fallback due to: " + cause.getMessage(), cause);
|
||||||
|
}
|
||||||
|
return constant;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return constant.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+79
-12
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -16,6 +16,7 @@
|
|||||||
|
|
||||||
package org.springframework.cloud.openfeign;
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Timer;
|
import java.util.Timer;
|
||||||
@@ -24,11 +25,14 @@ import java.util.concurrent.TimeUnit;
|
|||||||
|
|
||||||
import javax.annotation.PreDestroy;
|
import javax.annotation.PreDestroy;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.Module;
|
||||||
import feign.Client;
|
import feign.Client;
|
||||||
import feign.Feign;
|
import feign.Feign;
|
||||||
import feign.httpclient.ApacheHttpClient;
|
import feign.httpclient.ApacheHttpClient;
|
||||||
import feign.okhttp.OkHttpClient;
|
import feign.okhttp.OkHttpClient;
|
||||||
import okhttp3.ConnectionPool;
|
import okhttp3.ConnectionPool;
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
import org.apache.http.client.HttpClient;
|
import org.apache.http.client.HttpClient;
|
||||||
import org.apache.http.client.config.RequestConfig;
|
import org.apache.http.client.config.RequestConfig;
|
||||||
import org.apache.http.config.RegistryBuilder;
|
import org.apache.http.config.RegistryBuilder;
|
||||||
@@ -36,30 +40,44 @@ import org.apache.http.conn.HttpClientConnectionManager;
|
|||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
import org.springframework.cloud.client.actuator.HasFeatures;
|
import org.springframework.cloud.client.actuator.HasFeatures;
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
|
||||||
import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory;
|
import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory;
|
||||||
import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory;
|
import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory;
|
||||||
import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory;
|
import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory;
|
||||||
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
|
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
|
||||||
|
import org.springframework.cloud.openfeign.support.DefaultGzipDecoderConfiguration;
|
||||||
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
|
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
|
||||||
|
import org.springframework.cloud.openfeign.support.PageJacksonModule;
|
||||||
|
import org.springframework.cloud.openfeign.support.SortJacksonModule;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Spencer Gibb
|
* @author Spencer Gibb
|
||||||
* @author Julien Roy
|
* @author Julien Roy
|
||||||
|
* @author Grzegorz Poznachowski
|
||||||
|
* @author Nikita Konev
|
||||||
*/
|
*/
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
@ConditionalOnClass(Feign.class)
|
@ConditionalOnClass(Feign.class)
|
||||||
@EnableConfigurationProperties({ FeignClientProperties.class,
|
@EnableConfigurationProperties({ FeignClientProperties.class,
|
||||||
FeignHttpClientProperties.class })
|
FeignHttpClientProperties.class })
|
||||||
|
@Import(DefaultGzipDecoderConfiguration.class)
|
||||||
public class FeignAutoConfiguration {
|
public class FeignAutoConfiguration {
|
||||||
|
|
||||||
|
private static final Log LOG = LogFactory.getLog(FeignAutoConfiguration.class);
|
||||||
|
|
||||||
@Autowired(required = false)
|
@Autowired(required = false)
|
||||||
private List<FeignClientSpecification> configurations = new ArrayList<>();
|
private List<FeignClientSpecification> configurations = new ArrayList<>();
|
||||||
|
|
||||||
@@ -75,7 +93,40 @@ public class FeignAutoConfiguration {
|
|||||||
return context;
|
return context;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@ConditionalOnClass({ Module.class, Page.class, Sort.class })
|
||||||
|
@ConditionalOnProperty(value = "feign.autoconfiguration.jackson.enabled",
|
||||||
|
havingValue = "true")
|
||||||
|
protected static class FeignJacksonConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean(PageJacksonModule.class)
|
||||||
|
public PageJacksonModule pageJacksonModule() {
|
||||||
|
return new PageJacksonModule();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean(SortJacksonModule.class)
|
||||||
|
public SortJacksonModule sortModule() {
|
||||||
|
return new SortJacksonModule();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@ConditionalOnMissingClass({ "feign.hystrix.HystrixFeign",
|
||||||
|
"org.springframework.cloud.client.circuitbreaker.CircuitBreaker" })
|
||||||
|
protected static class DefaultFeignTargeterConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean
|
||||||
|
public Targeter feignTargeter() {
|
||||||
|
return new DefaultTargeter();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
@ConditionalOnClass(name = "feign.hystrix.HystrixFeign")
|
@ConditionalOnClass(name = "feign.hystrix.HystrixFeign")
|
||||||
protected static class HystrixFeignTargeterConfiguration {
|
protected static class HystrixFeignTargeterConfiguration {
|
||||||
|
|
||||||
@@ -87,14 +138,23 @@ public class FeignAutoConfiguration {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
@ConditionalOnMissingClass("feign.hystrix.HystrixFeign")
|
@ConditionalOnClass(CircuitBreaker.class)
|
||||||
protected static class DefaultFeignTargeterConfiguration {
|
@ConditionalOnProperty("feign.circuitbreaker.enabled")
|
||||||
|
protected static class CircuitBreakerPresentFeignTargeterConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean(CircuitBreakerFactory.class)
|
||||||
|
public Targeter defaultFeignTargeter() {
|
||||||
|
return new DefaultTargeter();
|
||||||
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public Targeter feignTargeter() {
|
@ConditionalOnBean(CircuitBreakerFactory.class)
|
||||||
return new DefaultTargeter();
|
public Targeter circuitBreakerFeignTargeter(
|
||||||
|
CircuitBreakerFactory circuitBreakerFactory) {
|
||||||
|
return new FeignCircuitBreakerTargeter(circuitBreakerFactory);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -103,7 +163,7 @@ public class FeignAutoConfiguration {
|
|||||||
// ribbon is not on the class path.
|
// ribbon is not on the class path.
|
||||||
// see corresponding configurations in FeignRibbonClientAutoConfiguration
|
// see corresponding configurations in FeignRibbonClientAutoConfiguration
|
||||||
// for load balanced ribbon clients.
|
// for load balanced ribbon clients.
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
@ConditionalOnClass(ApacheHttpClient.class)
|
@ConditionalOnClass(ApacheHttpClient.class)
|
||||||
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
|
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
|
||||||
@ConditionalOnMissingBean(CloseableHttpClient.class)
|
@ConditionalOnMissingBean(CloseableHttpClient.class)
|
||||||
@@ -160,16 +220,23 @@ public class FeignAutoConfiguration {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PreDestroy
|
@PreDestroy
|
||||||
public void destroy() throws Exception {
|
public void destroy() {
|
||||||
this.connectionManagerTimer.cancel();
|
this.connectionManagerTimer.cancel();
|
||||||
if (this.httpClient != null) {
|
if (this.httpClient != null) {
|
||||||
this.httpClient.close();
|
try {
|
||||||
|
this.httpClient.close();
|
||||||
|
}
|
||||||
|
catch (IOException e) {
|
||||||
|
if (LOG.isErrorEnabled()) {
|
||||||
|
LOG.error("Could not correctly close httpClient.");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
@ConditionalOnClass(OkHttpClient.class)
|
@ConditionalOnClass(OkHttpClient.class)
|
||||||
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
|
@ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
|
||||||
@ConditionalOnMissingBean(okhttp3.OkHttpClient.class)
|
@ConditionalOnMissingBean(okhttp3.OkHttpClient.class)
|
||||||
|
|||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2019 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import feign.Feign;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allows application to customize the Feign builder.
|
||||||
|
*
|
||||||
|
* @author Matt King
|
||||||
|
*/
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface FeignBuilderCustomizer {
|
||||||
|
|
||||||
|
void customize(Feign.Builder builder);
|
||||||
|
|
||||||
|
}
|
||||||
+89
@@ -0,0 +1,89 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import feign.Feign;
|
||||||
|
import feign.Target;
|
||||||
|
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allows Feign interfaces to work with {@link CircuitBreaker}.
|
||||||
|
*
|
||||||
|
* @author Marcin Grzejszczak
|
||||||
|
* @since 3.0.0
|
||||||
|
*/
|
||||||
|
public final class FeignCircuitBreaker {
|
||||||
|
|
||||||
|
private FeignCircuitBreaker() {
|
||||||
|
throw new IllegalStateException("Don't instantiate a utility class");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return builder for Feign CircuitBreaker integration
|
||||||
|
*/
|
||||||
|
public static Builder builder() {
|
||||||
|
return new Builder();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builder for Feign CircuitBreaker integration.
|
||||||
|
*/
|
||||||
|
public static final class Builder extends Feign.Builder {
|
||||||
|
|
||||||
|
private CircuitBreakerFactory circuitBreakerFactory;
|
||||||
|
|
||||||
|
private String feignClientName;
|
||||||
|
|
||||||
|
Builder circuitBreakerFactory(CircuitBreakerFactory circuitBreakerFactory) {
|
||||||
|
this.circuitBreakerFactory = circuitBreakerFactory;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
Builder feignClientName(String feignClientName) {
|
||||||
|
this.feignClientName = feignClientName;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> T target(Target<T> target, T fallback) {
|
||||||
|
return build(
|
||||||
|
fallback != null ? new FallbackFactory.Default<T>(fallback) : null)
|
||||||
|
.newInstance(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> T target(Target<T> target,
|
||||||
|
FallbackFactory<? extends T> fallbackFactory) {
|
||||||
|
return build(fallbackFactory).newInstance(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> T target(Target<T> target) {
|
||||||
|
return build(null).newInstance(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Feign build(final FallbackFactory<?> nullableFallbackFactory) {
|
||||||
|
super.invocationHandlerFactory(
|
||||||
|
(target, dispatch) -> new FeignCircuitBreakerInvocationHandler(
|
||||||
|
circuitBreakerFactory, feignClientName, target, dispatch,
|
||||||
|
nullableFallbackFactory));
|
||||||
|
return super.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+40
@@ -0,0 +1,40 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
|
||||||
|
class FeignCircuitBreakerDisabledConditions extends AnyNestedCondition {
|
||||||
|
|
||||||
|
FeignCircuitBreakerDisabledConditions() {
|
||||||
|
super(ConfigurationPhase.PARSE_CONFIGURATION);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ConditionalOnMissingClass("org.springframework.cloud.client.circuitbreaker.CircuitBreaker")
|
||||||
|
static class CircuitBreakerClassMissing {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@ConditionalOnProperty(value = "feign.circuitbreaker.enabled", havingValue = "false",
|
||||||
|
matchIfMissing = true)
|
||||||
|
static class CircuitBreakerDisabled {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+152
@@ -0,0 +1,152 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationHandler;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.lang.reflect.Proxy;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
import feign.InvocationHandlerFactory;
|
||||||
|
import feign.Target;
|
||||||
|
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
|
||||||
|
|
||||||
|
import static feign.Util.checkNotNull;
|
||||||
|
|
||||||
|
class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
|
||||||
|
|
||||||
|
private final CircuitBreakerFactory factory;
|
||||||
|
|
||||||
|
private final String feignClientName;
|
||||||
|
|
||||||
|
private final Target<?> target;
|
||||||
|
|
||||||
|
private final Map<Method, InvocationHandlerFactory.MethodHandler> dispatch;
|
||||||
|
|
||||||
|
private final FallbackFactory<?> nullableFallbackFactory;
|
||||||
|
|
||||||
|
private final Map<Method, Method> fallbackMethodMap;
|
||||||
|
|
||||||
|
FeignCircuitBreakerInvocationHandler(CircuitBreakerFactory factory,
|
||||||
|
String feignClientName, Target<?> target,
|
||||||
|
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch,
|
||||||
|
FallbackFactory<?> nullableFallbackFactory) {
|
||||||
|
this.factory = factory;
|
||||||
|
this.feignClientName = feignClientName;
|
||||||
|
this.target = checkNotNull(target, "target");
|
||||||
|
this.dispatch = checkNotNull(dispatch, "dispatch");
|
||||||
|
this.fallbackMethodMap = toFallbackMethod(dispatch);
|
||||||
|
this.nullableFallbackFactory = nullableFallbackFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object invoke(final Object proxy, final Method method, final Object[] args)
|
||||||
|
throws Throwable {
|
||||||
|
// early exit if the invoked method is from java.lang.Object
|
||||||
|
// code is the same as ReflectiveFeign.FeignInvocationHandler
|
||||||
|
if ("equals".equals(method.getName())) {
|
||||||
|
try {
|
||||||
|
Object otherHandler = args.length > 0 && args[0] != null
|
||||||
|
? Proxy.getInvocationHandler(args[0]) : null;
|
||||||
|
return equals(otherHandler);
|
||||||
|
}
|
||||||
|
catch (IllegalArgumentException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if ("hashCode".equals(method.getName())) {
|
||||||
|
return hashCode();
|
||||||
|
}
|
||||||
|
else if ("toString".equals(method.getName())) {
|
||||||
|
return toString();
|
||||||
|
}
|
||||||
|
String circuitName = this.feignClientName + "_" + method.getName();
|
||||||
|
CircuitBreaker circuitBreaker = this.factory.create(circuitName);
|
||||||
|
Supplier<Object> supplier = asSupplier(method, args);
|
||||||
|
if (this.nullableFallbackFactory != null) {
|
||||||
|
Function<Throwable, Object> fallbackFunction = throwable -> {
|
||||||
|
Object fallback = this.nullableFallbackFactory.create(throwable);
|
||||||
|
try {
|
||||||
|
return this.fallbackMethodMap.get(method).invoke(fallback, args);
|
||||||
|
}
|
||||||
|
catch (Exception e) {
|
||||||
|
throw new IllegalStateException(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return circuitBreaker.run(supplier, fallbackFunction);
|
||||||
|
}
|
||||||
|
return circuitBreaker.run(supplier);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Supplier<Object> asSupplier(final Method method, final Object[] args) {
|
||||||
|
return () -> {
|
||||||
|
try {
|
||||||
|
return this.dispatch.get(method).invoke(args);
|
||||||
|
}
|
||||||
|
catch (RuntimeException throwable) {
|
||||||
|
throw throwable;
|
||||||
|
}
|
||||||
|
catch (Throwable throwable) {
|
||||||
|
throw new RuntimeException(throwable);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If the method param of InvocationHandler.invoke is not accessible, i.e in a
|
||||||
|
* package-private interface, the fallback call will cause of access restrictions. But
|
||||||
|
* methods in dispatch are copied methods. So setting access to dispatch method
|
||||||
|
* doesn't take effect to the method in InvocationHandler.invoke. Use map to store a
|
||||||
|
* copy of method to invoke the fallback to bypass this and reducing the count of
|
||||||
|
* reflection calls.
|
||||||
|
* @return cached methods map for fallback invoking
|
||||||
|
*/
|
||||||
|
static Map<Method, Method> toFallbackMethod(
|
||||||
|
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch) {
|
||||||
|
Map<Method, Method> result = new LinkedHashMap<Method, Method>();
|
||||||
|
for (Method method : dispatch.keySet()) {
|
||||||
|
method.setAccessible(true);
|
||||||
|
result.put(method, method);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (obj instanceof FeignCircuitBreakerInvocationHandler) {
|
||||||
|
FeignCircuitBreakerInvocationHandler other = (FeignCircuitBreakerInvocationHandler) obj;
|
||||||
|
return this.target.equals(other.target);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return this.target.hashCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return this.target.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+97
@@ -0,0 +1,97 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import feign.Feign;
|
||||||
|
import feign.Target;
|
||||||
|
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
class FeignCircuitBreakerTargeter implements Targeter {
|
||||||
|
|
||||||
|
private final CircuitBreakerFactory circuitBreakerFactory;
|
||||||
|
|
||||||
|
FeignCircuitBreakerTargeter(CircuitBreakerFactory circuitBreakerFactory) {
|
||||||
|
this.circuitBreakerFactory = circuitBreakerFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign,
|
||||||
|
FeignContext context, Target.HardCodedTarget<T> target) {
|
||||||
|
if (!(feign instanceof FeignCircuitBreaker.Builder)) {
|
||||||
|
return feign.target(target);
|
||||||
|
}
|
||||||
|
FeignCircuitBreaker.Builder builder = (FeignCircuitBreaker.Builder) feign;
|
||||||
|
String name = !StringUtils.hasText(factory.getContextId()) ? factory.getName()
|
||||||
|
: factory.getContextId();
|
||||||
|
Class<?> fallback = factory.getFallback();
|
||||||
|
if (fallback != void.class) {
|
||||||
|
return targetWithFallback(name, context, target, builder, fallback);
|
||||||
|
}
|
||||||
|
Class<?> fallbackFactory = factory.getFallbackFactory();
|
||||||
|
if (fallbackFactory != void.class) {
|
||||||
|
return targetWithFallbackFactory(name, context, target, builder,
|
||||||
|
fallbackFactory);
|
||||||
|
}
|
||||||
|
return builder(name, builder).target(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T targetWithFallbackFactory(String feignClientName, FeignContext context,
|
||||||
|
Target.HardCodedTarget<T> target, FeignCircuitBreaker.Builder builder,
|
||||||
|
Class<?> fallbackFactoryClass) {
|
||||||
|
FallbackFactory<? extends T> fallbackFactory = (FallbackFactory<? extends T>) getFromContext(
|
||||||
|
"fallbackFactory", feignClientName, context, fallbackFactoryClass,
|
||||||
|
FallbackFactory.class);
|
||||||
|
return builder(feignClientName, builder).target(target, fallbackFactory);
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T targetWithFallback(String feignClientName, FeignContext context,
|
||||||
|
Target.HardCodedTarget<T> target, FeignCircuitBreaker.Builder builder,
|
||||||
|
Class<?> fallback) {
|
||||||
|
T fallbackInstance = getFromContext("fallback", feignClientName, context,
|
||||||
|
fallback, target.type());
|
||||||
|
return builder(feignClientName, builder).target(target, fallbackInstance);
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T getFromContext(String fallbackMechanism, String feignClientName,
|
||||||
|
FeignContext context, Class<?> beanType, Class<T> targetType) {
|
||||||
|
Object fallbackInstance = context.getInstance(feignClientName, beanType);
|
||||||
|
if (fallbackInstance == null) {
|
||||||
|
throw new IllegalStateException(String.format(
|
||||||
|
"No " + fallbackMechanism
|
||||||
|
+ " instance of type %s found for feign client %s",
|
||||||
|
beanType, feignClientName));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!targetType.isAssignableFrom(beanType)) {
|
||||||
|
throw new IllegalStateException(String.format("Incompatible "
|
||||||
|
+ fallbackMechanism
|
||||||
|
+ " instance. Fallback/fallbackFactory of type %s is not assignable to %s for feign client %s",
|
||||||
|
beanType, targetType, feignClientName));
|
||||||
|
}
|
||||||
|
return (T) fallbackInstance;
|
||||||
|
}
|
||||||
|
|
||||||
|
private FeignCircuitBreaker.Builder builder(String feignClientName,
|
||||||
|
FeignCircuitBreaker.Builder builder) {
|
||||||
|
return builder.circuitBreakerFactory(this.circuitBreakerFactory)
|
||||||
|
.feignClientName(feignClientName);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+5
-2
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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,6 +18,7 @@ package org.springframework.cloud.openfeign;
|
|||||||
|
|
||||||
import java.lang.annotation.Documented;
|
import java.lang.annotation.Documented;
|
||||||
import java.lang.annotation.ElementType;
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Inherited;
|
||||||
import java.lang.annotation.Retention;
|
import java.lang.annotation.Retention;
|
||||||
import java.lang.annotation.RetentionPolicy;
|
import java.lang.annotation.RetentionPolicy;
|
||||||
import java.lang.annotation.Target;
|
import java.lang.annotation.Target;
|
||||||
@@ -36,6 +37,7 @@ import org.springframework.core.annotation.AliasFor;
|
|||||||
@Target(ElementType.TYPE)
|
@Target(ElementType.TYPE)
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
@Documented
|
@Documented
|
||||||
|
@Inherited
|
||||||
public @interface FeignClient {
|
public @interface FeignClient {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -85,7 +87,7 @@ public @interface FeignClient {
|
|||||||
boolean decode404() default false;
|
boolean decode404() default false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A custom <code>@Configuration</code> for the feign client. Can contain override
|
* A custom configuration class for the feign client. Can contain override
|
||||||
* <code>@Bean</code> definition for the pieces that make up the client, for instance
|
* <code>@Bean</code> definition for the pieces that make up the client, for instance
|
||||||
* {@link feign.codec.Decoder}, {@link feign.codec.Encoder}, {@link feign.Contract}.
|
* {@link feign.codec.Decoder}, {@link feign.codec.Encoder}, {@link feign.Contract}.
|
||||||
*
|
*
|
||||||
@@ -107,6 +109,7 @@ public @interface FeignClient {
|
|||||||
* annotated by {@link FeignClient}. The fallback factory must be a valid spring bean.
|
* annotated by {@link FeignClient}. The fallback factory must be a valid spring bean.
|
||||||
*
|
*
|
||||||
* @see feign.hystrix.FallbackFactory for details.
|
* @see feign.hystrix.FallbackFactory for details.
|
||||||
|
* @see FallbackFactory for details.
|
||||||
* @return fallback factory for the specified Feign client interface
|
* @return fallback factory for the specified Feign client interface
|
||||||
*/
|
*/
|
||||||
Class<?> fallbackFactory() default void.class;
|
Class<?> fallbackFactory() default void.class;
|
||||||
|
|||||||
+8
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -27,6 +27,7 @@ import org.springframework.context.ApplicationContext;
|
|||||||
* {@link FeignClient} annotation.
|
* {@link FeignClient} annotation.
|
||||||
*
|
*
|
||||||
* @author Sven Döring
|
* @author Sven Döring
|
||||||
|
* @author Matt King
|
||||||
*/
|
*/
|
||||||
public class FeignClientBuilder {
|
public class FeignClientBuilder {
|
||||||
|
|
||||||
@@ -57,6 +58,7 @@ public class FeignClientBuilder {
|
|||||||
this.feignClientFactoryBean.setType(type);
|
this.feignClientFactoryBean.setType(type);
|
||||||
this.feignClientFactoryBean.setName(FeignClientsRegistrar.getName(name));
|
this.feignClientFactoryBean.setName(FeignClientsRegistrar.getName(name));
|
||||||
this.feignClientFactoryBean.setContextId(FeignClientsRegistrar.getName(name));
|
this.feignClientFactoryBean.setContextId(FeignClientsRegistrar.getName(name));
|
||||||
|
this.feignClientFactoryBean.setInheritParentContext(true);
|
||||||
// preset default values - these values resemble the default values on the
|
// preset default values - these values resemble the default values on the
|
||||||
// FeignClient annotation
|
// FeignClient annotation
|
||||||
this.url("").path("").decode404(false);
|
this.url("").path("").decode404(false);
|
||||||
@@ -82,6 +84,11 @@ public class FeignClientBuilder {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Builder<T> inheritParentContext(final boolean inheritParentContext) {
|
||||||
|
this.feignClientFactoryBean.setInheritParentContext(inheritParentContext);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
public Builder<T> fallback(final Class<? extends T> fallback) {
|
public Builder<T> fallback(final Class<? extends T> fallback) {
|
||||||
FeignClientsRegistrar.validateFallback(fallback);
|
FeignClientsRegistrar.validateFallback(fallback);
|
||||||
this.feignClientFactoryBean.setFallback(fallback);
|
this.feignClientFactoryBean.setFallback(fallback);
|
||||||
|
|||||||
+190
-71
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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,11 +16,15 @@
|
|||||||
|
|
||||||
package org.springframework.cloud.openfeign;
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import feign.Client;
|
import feign.Client;
|
||||||
import feign.Contract;
|
import feign.Contract;
|
||||||
|
import feign.ExceptionPropagationPolicy;
|
||||||
import feign.Feign;
|
import feign.Feign;
|
||||||
import feign.Logger;
|
import feign.Logger;
|
||||||
import feign.QueryMapEncoder;
|
import feign.QueryMapEncoder;
|
||||||
@@ -34,12 +38,17 @@ import feign.codec.ErrorDecoder;
|
|||||||
|
|
||||||
import org.springframework.beans.BeanUtils;
|
import org.springframework.beans.BeanUtils;
|
||||||
import org.springframework.beans.BeansException;
|
import org.springframework.beans.BeansException;
|
||||||
|
import org.springframework.beans.factory.BeanFactory;
|
||||||
|
import org.springframework.beans.factory.BeanFactoryAware;
|
||||||
import org.springframework.beans.factory.FactoryBean;
|
import org.springframework.beans.factory.FactoryBean;
|
||||||
import org.springframework.beans.factory.InitializingBean;
|
import org.springframework.beans.factory.InitializingBean;
|
||||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||||
|
import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer;
|
||||||
|
import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient;
|
||||||
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
|
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
|
||||||
import org.springframework.context.ApplicationContext;
|
import org.springframework.context.ApplicationContext;
|
||||||
import org.springframework.context.ApplicationContextAware;
|
import org.springframework.context.ApplicationContextAware;
|
||||||
|
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
@@ -48,9 +57,13 @@ import org.springframework.util.StringUtils;
|
|||||||
* @author Venil Noronha
|
* @author Venil Noronha
|
||||||
* @author Eko Kurniawan Khannedy
|
* @author Eko Kurniawan Khannedy
|
||||||
* @author Gregor Zurowski
|
* @author Gregor Zurowski
|
||||||
|
* @author Matt King
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
|
* @author Ilia Ilinykh
|
||||||
|
* @author Marcin Grzejszczak
|
||||||
*/
|
*/
|
||||||
class FeignClientFactoryBean
|
public class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean,
|
||||||
implements FactoryBean<Object>, InitializingBean, ApplicationContextAware {
|
ApplicationContextAware, BeanFactoryAware {
|
||||||
|
|
||||||
/***********************************
|
/***********************************
|
||||||
* WARNING! Nothing in this class should be @Autowired. It causes NPEs because of some
|
* WARNING! Nothing in this class should be @Autowired. It causes NPEs because of some
|
||||||
@@ -69,21 +82,29 @@ class FeignClientFactoryBean
|
|||||||
|
|
||||||
private boolean decode404;
|
private boolean decode404;
|
||||||
|
|
||||||
|
private boolean inheritParentContext = true;
|
||||||
|
|
||||||
private ApplicationContext applicationContext;
|
private ApplicationContext applicationContext;
|
||||||
|
|
||||||
|
private BeanFactory beanFactory;
|
||||||
|
|
||||||
private Class<?> fallback = void.class;
|
private Class<?> fallback = void.class;
|
||||||
|
|
||||||
private Class<?> fallbackFactory = void.class;
|
private Class<?> fallbackFactory = void.class;
|
||||||
|
|
||||||
|
private int readTimeoutMillis = new Request.Options().readTimeoutMillis();
|
||||||
|
|
||||||
|
private int connectTimeoutMillis = new Request.Options().connectTimeoutMillis();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void afterPropertiesSet() throws Exception {
|
public void afterPropertiesSet() {
|
||||||
Assert.hasText(this.contextId, "Context id must be set");
|
Assert.hasText(contextId, "Context id must be set");
|
||||||
Assert.hasText(this.name, "Name must be set");
|
Assert.hasText(name, "Name must be set");
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Feign.Builder feign(FeignContext context) {
|
protected Feign.Builder feign(FeignContext context) {
|
||||||
FeignLoggerFactory loggerFactory = get(context, FeignLoggerFactory.class);
|
FeignLoggerFactory loggerFactory = get(context, FeignLoggerFactory.class);
|
||||||
Logger logger = loggerFactory.create(this.type);
|
Logger logger = loggerFactory.create(type);
|
||||||
|
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
Feign.Builder builder = get(context, Feign.Builder.class)
|
Feign.Builder builder = get(context, Feign.Builder.class)
|
||||||
@@ -95,28 +116,45 @@ class FeignClientFactoryBean
|
|||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
configureFeign(context, builder);
|
configureFeign(context, builder);
|
||||||
|
applyBuildCustomizers(context, builder);
|
||||||
|
|
||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void applyBuildCustomizers(FeignContext context, Feign.Builder builder) {
|
||||||
|
Map<String, FeignBuilderCustomizer> customizerMap = context
|
||||||
|
.getInstances(contextId, FeignBuilderCustomizer.class);
|
||||||
|
|
||||||
|
if (customizerMap != null) {
|
||||||
|
customizerMap.values().stream()
|
||||||
|
.sorted(AnnotationAwareOrderComparator.INSTANCE)
|
||||||
|
.forEach(feignBuilderCustomizer -> feignBuilderCustomizer
|
||||||
|
.customize(builder));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
protected void configureFeign(FeignContext context, Feign.Builder builder) {
|
protected void configureFeign(FeignContext context, Feign.Builder builder) {
|
||||||
FeignClientProperties properties = this.applicationContext
|
FeignClientProperties properties = beanFactory != null
|
||||||
.getBean(FeignClientProperties.class);
|
? beanFactory.getBean(FeignClientProperties.class)
|
||||||
if (properties != null) {
|
: applicationContext.getBean(FeignClientProperties.class);
|
||||||
|
|
||||||
|
FeignClientConfigurer feignClientConfigurer = getOptional(context,
|
||||||
|
FeignClientConfigurer.class);
|
||||||
|
setInheritParentContext(feignClientConfigurer.inheritParentConfiguration());
|
||||||
|
|
||||||
|
if (properties != null && inheritParentContext) {
|
||||||
if (properties.isDefaultToProperties()) {
|
if (properties.isDefaultToProperties()) {
|
||||||
configureUsingConfiguration(context, builder);
|
configureUsingConfiguration(context, builder);
|
||||||
configureUsingProperties(
|
configureUsingProperties(
|
||||||
properties.getConfig().get(properties.getDefaultConfig()),
|
properties.getConfig().get(properties.getDefaultConfig()),
|
||||||
builder);
|
builder);
|
||||||
configureUsingProperties(properties.getConfig().get(this.contextId),
|
configureUsingProperties(properties.getConfig().get(contextId), builder);
|
||||||
builder);
|
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
configureUsingProperties(
|
configureUsingProperties(
|
||||||
properties.getConfig().get(properties.getDefaultConfig()),
|
properties.getConfig().get(properties.getDefaultConfig()),
|
||||||
builder);
|
builder);
|
||||||
configureUsingProperties(properties.getConfig().get(this.contextId),
|
configureUsingProperties(properties.getConfig().get(contextId), builder);
|
||||||
builder);
|
|
||||||
configureUsingConfiguration(context, builder);
|
configureUsingConfiguration(context, builder);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -127,34 +165,55 @@ class FeignClientFactoryBean
|
|||||||
|
|
||||||
protected void configureUsingConfiguration(FeignContext context,
|
protected void configureUsingConfiguration(FeignContext context,
|
||||||
Feign.Builder builder) {
|
Feign.Builder builder) {
|
||||||
Logger.Level level = getOptional(context, Logger.Level.class);
|
Logger.Level level = getInheritedAwareOptional(context, Logger.Level.class);
|
||||||
if (level != null) {
|
if (level != null) {
|
||||||
builder.logLevel(level);
|
builder.logLevel(level);
|
||||||
}
|
}
|
||||||
Retryer retryer = getOptional(context, Retryer.class);
|
Retryer retryer = getInheritedAwareOptional(context, Retryer.class);
|
||||||
if (retryer != null) {
|
if (retryer != null) {
|
||||||
builder.retryer(retryer);
|
builder.retryer(retryer);
|
||||||
}
|
}
|
||||||
ErrorDecoder errorDecoder = getOptional(context, ErrorDecoder.class);
|
ErrorDecoder errorDecoder = getInheritedAwareOptional(context,
|
||||||
|
ErrorDecoder.class);
|
||||||
if (errorDecoder != null) {
|
if (errorDecoder != null) {
|
||||||
builder.errorDecoder(errorDecoder);
|
builder.errorDecoder(errorDecoder);
|
||||||
}
|
}
|
||||||
Request.Options options = getOptional(context, Request.Options.class);
|
else {
|
||||||
|
FeignErrorDecoderFactory errorDecoderFactory = getOptional(context,
|
||||||
|
FeignErrorDecoderFactory.class);
|
||||||
|
if (errorDecoderFactory != null) {
|
||||||
|
ErrorDecoder factoryErrorDecoder = errorDecoderFactory.create(type);
|
||||||
|
builder.errorDecoder(factoryErrorDecoder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Request.Options options = getInheritedAwareOptional(context,
|
||||||
|
Request.Options.class);
|
||||||
if (options != null) {
|
if (options != null) {
|
||||||
builder.options(options);
|
builder.options(options);
|
||||||
|
readTimeoutMillis = options.readTimeoutMillis();
|
||||||
|
connectTimeoutMillis = options.connectTimeoutMillis();
|
||||||
}
|
}
|
||||||
Map<String, RequestInterceptor> requestInterceptors = context
|
Map<String, RequestInterceptor> requestInterceptors = getInheritedAwareInstances(
|
||||||
.getInstances(this.contextId, RequestInterceptor.class);
|
context, RequestInterceptor.class);
|
||||||
if (requestInterceptors != null) {
|
if (requestInterceptors != null) {
|
||||||
builder.requestInterceptors(requestInterceptors.values());
|
List<RequestInterceptor> interceptors = new ArrayList<>(
|
||||||
|
requestInterceptors.values());
|
||||||
|
AnnotationAwareOrderComparator.sort(interceptors);
|
||||||
|
builder.requestInterceptors(interceptors);
|
||||||
}
|
}
|
||||||
QueryMapEncoder queryMapEncoder = getOptional(context, QueryMapEncoder.class);
|
QueryMapEncoder queryMapEncoder = getInheritedAwareOptional(context,
|
||||||
|
QueryMapEncoder.class);
|
||||||
if (queryMapEncoder != null) {
|
if (queryMapEncoder != null) {
|
||||||
builder.queryMapEncoder(queryMapEncoder);
|
builder.queryMapEncoder(queryMapEncoder);
|
||||||
}
|
}
|
||||||
if (this.decode404) {
|
if (decode404) {
|
||||||
builder.decode404();
|
builder.decode404();
|
||||||
}
|
}
|
||||||
|
ExceptionPropagationPolicy exceptionPropagationPolicy = getInheritedAwareOptional(
|
||||||
|
context, ExceptionPropagationPolicy.class);
|
||||||
|
if (exceptionPropagationPolicy != null) {
|
||||||
|
builder.exceptionPropagationPolicy(exceptionPropagationPolicy);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void configureUsingProperties(
|
protected void configureUsingProperties(
|
||||||
@@ -168,10 +227,13 @@ class FeignClientFactoryBean
|
|||||||
builder.logLevel(config.getLoggerLevel());
|
builder.logLevel(config.getLoggerLevel());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (config.getConnectTimeout() != null && config.getReadTimeout() != null) {
|
connectTimeoutMillis = config.getConnectTimeout() != null
|
||||||
builder.options(new Request.Options(config.getConnectTimeout(),
|
? config.getConnectTimeout() : connectTimeoutMillis;
|
||||||
config.getReadTimeout()));
|
readTimeoutMillis = config.getReadTimeout() != null ? config.getReadTimeout()
|
||||||
}
|
: readTimeoutMillis;
|
||||||
|
|
||||||
|
builder.options(new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS,
|
||||||
|
readTimeoutMillis, TimeUnit.MILLISECONDS, true));
|
||||||
|
|
||||||
if (config.getRetryer() != null) {
|
if (config.getRetryer() != null) {
|
||||||
Retryer retryer = getOrInstantiate(config.getRetryer());
|
Retryer retryer = getOrInstantiate(config.getRetryer());
|
||||||
@@ -202,6 +264,16 @@ class FeignClientFactoryBean
|
|||||||
builder.encoder(getOrInstantiate(config.getEncoder()));
|
builder.encoder(getOrInstantiate(config.getEncoder()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (Objects.nonNull(config.getDefaultRequestHeaders())) {
|
||||||
|
builder.requestInterceptor(requestTemplate -> requestTemplate
|
||||||
|
.headers(config.getDefaultRequestHeaders()));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Objects.nonNull(config.getDefaultQueryParameters())) {
|
||||||
|
builder.requestInterceptor(requestTemplate -> requestTemplate
|
||||||
|
.queries(config.getDefaultQueryParameters()));
|
||||||
|
}
|
||||||
|
|
||||||
if (Objects.nonNull(config.getDecoder())) {
|
if (Objects.nonNull(config.getDecoder())) {
|
||||||
builder.decoder(getOrInstantiate(config.getDecoder()));
|
builder.decoder(getOrInstantiate(config.getDecoder()));
|
||||||
}
|
}
|
||||||
@@ -209,11 +281,16 @@ class FeignClientFactoryBean
|
|||||||
if (Objects.nonNull(config.getContract())) {
|
if (Objects.nonNull(config.getContract())) {
|
||||||
builder.contract(getOrInstantiate(config.getContract()));
|
builder.contract(getOrInstantiate(config.getContract()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (Objects.nonNull(config.getExceptionPropagationPolicy())) {
|
||||||
|
builder.exceptionPropagationPolicy(config.getExceptionPropagationPolicy());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private <T> T getOrInstantiate(Class<T> tClass) {
|
private <T> T getOrInstantiate(Class<T> tClass) {
|
||||||
try {
|
try {
|
||||||
return this.applicationContext.getBean(tClass);
|
return beanFactory != null ? beanFactory.getBean(tClass)
|
||||||
|
: applicationContext.getBean(tClass);
|
||||||
}
|
}
|
||||||
catch (NoSuchBeanDefinitionException e) {
|
catch (NoSuchBeanDefinitionException e) {
|
||||||
return BeanUtils.instantiateClass(tClass);
|
return BeanUtils.instantiateClass(tClass);
|
||||||
@@ -221,16 +298,35 @@ class FeignClientFactoryBean
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected <T> T get(FeignContext context, Class<T> type) {
|
protected <T> T get(FeignContext context, Class<T> type) {
|
||||||
T instance = context.getInstance(this.contextId, type);
|
T instance = context.getInstance(contextId, type);
|
||||||
if (instance == null) {
|
if (instance == null) {
|
||||||
throw new IllegalStateException(
|
throw new IllegalStateException(
|
||||||
"No bean found of type " + type + " for " + this.contextId);
|
"No bean found of type " + type + " for " + contextId);
|
||||||
}
|
}
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected <T> T getOptional(FeignContext context, Class<T> type) {
|
protected <T> T getOptional(FeignContext context, Class<T> type) {
|
||||||
return context.getInstance(this.contextId, type);
|
return context.getInstance(contextId, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected <T> T getInheritedAwareOptional(FeignContext context, Class<T> type) {
|
||||||
|
if (inheritParentContext) {
|
||||||
|
return getOptional(context, type);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return context.getInstanceWithoutAncestors(contextId, type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected <T> Map<String, T> getInheritedAwareInstances(FeignContext context,
|
||||||
|
Class<T> type) {
|
||||||
|
if (inheritParentContext) {
|
||||||
|
return context.getInstances(contextId, type);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return context.getInstancesWithoutAncestors(contextId, type);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected <T> T loadBalance(Feign.Builder builder, FeignContext context,
|
protected <T> T loadBalance(Feign.Builder builder, FeignContext context,
|
||||||
@@ -247,7 +343,7 @@ class FeignClientFactoryBean
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object getObject() throws Exception {
|
public Object getObject() {
|
||||||
return getTarget();
|
return getTarget();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -257,22 +353,24 @@ class FeignClientFactoryBean
|
|||||||
* information
|
* information
|
||||||
*/
|
*/
|
||||||
<T> T getTarget() {
|
<T> T getTarget() {
|
||||||
FeignContext context = this.applicationContext.getBean(FeignContext.class);
|
FeignContext context = beanFactory != null
|
||||||
|
? beanFactory.getBean(FeignContext.class)
|
||||||
|
: applicationContext.getBean(FeignContext.class);
|
||||||
Feign.Builder builder = feign(context);
|
Feign.Builder builder = feign(context);
|
||||||
|
|
||||||
if (!StringUtils.hasText(this.url)) {
|
if (!StringUtils.hasText(url)) {
|
||||||
if (!this.name.startsWith("http")) {
|
if (!name.startsWith("http")) {
|
||||||
this.url = "http://" + this.name;
|
url = "http://" + name;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
this.url = this.name;
|
url = name;
|
||||||
}
|
}
|
||||||
this.url += cleanPath();
|
url += cleanPath();
|
||||||
return (T) loadBalance(builder, context,
|
return (T) loadBalance(builder, context,
|
||||||
new HardCodedTarget<>(this.type, this.name, this.url));
|
new HardCodedTarget<>(type, name, url));
|
||||||
}
|
}
|
||||||
if (StringUtils.hasText(this.url) && !this.url.startsWith("http")) {
|
if (StringUtils.hasText(url) && !url.startsWith("http")) {
|
||||||
this.url = "http://" + this.url;
|
url = "http://" + url;
|
||||||
}
|
}
|
||||||
String url = this.url + cleanPath();
|
String url = this.url + cleanPath();
|
||||||
Client client = getOptional(context, Client.class);
|
Client client = getOptional(context, Client.class);
|
||||||
@@ -282,11 +380,16 @@ class FeignClientFactoryBean
|
|||||||
// but ribbon is on the classpath, so unwrap
|
// but ribbon is on the classpath, so unwrap
|
||||||
client = ((LoadBalancerFeignClient) client).getDelegate();
|
client = ((LoadBalancerFeignClient) client).getDelegate();
|
||||||
}
|
}
|
||||||
|
if (client instanceof FeignBlockingLoadBalancerClient) {
|
||||||
|
// not load balancing because we have a url,
|
||||||
|
// but Spring Cloud LoadBalancer is on the classpath, so unwrap
|
||||||
|
client = ((FeignBlockingLoadBalancerClient) client).getDelegate();
|
||||||
|
}
|
||||||
builder.client(client);
|
builder.client(client);
|
||||||
}
|
}
|
||||||
Targeter targeter = get(context, Targeter.class);
|
Targeter targeter = get(context, Targeter.class);
|
||||||
return (T) targeter.target(this, builder, context,
|
return (T) targeter.target(this, builder, context,
|
||||||
new HardCodedTarget<>(this.type, this.name, url));
|
new HardCodedTarget<>(type, name, url));
|
||||||
}
|
}
|
||||||
|
|
||||||
private String cleanPath() {
|
private String cleanPath() {
|
||||||
@@ -304,7 +407,7 @@ class FeignClientFactoryBean
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Class<?> getObjectType() {
|
public Class<?> getObjectType() {
|
||||||
return this.type;
|
return type;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -313,7 +416,7 @@ class FeignClientFactoryBean
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Class<?> getType() {
|
public Class<?> getType() {
|
||||||
return this.type;
|
return type;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setType(Class<?> type) {
|
public void setType(Class<?> type) {
|
||||||
@@ -321,7 +424,7 @@ class FeignClientFactoryBean
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return this.name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
@@ -329,7 +432,7 @@ class FeignClientFactoryBean
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getContextId() {
|
public String getContextId() {
|
||||||
return this.contextId;
|
return contextId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setContextId(String contextId) {
|
public void setContextId(String contextId) {
|
||||||
@@ -337,7 +440,7 @@ class FeignClientFactoryBean
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getUrl() {
|
public String getUrl() {
|
||||||
return this.url;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setUrl(String url) {
|
public void setUrl(String url) {
|
||||||
@@ -345,7 +448,7 @@ class FeignClientFactoryBean
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getPath() {
|
public String getPath() {
|
||||||
return this.path;
|
return path;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setPath(String path) {
|
public void setPath(String path) {
|
||||||
@@ -353,24 +456,33 @@ class FeignClientFactoryBean
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean isDecode404() {
|
public boolean isDecode404() {
|
||||||
return this.decode404;
|
return decode404;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDecode404(boolean decode404) {
|
public void setDecode404(boolean decode404) {
|
||||||
this.decode404 = decode404;
|
this.decode404 = decode404;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public boolean isInheritParentContext() {
|
||||||
|
return inheritParentContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setInheritParentContext(boolean inheritParentContext) {
|
||||||
|
this.inheritParentContext = inheritParentContext;
|
||||||
|
}
|
||||||
|
|
||||||
public ApplicationContext getApplicationContext() {
|
public ApplicationContext getApplicationContext() {
|
||||||
return this.applicationContext;
|
return applicationContext;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setApplicationContext(ApplicationContext context) throws BeansException {
|
public void setApplicationContext(ApplicationContext context) throws BeansException {
|
||||||
this.applicationContext = context;
|
applicationContext = context;
|
||||||
|
beanFactory = context;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Class<?> getFallback() {
|
public Class<?> getFallback() {
|
||||||
return this.fallback;
|
return fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFallback(Class<?> fallback) {
|
public void setFallback(Class<?> fallback) {
|
||||||
@@ -378,7 +490,7 @@ class FeignClientFactoryBean
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Class<?> getFallbackFactory() {
|
public Class<?> getFallbackFactory() {
|
||||||
return this.fallbackFactory;
|
return fallbackFactory;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFallbackFactory(Class<?> fallbackFactory) {
|
public void setFallbackFactory(Class<?> fallbackFactory) {
|
||||||
@@ -394,32 +506,39 @@ class FeignClientFactoryBean
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
FeignClientFactoryBean that = (FeignClientFactoryBean) o;
|
FeignClientFactoryBean that = (FeignClientFactoryBean) o;
|
||||||
return Objects.equals(this.applicationContext, that.applicationContext)
|
return Objects.equals(applicationContext, that.applicationContext)
|
||||||
&& this.decode404 == that.decode404
|
&& Objects.equals(beanFactory, that.beanFactory)
|
||||||
&& Objects.equals(this.fallback, that.fallback)
|
&& decode404 == that.decode404
|
||||||
&& Objects.equals(this.fallbackFactory, that.fallbackFactory)
|
&& inheritParentContext == that.inheritParentContext
|
||||||
&& Objects.equals(this.name, that.name)
|
&& Objects.equals(fallback, that.fallback)
|
||||||
&& Objects.equals(this.path, that.path)
|
&& Objects.equals(fallbackFactory, that.fallbackFactory)
|
||||||
&& Objects.equals(this.type, that.type)
|
&& Objects.equals(name, that.name) && Objects.equals(path, that.path)
|
||||||
&& Objects.equals(this.url, that.url);
|
&& Objects.equals(type, that.type) && Objects.equals(url, that.url);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
return Objects.hash(this.applicationContext, this.decode404, this.fallback,
|
return Objects.hash(applicationContext, beanFactory, decode404,
|
||||||
this.fallbackFactory, this.name, this.path, this.type, this.url);
|
inheritParentContext, fallback, fallbackFactory, name, path, type, url);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return new StringBuilder("FeignClientFactoryBean{").append("type=")
|
return new StringBuilder("FeignClientFactoryBean{").append("type=").append(type)
|
||||||
.append(this.type).append(", ").append("name='").append(this.name)
|
.append(", ").append("name='").append(name).append("', ").append("url='")
|
||||||
.append("', ").append("url='").append(this.url).append("', ")
|
.append(url).append("', ").append("path='").append(path).append("', ")
|
||||||
.append("path='").append(this.path).append("', ").append("decode404=")
|
.append("decode404=").append(decode404).append(", ")
|
||||||
.append(this.decode404).append(", ").append("applicationContext=")
|
.append("inheritParentContext=").append(inheritParentContext).append(", ")
|
||||||
.append(this.applicationContext).append(", ").append("fallback=")
|
.append("applicationContext=").append(applicationContext).append(", ")
|
||||||
.append(this.fallback).append(", ").append("fallbackFactory=")
|
.append("beanFactory=").append(beanFactory).append(", ")
|
||||||
.append(this.fallbackFactory).append("}").toString();
|
.append("fallback=").append(fallback).append(", ")
|
||||||
|
.append("fallbackFactory=").append(fallbackFactory).append("}")
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
|
||||||
|
this.beanFactory = beanFactory;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+89
-31
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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,12 +16,14 @@
|
|||||||
|
|
||||||
package org.springframework.cloud.openfeign;
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
import feign.Contract;
|
import feign.Contract;
|
||||||
|
import feign.ExceptionPropagationPolicy;
|
||||||
import feign.Logger;
|
import feign.Logger;
|
||||||
import feign.RequestInterceptor;
|
import feign.RequestInterceptor;
|
||||||
import feign.Retryer;
|
import feign.Retryer;
|
||||||
@@ -33,6 +35,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Eko Kurniawan Khannedy
|
* @author Eko Kurniawan Khannedy
|
||||||
|
* @author Ilia Ilinykh
|
||||||
|
* @author Ram Anaswara
|
||||||
*/
|
*/
|
||||||
@ConfigurationProperties("feign.client")
|
@ConfigurationProperties("feign.client")
|
||||||
public class FeignClientProperties {
|
public class FeignClientProperties {
|
||||||
@@ -43,8 +47,14 @@ public class FeignClientProperties {
|
|||||||
|
|
||||||
private Map<String, FeignClientConfiguration> config = new HashMap<>();
|
private Map<String, FeignClientConfiguration> config = new HashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Feign clients do not encode slash `/` characters by default. To change this
|
||||||
|
* behavior, set the `decodeSlash` to `false`.
|
||||||
|
*/
|
||||||
|
private boolean decodeSlash = true;
|
||||||
|
|
||||||
public boolean isDefaultToProperties() {
|
public boolean isDefaultToProperties() {
|
||||||
return this.defaultToProperties;
|
return defaultToProperties;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDefaultToProperties(boolean defaultToProperties) {
|
public void setDefaultToProperties(boolean defaultToProperties) {
|
||||||
@@ -52,7 +62,7 @@ public class FeignClientProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getDefaultConfig() {
|
public String getDefaultConfig() {
|
||||||
return this.defaultConfig;
|
return defaultConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDefaultConfig(String defaultConfig) {
|
public void setDefaultConfig(String defaultConfig) {
|
||||||
@@ -60,13 +70,21 @@ public class FeignClientProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, FeignClientConfiguration> getConfig() {
|
public Map<String, FeignClientConfiguration> getConfig() {
|
||||||
return this.config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setConfig(Map<String, FeignClientConfiguration> config) {
|
public void setConfig(Map<String, FeignClientConfiguration> config) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public boolean isDecodeSlash() {
|
||||||
|
return decodeSlash;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDecodeSlash(boolean decodeSlash) {
|
||||||
|
this.decodeSlash = decodeSlash;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object o) {
|
public boolean equals(Object o) {
|
||||||
if (this == o) {
|
if (this == o) {
|
||||||
@@ -76,14 +94,15 @@ public class FeignClientProperties {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
FeignClientProperties that = (FeignClientProperties) o;
|
FeignClientProperties that = (FeignClientProperties) o;
|
||||||
return this.defaultToProperties == that.defaultToProperties
|
return defaultToProperties == that.defaultToProperties
|
||||||
&& Objects.equals(this.defaultConfig, that.defaultConfig)
|
&& Objects.equals(defaultConfig, that.defaultConfig)
|
||||||
&& Objects.equals(this.config, that.config);
|
&& Objects.equals(config, that.config)
|
||||||
|
&& Objects.equals(decodeSlash, that.decodeSlash);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
return Objects.hash(this.defaultToProperties, this.defaultConfig, this.config);
|
return Objects.hash(defaultToProperties, defaultConfig, config, decodeSlash);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -103,6 +122,10 @@ public class FeignClientProperties {
|
|||||||
|
|
||||||
private List<Class<RequestInterceptor>> requestInterceptors;
|
private List<Class<RequestInterceptor>> requestInterceptors;
|
||||||
|
|
||||||
|
private Map<String, Collection<String>> defaultRequestHeaders;
|
||||||
|
|
||||||
|
private Map<String, Collection<String>> defaultQueryParameters;
|
||||||
|
|
||||||
private Boolean decode404;
|
private Boolean decode404;
|
||||||
|
|
||||||
private Class<Decoder> decoder;
|
private Class<Decoder> decoder;
|
||||||
@@ -111,8 +134,10 @@ public class FeignClientProperties {
|
|||||||
|
|
||||||
private Class<Contract> contract;
|
private Class<Contract> contract;
|
||||||
|
|
||||||
|
private ExceptionPropagationPolicy exceptionPropagationPolicy;
|
||||||
|
|
||||||
public Logger.Level getLoggerLevel() {
|
public Logger.Level getLoggerLevel() {
|
||||||
return this.loggerLevel;
|
return loggerLevel;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLoggerLevel(Logger.Level loggerLevel) {
|
public void setLoggerLevel(Logger.Level loggerLevel) {
|
||||||
@@ -120,7 +145,7 @@ public class FeignClientProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Integer getConnectTimeout() {
|
public Integer getConnectTimeout() {
|
||||||
return this.connectTimeout;
|
return connectTimeout;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setConnectTimeout(Integer connectTimeout) {
|
public void setConnectTimeout(Integer connectTimeout) {
|
||||||
@@ -128,7 +153,7 @@ public class FeignClientProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Integer getReadTimeout() {
|
public Integer getReadTimeout() {
|
||||||
return this.readTimeout;
|
return readTimeout;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setReadTimeout(Integer readTimeout) {
|
public void setReadTimeout(Integer readTimeout) {
|
||||||
@@ -136,7 +161,7 @@ public class FeignClientProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Class<Retryer> getRetryer() {
|
public Class<Retryer> getRetryer() {
|
||||||
return this.retryer;
|
return retryer;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setRetryer(Class<Retryer> retryer) {
|
public void setRetryer(Class<Retryer> retryer) {
|
||||||
@@ -144,7 +169,7 @@ public class FeignClientProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Class<ErrorDecoder> getErrorDecoder() {
|
public Class<ErrorDecoder> getErrorDecoder() {
|
||||||
return this.errorDecoder;
|
return errorDecoder;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setErrorDecoder(Class<ErrorDecoder> errorDecoder) {
|
public void setErrorDecoder(Class<ErrorDecoder> errorDecoder) {
|
||||||
@@ -152,7 +177,7 @@ public class FeignClientProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public List<Class<RequestInterceptor>> getRequestInterceptors() {
|
public List<Class<RequestInterceptor>> getRequestInterceptors() {
|
||||||
return this.requestInterceptors;
|
return requestInterceptors;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setRequestInterceptors(
|
public void setRequestInterceptors(
|
||||||
@@ -160,8 +185,26 @@ public class FeignClientProperties {
|
|||||||
this.requestInterceptors = requestInterceptors;
|
this.requestInterceptors = requestInterceptors;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Map<String, Collection<String>> getDefaultRequestHeaders() {
|
||||||
|
return defaultRequestHeaders;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDefaultRequestHeaders(
|
||||||
|
Map<String, Collection<String>> defaultRequestHeaders) {
|
||||||
|
this.defaultRequestHeaders = defaultRequestHeaders;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Collection<String>> getDefaultQueryParameters() {
|
||||||
|
return defaultQueryParameters;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDefaultQueryParameters(
|
||||||
|
Map<String, Collection<String>> defaultQueryParameters) {
|
||||||
|
this.defaultQueryParameters = defaultQueryParameters;
|
||||||
|
}
|
||||||
|
|
||||||
public Boolean getDecode404() {
|
public Boolean getDecode404() {
|
||||||
return this.decode404;
|
return decode404;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDecode404(Boolean decode404) {
|
public void setDecode404(Boolean decode404) {
|
||||||
@@ -169,7 +212,7 @@ public class FeignClientProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Class<Decoder> getDecoder() {
|
public Class<Decoder> getDecoder() {
|
||||||
return this.decoder;
|
return decoder;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDecoder(Class<Decoder> decoder) {
|
public void setDecoder(Class<Decoder> decoder) {
|
||||||
@@ -177,7 +220,7 @@ public class FeignClientProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Class<Encoder> getEncoder() {
|
public Class<Encoder> getEncoder() {
|
||||||
return this.encoder;
|
return encoder;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setEncoder(Class<Encoder> encoder) {
|
public void setEncoder(Class<Encoder> encoder) {
|
||||||
@@ -185,13 +228,22 @@ public class FeignClientProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Class<Contract> getContract() {
|
public Class<Contract> getContract() {
|
||||||
return this.contract;
|
return contract;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setContract(Class<Contract> contract) {
|
public void setContract(Class<Contract> contract) {
|
||||||
this.contract = contract;
|
this.contract = contract;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ExceptionPropagationPolicy getExceptionPropagationPolicy() {
|
||||||
|
return exceptionPropagationPolicy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setExceptionPropagationPolicy(
|
||||||
|
ExceptionPropagationPolicy exceptionPropagationPolicy) {
|
||||||
|
this.exceptionPropagationPolicy = exceptionPropagationPolicy;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object o) {
|
public boolean equals(Object o) {
|
||||||
if (this == o) {
|
if (this == o) {
|
||||||
@@ -201,23 +253,29 @@ public class FeignClientProperties {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
FeignClientConfiguration that = (FeignClientConfiguration) o;
|
FeignClientConfiguration that = (FeignClientConfiguration) o;
|
||||||
return this.loggerLevel == that.loggerLevel
|
return loggerLevel == that.loggerLevel
|
||||||
&& Objects.equals(this.connectTimeout, that.connectTimeout)
|
&& Objects.equals(connectTimeout, that.connectTimeout)
|
||||||
&& Objects.equals(this.readTimeout, that.readTimeout)
|
&& Objects.equals(readTimeout, that.readTimeout)
|
||||||
&& Objects.equals(this.retryer, that.retryer)
|
&& Objects.equals(retryer, that.retryer)
|
||||||
&& Objects.equals(this.errorDecoder, that.errorDecoder)
|
&& Objects.equals(errorDecoder, that.errorDecoder)
|
||||||
&& Objects.equals(this.requestInterceptors, that.requestInterceptors)
|
&& Objects.equals(requestInterceptors, that.requestInterceptors)
|
||||||
&& Objects.equals(this.decode404, that.decode404)
|
&& Objects.equals(decode404, that.decode404)
|
||||||
&& Objects.equals(this.encoder, that.encoder)
|
&& Objects.equals(encoder, that.encoder)
|
||||||
&& Objects.equals(this.decoder, that.decoder)
|
&& Objects.equals(decoder, that.decoder)
|
||||||
&& Objects.equals(this.contract, that.contract);
|
&& Objects.equals(contract, that.contract)
|
||||||
|
&& Objects.equals(exceptionPropagationPolicy,
|
||||||
|
that.exceptionPropagationPolicy)
|
||||||
|
&& Objects.equals(defaultRequestHeaders, that.defaultRequestHeaders)
|
||||||
|
&& Objects.equals(defaultQueryParameters,
|
||||||
|
that.defaultQueryParameters);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
return Objects.hash(this.loggerLevel, this.connectTimeout, this.readTimeout,
|
return Objects.hash(loggerLevel, connectTimeout, readTimeout, retryer,
|
||||||
this.retryer, this.errorDecoder, this.requestInterceptors,
|
errorDecoder, requestInterceptors, decode404, encoder, decoder,
|
||||||
this.decode404, this.encoder, this.decoder, this.contract);
|
contract, exceptionPropagationPolicy, defaultQueryParameters,
|
||||||
|
defaultRequestHeaders);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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.
|
||||||
|
|||||||
+77
-13
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -19,7 +19,6 @@ package org.springframework.cloud.openfeign;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.Module;
|
|
||||||
import com.netflix.hystrix.HystrixCommand;
|
import com.netflix.hystrix.HystrixCommand;
|
||||||
import feign.Contract;
|
import feign.Contract;
|
||||||
import feign.Feign;
|
import feign.Feign;
|
||||||
@@ -27,18 +26,25 @@ import feign.Logger;
|
|||||||
import feign.Retryer;
|
import feign.Retryer;
|
||||||
import feign.codec.Decoder;
|
import feign.codec.Decoder;
|
||||||
import feign.codec.Encoder;
|
import feign.codec.Encoder;
|
||||||
|
import feign.form.MultipartFormContentProcessor;
|
||||||
|
import feign.form.spring.SpringFormEncoder;
|
||||||
import feign.hystrix.HystrixFeign;
|
import feign.hystrix.HystrixFeign;
|
||||||
import feign.optionals.OptionalDecoder;
|
import feign.optionals.OptionalDecoder;
|
||||||
|
|
||||||
import org.springframework.beans.factory.ObjectFactory;
|
import org.springframework.beans.factory.ObjectFactory;
|
||||||
|
import org.springframework.beans.factory.ObjectProvider;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
|
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
|
||||||
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
|
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
|
||||||
import org.springframework.cloud.openfeign.support.PageJacksonModule;
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
|
||||||
|
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
|
||||||
|
import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer;
|
||||||
|
import org.springframework.cloud.openfeign.support.AbstractFormWriter;
|
||||||
import org.springframework.cloud.openfeign.support.PageableSpringEncoder;
|
import org.springframework.cloud.openfeign.support.PageableSpringEncoder;
|
||||||
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
|
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
|
||||||
import org.springframework.cloud.openfeign.support.SpringDecoder;
|
import org.springframework.cloud.openfeign.support.SpringDecoder;
|
||||||
@@ -51,11 +57,14 @@ import org.springframework.core.convert.ConversionService;
|
|||||||
import org.springframework.format.support.DefaultFormattingConversionService;
|
import org.springframework.format.support.DefaultFormattingConversionService;
|
||||||
import org.springframework.format.support.FormattingConversionService;
|
import org.springframework.format.support.FormattingConversionService;
|
||||||
|
|
||||||
|
import static feign.form.ContentType.MULTIPART;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Dave Syer
|
* @author Dave Syer
|
||||||
* @author Venil Noronha
|
* @author Venil Noronha
|
||||||
|
* @author Darren Foong
|
||||||
*/
|
*/
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
public class FeignClientsConfiguration {
|
public class FeignClientsConfiguration {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -73,6 +82,9 @@ public class FeignClientsConfiguration {
|
|||||||
@Autowired(required = false)
|
@Autowired(required = false)
|
||||||
private SpringDataWebProperties springDataWebProperties;
|
private SpringDataWebProperties springDataWebProperties;
|
||||||
|
|
||||||
|
@Autowired(required = false)
|
||||||
|
private FeignClientProperties feignClientProperties;
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public Decoder feignDecoder() {
|
public Decoder feignDecoder() {
|
||||||
@@ -83,16 +95,18 @@ public class FeignClientsConfiguration {
|
|||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
@ConditionalOnMissingClass("org.springframework.data.domain.Pageable")
|
@ConditionalOnMissingClass("org.springframework.data.domain.Pageable")
|
||||||
public Encoder feignEncoder() {
|
public Encoder feignEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider) {
|
||||||
return new SpringEncoder(this.messageConverters);
|
return springEncoder(formWriterProvider);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnClass(name = "org.springframework.data.domain.Pageable")
|
@ConditionalOnClass(name = "org.springframework.data.domain.Pageable")
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public Encoder feignEncoderPageable() {
|
public Encoder feignEncoderPageable(
|
||||||
|
ObjectProvider<AbstractFormWriter> formWriterProvider) {
|
||||||
PageableSpringEncoder encoder = new PageableSpringEncoder(
|
PageableSpringEncoder encoder = new PageableSpringEncoder(
|
||||||
new SpringEncoder(this.messageConverters));
|
springEncoder(formWriterProvider));
|
||||||
|
|
||||||
if (springDataWebProperties != null) {
|
if (springDataWebProperties != null) {
|
||||||
encoder.setPageParameter(
|
encoder.setPageParameter(
|
||||||
springDataWebProperties.getPageable().getPageParameter());
|
springDataWebProperties.getPageable().getPageParameter());
|
||||||
@@ -107,7 +121,10 @@ public class FeignClientsConfiguration {
|
|||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public Contract feignContract(ConversionService feignConversionService) {
|
public Contract feignContract(ConversionService feignConversionService) {
|
||||||
return new SpringMvcContract(this.parameterProcessors, feignConversionService);
|
boolean decodeSlash = feignClientProperties == null
|
||||||
|
|| feignClientProperties.isDecodeSlash();
|
||||||
|
return new SpringMvcContract(this.parameterProcessors, feignConversionService,
|
||||||
|
decodeSlash);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@@ -139,12 +156,25 @@ public class FeignClientsConfiguration {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnClass(name = "org.springframework.data.domain.Page")
|
@ConditionalOnMissingBean(FeignClientConfigurer.class)
|
||||||
public Module pageJacksonModule() {
|
public FeignClientConfigurer feignClientConfigurer() {
|
||||||
return new PageJacksonModule();
|
return new FeignClientConfigurer() {
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@Configuration
|
private Encoder springEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider) {
|
||||||
|
AbstractFormWriter formWriter = formWriterProvider.getIfAvailable();
|
||||||
|
|
||||||
|
if (formWriter != null) {
|
||||||
|
return new SpringEncoder(new SpringPojoFormEncoder(formWriter),
|
||||||
|
this.messageConverters);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return new SpringEncoder(new SpringFormEncoder(), this.messageConverters);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
@ConditionalOnClass({ HystrixCommand.class, HystrixFeign.class })
|
@ConditionalOnClass({ HystrixCommand.class, HystrixFeign.class })
|
||||||
protected static class HystrixFeignConfiguration {
|
protected static class HystrixFeignConfiguration {
|
||||||
|
|
||||||
@@ -158,4 +188,38 @@ public class FeignClientsConfiguration {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private class SpringPojoFormEncoder extends SpringFormEncoder {
|
||||||
|
|
||||||
|
SpringPojoFormEncoder(AbstractFormWriter formWriter) {
|
||||||
|
super();
|
||||||
|
|
||||||
|
MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor(
|
||||||
|
MULTIPART);
|
||||||
|
processor.addFirstWriter(formWriter);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@ConditionalOnClass(CircuitBreaker.class)
|
||||||
|
@ConditionalOnProperty("feign.circuitbreaker.enabled")
|
||||||
|
protected static class CircuitBreakerPresentFeignBuilderConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Scope("prototype")
|
||||||
|
@ConditionalOnMissingBean({ Feign.Builder.class, CircuitBreakerFactory.class })
|
||||||
|
public Feign.Builder defaultFeignBuilder(Retryer retryer) {
|
||||||
|
return Feign.builder().retryer(retryer);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Scope("prototype")
|
||||||
|
@ConditionalOnMissingBean
|
||||||
|
@ConditionalOnBean(CircuitBreakerFactory.class)
|
||||||
|
public Feign.Builder circuitBreakerFeignBuilder() {
|
||||||
|
return FeignCircuitBreaker.builder();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+92
-105
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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,20 +16,23 @@
|
|||||||
|
|
||||||
package org.springframework.cloud.openfeign;
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.MalformedURLException;
|
import java.net.MalformedURLException;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.net.URISyntaxException;
|
import java.net.URISyntaxException;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.LinkedHashSet;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.FactoryBean;
|
||||||
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
|
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
|
||||||
|
import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition;
|
||||||
import org.springframework.beans.factory.config.BeanDefinition;
|
import org.springframework.beans.factory.config.BeanDefinition;
|
||||||
import org.springframework.beans.factory.config.BeanDefinitionHolder;
|
import org.springframework.beans.factory.config.BeanDefinitionHolder;
|
||||||
|
import org.springframework.beans.factory.config.BeanExpressionContext;
|
||||||
|
import org.springframework.beans.factory.config.BeanExpressionResolver;
|
||||||
|
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
||||||
import org.springframework.beans.factory.support.AbstractBeanDefinition;
|
import org.springframework.beans.factory.support.AbstractBeanDefinition;
|
||||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||||
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
|
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
|
||||||
@@ -42,12 +45,7 @@ import org.springframework.core.annotation.AnnotationAttributes;
|
|||||||
import org.springframework.core.env.Environment;
|
import org.springframework.core.env.Environment;
|
||||||
import org.springframework.core.io.ResourceLoader;
|
import org.springframework.core.io.ResourceLoader;
|
||||||
import org.springframework.core.type.AnnotationMetadata;
|
import org.springframework.core.type.AnnotationMetadata;
|
||||||
import org.springframework.core.type.ClassMetadata;
|
|
||||||
import org.springframework.core.type.classreading.MetadataReader;
|
|
||||||
import org.springframework.core.type.classreading.MetadataReaderFactory;
|
|
||||||
import org.springframework.core.type.filter.AbstractClassTestingTypeFilter;
|
|
||||||
import org.springframework.core.type.filter.AnnotationTypeFilter;
|
import org.springframework.core.type.filter.AnnotationTypeFilter;
|
||||||
import org.springframework.core.type.filter.TypeFilter;
|
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.ClassUtils;
|
import org.springframework.util.ClassUtils;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
@@ -57,6 +55,8 @@ import org.springframework.util.StringUtils;
|
|||||||
* @author Jakub Narloch
|
* @author Jakub Narloch
|
||||||
* @author Venil Noronha
|
* @author Venil Noronha
|
||||||
* @author Gang Li
|
* @author Gang Li
|
||||||
|
* @author Michal Domagala
|
||||||
|
* @author Marcin Grzejszczak
|
||||||
*/
|
*/
|
||||||
class FeignClientsRegistrar
|
class FeignClientsRegistrar
|
||||||
implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
|
implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
|
||||||
@@ -164,60 +164,43 @@ class FeignClientsRegistrar
|
|||||||
|
|
||||||
public void registerFeignClients(AnnotationMetadata metadata,
|
public void registerFeignClients(AnnotationMetadata metadata,
|
||||||
BeanDefinitionRegistry registry) {
|
BeanDefinitionRegistry registry) {
|
||||||
ClassPathScanningCandidateComponentProvider scanner = getScanner();
|
|
||||||
scanner.setResourceLoader(this.resourceLoader);
|
|
||||||
|
|
||||||
Set<String> basePackages;
|
|
||||||
|
|
||||||
|
LinkedHashSet<BeanDefinition> candidateComponents = new LinkedHashSet<>();
|
||||||
Map<String, Object> attrs = metadata
|
Map<String, Object> attrs = metadata
|
||||||
.getAnnotationAttributes(EnableFeignClients.class.getName());
|
.getAnnotationAttributes(EnableFeignClients.class.getName());
|
||||||
AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
|
|
||||||
FeignClient.class);
|
|
||||||
final Class<?>[] clients = attrs == null ? null
|
final Class<?>[] clients = attrs == null ? null
|
||||||
: (Class<?>[]) attrs.get("clients");
|
: (Class<?>[]) attrs.get("clients");
|
||||||
if (clients == null || clients.length == 0) {
|
if (clients == null || clients.length == 0) {
|
||||||
scanner.addIncludeFilter(annotationTypeFilter);
|
ClassPathScanningCandidateComponentProvider scanner = getScanner();
|
||||||
basePackages = getBasePackages(metadata);
|
scanner.setResourceLoader(this.resourceLoader);
|
||||||
|
scanner.addIncludeFilter(new AnnotationTypeFilter(FeignClient.class));
|
||||||
|
Set<String> basePackages = getBasePackages(metadata);
|
||||||
|
for (String basePackage : basePackages) {
|
||||||
|
candidateComponents.addAll(scanner.findCandidateComponents(basePackage));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
final Set<String> clientClasses = new HashSet<>();
|
|
||||||
basePackages = new HashSet<>();
|
|
||||||
for (Class<?> clazz : clients) {
|
for (Class<?> clazz : clients) {
|
||||||
basePackages.add(ClassUtils.getPackageName(clazz));
|
candidateComponents.add(new AnnotatedGenericBeanDefinition(clazz));
|
||||||
clientClasses.add(clazz.getCanonicalName());
|
|
||||||
}
|
}
|
||||||
AbstractClassTestingTypeFilter filter = new AbstractClassTestingTypeFilter() {
|
|
||||||
@Override
|
|
||||||
protected boolean match(ClassMetadata metadata) {
|
|
||||||
String cleaned = metadata.getClassName().replaceAll("\\$", ".");
|
|
||||||
return clientClasses.contains(cleaned);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
scanner.addIncludeFilter(
|
|
||||||
new AllTypeFilter(Arrays.asList(filter, annotationTypeFilter)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for (String basePackage : basePackages) {
|
for (BeanDefinition candidateComponent : candidateComponents) {
|
||||||
Set<BeanDefinition> candidateComponents = scanner
|
if (candidateComponent instanceof AnnotatedBeanDefinition) {
|
||||||
.findCandidateComponents(basePackage);
|
// verify annotated class is an interface
|
||||||
for (BeanDefinition candidateComponent : candidateComponents) {
|
AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
|
||||||
if (candidateComponent instanceof AnnotatedBeanDefinition) {
|
AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
|
||||||
// verify annotated class is an interface
|
Assert.isTrue(annotationMetadata.isInterface(),
|
||||||
AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
|
"@FeignClient can only be specified on an interface");
|
||||||
AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
|
|
||||||
Assert.isTrue(annotationMetadata.isInterface(),
|
|
||||||
"@FeignClient can only be specified on an interface");
|
|
||||||
|
|
||||||
Map<String, Object> attributes = annotationMetadata
|
Map<String, Object> attributes = annotationMetadata
|
||||||
.getAnnotationAttributes(
|
.getAnnotationAttributes(FeignClient.class.getCanonicalName());
|
||||||
FeignClient.class.getCanonicalName());
|
|
||||||
|
|
||||||
String name = getClientName(attributes);
|
String name = getClientName(attributes);
|
||||||
registerClientConfiguration(registry, name,
|
registerClientConfiguration(registry, name,
|
||||||
attributes.get("configuration"));
|
attributes.get("configuration"));
|
||||||
|
|
||||||
registerFeignClient(registry, annotationMetadata, attributes);
|
registerFeignClient(registry, annotationMetadata, attributes);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -225,26 +208,48 @@ class FeignClientsRegistrar
|
|||||||
private void registerFeignClient(BeanDefinitionRegistry registry,
|
private void registerFeignClient(BeanDefinitionRegistry registry,
|
||||||
AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
|
AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
|
||||||
String className = annotationMetadata.getClassName();
|
String className = annotationMetadata.getClassName();
|
||||||
BeanDefinitionBuilder definition = BeanDefinitionBuilder
|
Class clazz = ClassUtils.resolveClassName(className, null);
|
||||||
.genericBeanDefinition(FeignClientFactoryBean.class);
|
ConfigurableBeanFactory beanFactory = registry instanceof ConfigurableBeanFactory
|
||||||
validate(attributes);
|
? (ConfigurableBeanFactory) registry : null;
|
||||||
definition.addPropertyValue("url", getUrl(attributes));
|
String contextId = getContextId(beanFactory, attributes);
|
||||||
definition.addPropertyValue("path", getPath(attributes));
|
|
||||||
String name = getName(attributes);
|
String name = getName(attributes);
|
||||||
definition.addPropertyValue("name", name);
|
FeignClientFactoryBean factoryBean = new FeignClientFactoryBean();
|
||||||
String contextId = getContextId(attributes);
|
factoryBean.setBeanFactory(beanFactory);
|
||||||
definition.addPropertyValue("contextId", contextId);
|
factoryBean.setName(name);
|
||||||
definition.addPropertyValue("type", className);
|
factoryBean.setContextId(contextId);
|
||||||
definition.addPropertyValue("decode404", attributes.get("decode404"));
|
factoryBean.setType(clazz);
|
||||||
definition.addPropertyValue("fallback", attributes.get("fallback"));
|
BeanDefinitionBuilder definition = BeanDefinitionBuilder
|
||||||
definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));
|
.genericBeanDefinition(clazz, () -> {
|
||||||
|
factoryBean.setUrl(getUrl(beanFactory, attributes));
|
||||||
|
factoryBean.setPath(getPath(beanFactory, attributes));
|
||||||
|
factoryBean.setDecode404(Boolean
|
||||||
|
.parseBoolean(String.valueOf(attributes.get("decode404"))));
|
||||||
|
Object fallback = attributes.get("fallback");
|
||||||
|
if (fallback != null) {
|
||||||
|
factoryBean.setFallback(fallback instanceof Class
|
||||||
|
? (Class<?>) fallback
|
||||||
|
: ClassUtils.resolveClassName(fallback.toString(), null));
|
||||||
|
}
|
||||||
|
Object fallbackFactory = attributes.get("fallbackFactory");
|
||||||
|
if (fallbackFactory != null) {
|
||||||
|
factoryBean.setFallbackFactory(fallbackFactory instanceof Class
|
||||||
|
? (Class<?>) fallbackFactory
|
||||||
|
: ClassUtils.resolveClassName(fallbackFactory.toString(),
|
||||||
|
null));
|
||||||
|
}
|
||||||
|
return factoryBean.getObject();
|
||||||
|
});
|
||||||
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
|
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
|
||||||
|
definition.setLazyInit(true);
|
||||||
|
validate(attributes);
|
||||||
|
|
||||||
String alias = contextId + "FeignClient";
|
String alias = contextId + "FeignClient";
|
||||||
AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
|
AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
|
||||||
|
beanDefinition.setAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE, className);
|
||||||
|
beanDefinition.setAttribute("feignClientsRegistrarFactoryBean", factoryBean);
|
||||||
|
|
||||||
boolean primary = (Boolean) attributes.get("primary"); // has a default, won't be
|
// has a default, won't be null
|
||||||
// null
|
boolean primary = (Boolean) attributes.get("primary");
|
||||||
|
|
||||||
beanDefinition.setPrimary(primary);
|
beanDefinition.setPrimary(primary);
|
||||||
|
|
||||||
@@ -267,6 +272,10 @@ class FeignClientsRegistrar
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* for testing */ String getName(Map<String, Object> attributes) {
|
/* for testing */ String getName(Map<String, Object> attributes) {
|
||||||
|
return getName(null, attributes);
|
||||||
|
}
|
||||||
|
|
||||||
|
String getName(ConfigurableBeanFactory beanFactory, Map<String, Object> attributes) {
|
||||||
String name = (String) attributes.get("serviceId");
|
String name = (String) attributes.get("serviceId");
|
||||||
if (!StringUtils.hasText(name)) {
|
if (!StringUtils.hasText(name)) {
|
||||||
name = (String) attributes.get("name");
|
name = (String) attributes.get("name");
|
||||||
@@ -274,34 +283,46 @@ class FeignClientsRegistrar
|
|||||||
if (!StringUtils.hasText(name)) {
|
if (!StringUtils.hasText(name)) {
|
||||||
name = (String) attributes.get("value");
|
name = (String) attributes.get("value");
|
||||||
}
|
}
|
||||||
name = resolve(name);
|
name = resolve(beanFactory, name);
|
||||||
return getName(name);
|
return getName(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getContextId(Map<String, Object> attributes) {
|
private String getContextId(ConfigurableBeanFactory beanFactory,
|
||||||
|
Map<String, Object> attributes) {
|
||||||
String contextId = (String) attributes.get("contextId");
|
String contextId = (String) attributes.get("contextId");
|
||||||
if (!StringUtils.hasText(contextId)) {
|
if (!StringUtils.hasText(contextId)) {
|
||||||
return getName(attributes);
|
return getName(attributes);
|
||||||
}
|
}
|
||||||
|
|
||||||
contextId = resolve(contextId);
|
contextId = resolve(beanFactory, contextId);
|
||||||
return getName(contextId);
|
return getName(contextId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private String resolve(String value) {
|
private String resolve(ConfigurableBeanFactory beanFactory, String value) {
|
||||||
if (StringUtils.hasText(value)) {
|
if (StringUtils.hasText(value)) {
|
||||||
return this.environment.resolvePlaceholders(value);
|
if (beanFactory == null) {
|
||||||
|
return this.environment.resolvePlaceholders(value);
|
||||||
|
}
|
||||||
|
BeanExpressionResolver resolver = beanFactory.getBeanExpressionResolver();
|
||||||
|
String resolved = beanFactory.resolveEmbeddedValue(value);
|
||||||
|
if (resolver == null) {
|
||||||
|
return resolved;
|
||||||
|
}
|
||||||
|
return String.valueOf(resolver.evaluate(resolved,
|
||||||
|
new BeanExpressionContext(beanFactory, null)));
|
||||||
}
|
}
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getUrl(Map<String, Object> attributes) {
|
private String getUrl(ConfigurableBeanFactory beanFactory,
|
||||||
String url = resolve((String) attributes.get("url"));
|
Map<String, Object> attributes) {
|
||||||
|
String url = resolve(beanFactory, (String) attributes.get("url"));
|
||||||
return getUrl(url);
|
return getUrl(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getPath(Map<String, Object> attributes) {
|
private String getPath(ConfigurableBeanFactory beanFactory,
|
||||||
String path = resolve((String) attributes.get("path"));
|
Map<String, Object> attributes) {
|
||||||
|
String path = resolve(beanFactory, (String) attributes.get("path"));
|
||||||
return getPath(path);
|
return getPath(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -396,38 +417,4 @@ class FeignClientsRegistrar
|
|||||||
this.environment = environment;
|
this.environment = environment;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Helper class to create a {@link TypeFilter} that matches if all the delegates
|
|
||||||
* match.
|
|
||||||
*
|
|
||||||
* @author Oliver Gierke
|
|
||||||
*/
|
|
||||||
private static class AllTypeFilter implements TypeFilter {
|
|
||||||
|
|
||||||
private final List<TypeFilter> delegates;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a new {@link AllTypeFilter} to match if all the given delegates match.
|
|
||||||
* @param delegates must not be {@literal null}.
|
|
||||||
*/
|
|
||||||
AllTypeFilter(List<TypeFilter> delegates) {
|
|
||||||
Assert.notNull(delegates, "This argument is required, it must not be null");
|
|
||||||
this.delegates = delegates;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean match(MetadataReader metadataReader,
|
|
||||||
MetadataReaderFactory metadataReaderFactory) throws IOException {
|
|
||||||
|
|
||||||
for (TypeFilter filter : this.delegates) {
|
|
||||||
if (!filter.match(metadataReader, metadataReaderFactory)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+22
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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,7 +16,12 @@
|
|||||||
|
|
||||||
package org.springframework.cloud.openfeign;
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.beans.BeansException;
|
||||||
|
import org.springframework.beans.factory.BeanFactoryUtils;
|
||||||
import org.springframework.cloud.context.named.NamedContextFactory;
|
import org.springframework.cloud.context.named.NamedContextFactory;
|
||||||
|
import org.springframework.lang.Nullable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A factory that creates instances of feign classes. It creates a Spring
|
* A factory that creates instances of feign classes. It creates a Spring
|
||||||
@@ -24,6 +29,7 @@ import org.springframework.cloud.context.named.NamedContextFactory;
|
|||||||
*
|
*
|
||||||
* @author Spencer Gibb
|
* @author Spencer Gibb
|
||||||
* @author Dave Syer
|
* @author Dave Syer
|
||||||
|
* @author Matt King
|
||||||
*/
|
*/
|
||||||
public class FeignContext extends NamedContextFactory<FeignClientSpecification> {
|
public class FeignContext extends NamedContextFactory<FeignClientSpecification> {
|
||||||
|
|
||||||
@@ -31,4 +37,19 @@ public class FeignContext extends NamedContextFactory<FeignClientSpecification>
|
|||||||
super(FeignClientsConfiguration.class, "feign", "feign.client.name");
|
super(FeignClientsConfiguration.class, "feign", "feign.client.name");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
public <T> T getInstanceWithoutAncestors(String name, Class<T> type) {
|
||||||
|
try {
|
||||||
|
return BeanFactoryUtils.beanOfType(getContext(name), type);
|
||||||
|
}
|
||||||
|
catch (BeansException ex) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
public <T> Map<String, T> getInstancesWithoutAncestors(String name, Class<T> type) {
|
||||||
|
return getContext(name).getBeansOfType(type);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2020-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import feign.codec.ErrorDecoder;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allows an application to use a custom Feign {@link feign.codec.ErrorDecoder}.
|
||||||
|
*
|
||||||
|
* @author Michael Cramer
|
||||||
|
*/
|
||||||
|
public interface FeignErrorDecoderFactory {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Factory method to provide a {@link feign.codec.ErrorDecoder} for a given
|
||||||
|
* {@link Class}.
|
||||||
|
* @param type the {@link Class} for which a {@link feign.codec.ErrorDecoder} instance
|
||||||
|
* is to be created
|
||||||
|
* @return a {@link feign.codec.ErrorDecoder} instance
|
||||||
|
*/
|
||||||
|
ErrorDecoder create(Class<?> type);
|
||||||
|
|
||||||
|
}
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2016-2019 the original author or authors.
|
* Copyright 2016-2020 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.
|
||||||
|
|||||||
+8
-6
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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,8 @@ import feign.hystrix.FallbackFactory;
|
|||||||
import feign.hystrix.HystrixFeign;
|
import feign.hystrix.HystrixFeign;
|
||||||
import feign.hystrix.SetterFactory;
|
import feign.hystrix.SetterFactory;
|
||||||
|
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Spencer Gibb
|
* @author Spencer Gibb
|
||||||
* @author Erik Kringen
|
* @author Erik Kringen
|
||||||
@@ -36,19 +38,19 @@ class HystrixTargeter implements Targeter {
|
|||||||
return feign.target(target);
|
return feign.target(target);
|
||||||
}
|
}
|
||||||
feign.hystrix.HystrixFeign.Builder builder = (feign.hystrix.HystrixFeign.Builder) feign;
|
feign.hystrix.HystrixFeign.Builder builder = (feign.hystrix.HystrixFeign.Builder) feign;
|
||||||
SetterFactory setterFactory = getOptional(factory.getName(), context,
|
String name = StringUtils.isEmpty(factory.getContextId()) ? factory.getName()
|
||||||
SetterFactory.class);
|
: factory.getContextId();
|
||||||
|
SetterFactory setterFactory = getOptional(name, context, SetterFactory.class);
|
||||||
if (setterFactory != null) {
|
if (setterFactory != null) {
|
||||||
builder.setterFactory(setterFactory);
|
builder.setterFactory(setterFactory);
|
||||||
}
|
}
|
||||||
Class<?> fallback = factory.getFallback();
|
Class<?> fallback = factory.getFallback();
|
||||||
if (fallback != void.class) {
|
if (fallback != void.class) {
|
||||||
return targetWithFallback(factory.getName(), context, target, builder,
|
return targetWithFallback(name, context, target, builder, fallback);
|
||||||
fallback);
|
|
||||||
}
|
}
|
||||||
Class<?> fallbackFactory = factory.getFallbackFactory();
|
Class<?> fallbackFactory = factory.getFallbackFactory();
|
||||||
if (fallbackFactory != void.class) {
|
if (fallbackFactory != void.class) {
|
||||||
return targetWithFallbackFactory(factory.getName(), context, target, builder,
|
return targetWithFallbackFactory(name, context, target, builder,
|
||||||
fallbackFactory);
|
fallbackFactory);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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
@@ -0,0 +1,83 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.annotation;
|
||||||
|
|
||||||
|
import java.lang.annotation.Annotation;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import feign.MethodMetadata;
|
||||||
|
|
||||||
|
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
|
||||||
|
import org.springframework.web.bind.annotation.MatrixVariable;
|
||||||
|
|
||||||
|
import static feign.Util.checkState;
|
||||||
|
import static feign.Util.emptyToNull;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link MatrixVariable} annotation processor.
|
||||||
|
*
|
||||||
|
* Can expand maps or single objects. Values are assigned from the objects
|
||||||
|
* {@code toString()} method.
|
||||||
|
*
|
||||||
|
* @author Matt King
|
||||||
|
* @see AnnotatedParameterProcessor
|
||||||
|
*/
|
||||||
|
public class MatrixVariableParameterProcessor implements AnnotatedParameterProcessor {
|
||||||
|
|
||||||
|
private static final Class<MatrixVariable> ANNOTATION = MatrixVariable.class;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Class<? extends Annotation> getAnnotationType() {
|
||||||
|
return ANNOTATION;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean processArgument(AnnotatedParameterContext context,
|
||||||
|
Annotation annotation, Method method) {
|
||||||
|
int parameterIndex = context.getParameterIndex();
|
||||||
|
Class<?> parameterType = method.getParameterTypes()[parameterIndex];
|
||||||
|
MethodMetadata data = context.getMethodMetadata();
|
||||||
|
String name = ANNOTATION.cast(annotation).value();
|
||||||
|
|
||||||
|
checkState(emptyToNull(name) != null,
|
||||||
|
"MatrixVariable annotation was empty on param %s.",
|
||||||
|
context.getParameterIndex());
|
||||||
|
|
||||||
|
context.setParameterName(name);
|
||||||
|
|
||||||
|
if (Map.class.isAssignableFrom(parameterType)) {
|
||||||
|
data.indexToExpander().put(parameterIndex, this::expandMap);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
data.indexToExpander().put(parameterIndex,
|
||||||
|
object -> ";" + name + "=" + object.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String expandMap(Object object) {
|
||||||
|
Map<String, Object> paramMap = (Map) object;
|
||||||
|
|
||||||
|
return paramMap.keySet().stream()
|
||||||
|
.map(key -> ";" + key + "=" + paramMap.get(key).toString())
|
||||||
|
.collect(Collectors.joining());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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.
|
||||||
|
|||||||
+64
@@ -0,0 +1,64 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.annotation;
|
||||||
|
|
||||||
|
import java.lang.annotation.Annotation;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
import feign.MethodMetadata;
|
||||||
|
|
||||||
|
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
|
||||||
|
import org.springframework.web.bind.annotation.RequestPart;
|
||||||
|
|
||||||
|
import static feign.Util.checkState;
|
||||||
|
import static feign.Util.emptyToNull;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link RequestPart} parameter processor.
|
||||||
|
*
|
||||||
|
* @author Aaron Whiteside
|
||||||
|
* @see AnnotatedParameterProcessor
|
||||||
|
*/
|
||||||
|
public class RequestPartParameterProcessor implements AnnotatedParameterProcessor {
|
||||||
|
|
||||||
|
private static final Class<RequestPart> ANNOTATION = RequestPart.class;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Class<? extends Annotation> getAnnotationType() {
|
||||||
|
return ANNOTATION;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean processArgument(AnnotatedParameterContext context,
|
||||||
|
Annotation annotation, Method method) {
|
||||||
|
int parameterIndex = context.getParameterIndex();
|
||||||
|
MethodMetadata data = context.getMethodMetadata();
|
||||||
|
|
||||||
|
String name = ANNOTATION.cast(annotation).value();
|
||||||
|
checkState(emptyToNull(name) != null,
|
||||||
|
"RequestPart.value() was empty on parameter %s", parameterIndex);
|
||||||
|
context.setParameterName(name);
|
||||||
|
|
||||||
|
data.formParams().add(name);
|
||||||
|
Collection<String> names = context.setTemplateParameter(name,
|
||||||
|
data.indexToName().get(parameterIndex));
|
||||||
|
data.indexToName().put(parameterIndex, names);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2019 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.clientconfig;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Additional Feign Client configuration that are not included in
|
||||||
|
* {@link org.springframework.cloud.openfeign.FeignClient}.
|
||||||
|
*
|
||||||
|
* @author Matt King
|
||||||
|
*/
|
||||||
|
public interface FeignClientConfigurer {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return whether to mark the feign proxy as a primary bean. Defaults to true.
|
||||||
|
*/
|
||||||
|
default boolean primary() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FALSE will only apply configurations from classes listed in
|
||||||
|
* <code>configuration()</code>. Will still use parent instance of
|
||||||
|
* {@link feign.codec.Decoder}, {@link feign.codec.Encoder}, and
|
||||||
|
* {@link feign.Contract} if none are provided.
|
||||||
|
* @return weather to inherit parent context for client configuration.
|
||||||
|
*/
|
||||||
|
default boolean inheritParentConfiguration() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+135
@@ -0,0 +1,135 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.clientconfig;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Timer;
|
||||||
|
import java.util.TimerTask;
|
||||||
|
|
||||||
|
import javax.annotation.PreDestroy;
|
||||||
|
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.apache.http.client.config.RequestConfig;
|
||||||
|
import org.apache.http.config.RegistryBuilder;
|
||||||
|
import org.apache.http.conn.HttpClientConnectionManager;
|
||||||
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory;
|
||||||
|
import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory;
|
||||||
|
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default configuration for {@link CloseableHttpClient}.
|
||||||
|
*
|
||||||
|
* @author Ryan Baxter
|
||||||
|
* @author Marcin Grzejszczak
|
||||||
|
* @author Spencer Gibb
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
|
*/
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@ConditionalOnMissingBean(CloseableHttpClient.class)
|
||||||
|
public class HttpClientFeignConfiguration {
|
||||||
|
|
||||||
|
private static final Log LOG = LogFactory.getLog(HttpClientFeignConfiguration.class);
|
||||||
|
|
||||||
|
private final Timer connectionManagerTimer = new Timer(
|
||||||
|
"FeignApacheHttpClientConfiguration.connectionManagerTimer", true);
|
||||||
|
|
||||||
|
private CloseableHttpClient httpClient;
|
||||||
|
|
||||||
|
@Autowired(required = false)
|
||||||
|
private RegistryBuilder registryBuilder;
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean(HttpClientConnectionManager.class)
|
||||||
|
public HttpClientConnectionManager connectionManager(
|
||||||
|
ApacheHttpClientConnectionManagerFactory connectionManagerFactory,
|
||||||
|
FeignHttpClientProperties httpClientProperties) {
|
||||||
|
final HttpClientConnectionManager connectionManager = connectionManagerFactory
|
||||||
|
.newConnectionManager(httpClientProperties.isDisableSslValidation(),
|
||||||
|
httpClientProperties.getMaxConnections(),
|
||||||
|
httpClientProperties.getMaxConnectionsPerRoute(),
|
||||||
|
httpClientProperties.getTimeToLive(),
|
||||||
|
httpClientProperties.getTimeToLiveUnit(), this.registryBuilder);
|
||||||
|
this.connectionManagerTimer.schedule(new TimerTask() {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
connectionManager.closeExpiredConnections();
|
||||||
|
}
|
||||||
|
}, 30000, httpClientProperties.getConnectionTimerRepeat());
|
||||||
|
return connectionManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnProperty(value = "feign.compression.response.enabled",
|
||||||
|
havingValue = "true")
|
||||||
|
public CloseableHttpClient customHttpClient(
|
||||||
|
HttpClientConnectionManager httpClientConnectionManager,
|
||||||
|
FeignHttpClientProperties httpClientProperties) {
|
||||||
|
HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement()
|
||||||
|
.useSystemProperties();
|
||||||
|
this.httpClient = createClient(builder, httpClientConnectionManager,
|
||||||
|
httpClientProperties);
|
||||||
|
return this.httpClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnProperty(value = "feign.compression.response.enabled",
|
||||||
|
havingValue = "false", matchIfMissing = true)
|
||||||
|
public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory,
|
||||||
|
HttpClientConnectionManager httpClientConnectionManager,
|
||||||
|
FeignHttpClientProperties httpClientProperties) {
|
||||||
|
this.httpClient = createClient(httpClientFactory.createBuilder(),
|
||||||
|
httpClientConnectionManager, httpClientProperties);
|
||||||
|
return this.httpClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
private CloseableHttpClient createClient(HttpClientBuilder builder,
|
||||||
|
HttpClientConnectionManager httpClientConnectionManager,
|
||||||
|
FeignHttpClientProperties httpClientProperties) {
|
||||||
|
RequestConfig defaultRequestConfig = RequestConfig.custom()
|
||||||
|
.setConnectTimeout(httpClientProperties.getConnectionTimeout())
|
||||||
|
.setRedirectsEnabled(httpClientProperties.isFollowRedirects()).build();
|
||||||
|
CloseableHttpClient httpClient = builder
|
||||||
|
.setDefaultRequestConfig(defaultRequestConfig)
|
||||||
|
.setConnectionManager(httpClientConnectionManager).build();
|
||||||
|
return httpClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreDestroy
|
||||||
|
public void destroy() {
|
||||||
|
this.connectionManagerTimer.cancel();
|
||||||
|
if (this.httpClient != null) {
|
||||||
|
try {
|
||||||
|
this.httpClient.close();
|
||||||
|
}
|
||||||
|
catch (IOException e) {
|
||||||
|
if (LOG.isErrorEnabled()) {
|
||||||
|
LOG.error("Could not correctly close httpClient.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+79
@@ -0,0 +1,79 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.clientconfig;
|
||||||
|
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import javax.annotation.PreDestroy;
|
||||||
|
|
||||||
|
import okhttp3.ConnectionPool;
|
||||||
|
import okhttp3.OkHttpClient;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
|
import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory;
|
||||||
|
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
|
||||||
|
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Defualt configuration for {@link OkHttpClient}.
|
||||||
|
*
|
||||||
|
* @author Ryan Baxter
|
||||||
|
* @author Marcin Grzejszczak
|
||||||
|
* @author Spencer Gibb
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
|
*/
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@ConditionalOnMissingBean(okhttp3.OkHttpClient.class)
|
||||||
|
public class OkHttpFeignConfiguration {
|
||||||
|
|
||||||
|
private okhttp3.OkHttpClient okHttpClient;
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean(ConnectionPool.class)
|
||||||
|
public ConnectionPool httpClientConnectionPool(
|
||||||
|
FeignHttpClientProperties httpClientProperties,
|
||||||
|
OkHttpClientConnectionPoolFactory connectionPoolFactory) {
|
||||||
|
Integer maxTotalConnections = httpClientProperties.getMaxConnections();
|
||||||
|
Long timeToLive = httpClientProperties.getTimeToLive();
|
||||||
|
TimeUnit ttlUnit = httpClientProperties.getTimeToLiveUnit();
|
||||||
|
return connectionPoolFactory.create(maxTotalConnections, timeToLive, ttlUnit);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory,
|
||||||
|
ConnectionPool connectionPool,
|
||||||
|
FeignHttpClientProperties httpClientProperties) {
|
||||||
|
Boolean followRedirects = httpClientProperties.isFollowRedirects();
|
||||||
|
Integer connectTimeout = httpClientProperties.getConnectionTimeout();
|
||||||
|
this.okHttpClient = httpClientFactory
|
||||||
|
.createBuilder(httpClientProperties.isDisableSslValidation())
|
||||||
|
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
|
||||||
|
.followRedirects(followRedirects).connectionPool(connectionPool).build();
|
||||||
|
return this.okHttpClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreDestroy
|
||||||
|
public void destroy() {
|
||||||
|
if (this.okHttpClient != null) {
|
||||||
|
this.okHttpClient.dispatcher().executorService().shutdown();
|
||||||
|
this.okHttpClient.connectionPool().evictAll();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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.
|
||||||
|
|||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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.context.annotation.Configuration;
|
|||||||
* @author Jakub Narloch
|
* @author Jakub Narloch
|
||||||
* @see FeignAcceptGzipEncodingInterceptor
|
* @see FeignAcceptGzipEncodingInterceptor
|
||||||
*/
|
*/
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
@EnableConfigurationProperties(FeignClientEncodingProperties.class)
|
@EnableConfigurationProperties(FeignClientEncodingProperties.class)
|
||||||
@ConditionalOnClass(Feign.class)
|
@ConditionalOnClass(Feign.class)
|
||||||
@ConditionalOnBean(Client.class)
|
@ConditionalOnBean(Client.class)
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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.
|
||||||
|
|||||||
+3
-7
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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,11 +16,9 @@
|
|||||||
|
|
||||||
package org.springframework.cloud.openfeign.encoding;
|
package org.springframework.cloud.openfeign.encoding;
|
||||||
|
|
||||||
import feign.Client;
|
|
||||||
import feign.Feign;
|
import feign.Feign;
|
||||||
|
|
||||||
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
@@ -35,15 +33,13 @@ import org.springframework.context.annotation.Configuration;
|
|||||||
* @author Jakub Narloch
|
* @author Jakub Narloch
|
||||||
* @see FeignContentGzipEncodingInterceptor
|
* @see FeignContentGzipEncodingInterceptor
|
||||||
*/
|
*/
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
@EnableConfigurationProperties(FeignClientEncodingProperties.class)
|
@EnableConfigurationProperties(FeignClientEncodingProperties.class)
|
||||||
@ConditionalOnClass(Feign.class)
|
@ConditionalOnClass(Feign.class)
|
||||||
@ConditionalOnBean(Client.class)
|
|
||||||
// The OK HTTP client uses "transparent" compression.
|
// The OK HTTP client uses "transparent" compression.
|
||||||
// If the content-encoding header is present it disable transparent compression
|
// If the content-encoding header is present it disable transparent compression
|
||||||
@ConditionalOnMissingBean(type = "okhttp3.OkHttpClient")
|
@ConditionalOnMissingBean(type = "okhttp3.OkHttpClient")
|
||||||
@ConditionalOnProperty(value = "feign.compression.request.enabled",
|
@ConditionalOnProperty("feign.compression.request.enabled")
|
||||||
matchIfMissing = false)
|
|
||||||
@AutoConfigureAfter(FeignAutoConfiguration.class)
|
@AutoConfigureAfter(FeignAutoConfiguration.class)
|
||||||
public class FeignContentGzipEncodingAutoConfiguration {
|
public class FeignContentGzipEncodingAutoConfiguration {
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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.
|
||||||
|
|||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2016-2019 the original author or authors.
|
* Copyright 2016-2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -48,7 +48,7 @@ import static org.springframework.hateoas.MediaTypes.HAL_JSON;
|
|||||||
/**
|
/**
|
||||||
* @author Hector Espert
|
* @author Hector Espert
|
||||||
*/
|
*/
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
@ConditionalOnWebApplication
|
@ConditionalOnWebApplication
|
||||||
@ConditionalOnClass(RepresentationModel.class)
|
@ConditionalOnClass(RepresentationModel.class)
|
||||||
@AutoConfigureAfter({ JacksonAutoConfiguration.class,
|
@AutoConfigureAfter({ JacksonAutoConfiguration.class,
|
||||||
|
|||||||
+66
@@ -0,0 +1,66 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.loadbalancer;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import feign.Client;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
|
||||||
|
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Conditional;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration instantiating a {@link BlockingLoadBalancerClient}-based {@link Client}
|
||||||
|
* object that uses {@link Client.Default} under the hood.
|
||||||
|
*
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
|
* @since 2.2.0
|
||||||
|
*/
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
class DefaultFeignLoadBalancerConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean
|
||||||
|
@Conditional(OnRetryNotEnabledCondition.class)
|
||||||
|
public Client feignClient(BlockingLoadBalancerClient loadBalancerClient) {
|
||||||
|
return new FeignBlockingLoadBalancerClient(new Client.Default(null, null),
|
||||||
|
loadBalancerClient);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean
|
||||||
|
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
|
||||||
|
@ConditionalOnBean(LoadBalancedRetryFactory.class)
|
||||||
|
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled",
|
||||||
|
havingValue = "true", matchIfMissing = true)
|
||||||
|
public Client feignRetryClient(BlockingLoadBalancerClient loadBalancerClient,
|
||||||
|
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) {
|
||||||
|
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories);
|
||||||
|
return new RetryableFeignBlockingLoadBalancerClient(
|
||||||
|
new Client.Default(null, null), loadBalancerClient,
|
||||||
|
loadBalancedRetryFactories.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+89
@@ -0,0 +1,89 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.loadbalancer;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
|
import feign.Client;
|
||||||
|
import feign.Request;
|
||||||
|
import feign.Response;
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
|
||||||
|
import org.springframework.cloud.client.ServiceInstance;
|
||||||
|
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A {@link Client} implementation that uses {@link BlockingLoadBalancerClient} to select
|
||||||
|
* a {@link ServiceInstance} to use while resolving the request host.
|
||||||
|
*
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
|
* @since 2.2.0
|
||||||
|
*/
|
||||||
|
public class FeignBlockingLoadBalancerClient implements Client {
|
||||||
|
|
||||||
|
private static final Log LOG = LogFactory
|
||||||
|
.getLog(FeignBlockingLoadBalancerClient.class);
|
||||||
|
|
||||||
|
private final Client delegate;
|
||||||
|
|
||||||
|
private final BlockingLoadBalancerClient loadBalancerClient;
|
||||||
|
|
||||||
|
public FeignBlockingLoadBalancerClient(Client delegate,
|
||||||
|
BlockingLoadBalancerClient loadBalancerClient) {
|
||||||
|
this.delegate = delegate;
|
||||||
|
this.loadBalancerClient = loadBalancerClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Response execute(Request request, Request.Options options) throws IOException {
|
||||||
|
final URI originalUri = URI.create(request.url());
|
||||||
|
String serviceId = originalUri.getHost();
|
||||||
|
Assert.state(serviceId != null,
|
||||||
|
"Request URI does not contain a valid hostname: " + originalUri);
|
||||||
|
ServiceInstance instance = loadBalancerClient.choose(serviceId);
|
||||||
|
if (instance == null) {
|
||||||
|
String message = "Load balancer does not contain an instance for the service "
|
||||||
|
+ serviceId;
|
||||||
|
if (LOG.isWarnEnabled()) {
|
||||||
|
LOG.warn(message);
|
||||||
|
}
|
||||||
|
return Response.builder().request(request)
|
||||||
|
.status(HttpStatus.SERVICE_UNAVAILABLE.value())
|
||||||
|
.body(message, StandardCharsets.UTF_8).build();
|
||||||
|
}
|
||||||
|
String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri)
|
||||||
|
.toString();
|
||||||
|
Request newRequest = buildRequest(request, reconstructedUrl);
|
||||||
|
return delegate.execute(newRequest, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Request buildRequest(Request request, String reconstructedUrl) {
|
||||||
|
return Request.create(request.httpMethod(), reconstructedUrl, request.headers(),
|
||||||
|
request.body(), request.charset(), request.requestTemplate());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Visible for Sleuth instrumentation
|
||||||
|
public Client getDelegate() {
|
||||||
|
return delegate;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+57
@@ -0,0 +1,57 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.loadbalancer;
|
||||||
|
|
||||||
|
import feign.Client;
|
||||||
|
import feign.Feign;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||||
|
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
|
||||||
|
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
|
||||||
|
import org.springframework.cloud.openfeign.ribbon.FeignRibbonClientAutoConfiguration;
|
||||||
|
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An autoconfiguration that instantiates {@link BlockingLoadBalancerClient}-based
|
||||||
|
* implementations of {@link Client}. In order to use this load-balancing mechanism, the
|
||||||
|
* Ribbon-based implementation has to be disabled by setting
|
||||||
|
* <code>spring.cloud.loadbalancer.ribbon.enabled</code> to <code>true</code>.
|
||||||
|
*
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
|
* @since 2.2.0
|
||||||
|
*/
|
||||||
|
@ConditionalOnClass(Feign.class)
|
||||||
|
@ConditionalOnBean(BlockingLoadBalancerClient.class)
|
||||||
|
@AutoConfigureBefore(FeignAutoConfiguration.class)
|
||||||
|
@AutoConfigureAfter(FeignRibbonClientAutoConfiguration.class)
|
||||||
|
@EnableConfigurationProperties(FeignHttpClientProperties.class)
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
// Order is important here, last should be the default, first should be optional
|
||||||
|
// see
|
||||||
|
// https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653
|
||||||
|
@Import({ HttpClientFeignLoadBalancerConfiguration.class,
|
||||||
|
OkHttpFeignLoadBalancerConfiguration.class,
|
||||||
|
DefaultFeignLoadBalancerConfiguration.class })
|
||||||
|
public class FeignLoadBalancerAutoConfiguration {
|
||||||
|
|
||||||
|
}
|
||||||
+76
@@ -0,0 +1,76 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.loadbalancer;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import feign.Client;
|
||||||
|
import feign.httpclient.ApacheHttpClient;
|
||||||
|
import org.apache.http.client.HttpClient;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
|
||||||
|
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
|
||||||
|
import org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Conditional;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration instantiating a {@link BlockingLoadBalancerClient}-based {@link Client}
|
||||||
|
* object that uses {@link ApacheHttpClient} under the hood.
|
||||||
|
*
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
|
* @since 2.2.0
|
||||||
|
*/
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@ConditionalOnClass(ApacheHttpClient.class)
|
||||||
|
@ConditionalOnBean(BlockingLoadBalancerClient.class)
|
||||||
|
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
|
||||||
|
@Import(HttpClientFeignConfiguration.class)
|
||||||
|
class HttpClientFeignLoadBalancerConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean
|
||||||
|
@Conditional(OnRetryNotEnabledCondition.class)
|
||||||
|
public Client feignClient(BlockingLoadBalancerClient loadBalancerClient,
|
||||||
|
HttpClient httpClient) {
|
||||||
|
ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
|
||||||
|
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean
|
||||||
|
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
|
||||||
|
@ConditionalOnBean(LoadBalancedRetryFactory.class)
|
||||||
|
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled",
|
||||||
|
havingValue = "true", matchIfMissing = true)
|
||||||
|
public Client feignRetryClient(BlockingLoadBalancerClient loadBalancerClient,
|
||||||
|
HttpClient httpClient,
|
||||||
|
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) {
|
||||||
|
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories);
|
||||||
|
ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
|
||||||
|
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient,
|
||||||
|
loadBalancedRetryFactories.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+75
@@ -0,0 +1,75 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.loadbalancer;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import feign.Client;
|
||||||
|
import feign.okhttp.OkHttpClient;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
|
||||||
|
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
|
||||||
|
import org.springframework.cloud.openfeign.clientconfig.OkHttpFeignConfiguration;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Conditional;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration instantiating a {@link BlockingLoadBalancerClient}-based {@link Client}
|
||||||
|
* object that uses {@link OkHttpClient} under the hood.
|
||||||
|
*
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
|
* @since 2.2.0
|
||||||
|
*/
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@ConditionalOnClass(OkHttpClient.class)
|
||||||
|
@ConditionalOnProperty("feign.okhttp.enabled")
|
||||||
|
@ConditionalOnBean(BlockingLoadBalancerClient.class)
|
||||||
|
@Import(OkHttpFeignConfiguration.class)
|
||||||
|
class OkHttpFeignLoadBalancerConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean
|
||||||
|
@Conditional(OnRetryNotEnabledCondition.class)
|
||||||
|
public Client feignClient(okhttp3.OkHttpClient okHttpClient,
|
||||||
|
BlockingLoadBalancerClient loadBalancerClient) {
|
||||||
|
OkHttpClient delegate = new OkHttpClient(okHttpClient);
|
||||||
|
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean
|
||||||
|
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
|
||||||
|
@ConditionalOnBean(LoadBalancedRetryFactory.class)
|
||||||
|
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled",
|
||||||
|
havingValue = "true", matchIfMissing = true)
|
||||||
|
public Client feignRetryClient(BlockingLoadBalancerClient loadBalancerClient,
|
||||||
|
okhttp3.OkHttpClient okHttpClient,
|
||||||
|
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) {
|
||||||
|
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories);
|
||||||
|
OkHttpClient delegate = new OkHttpClient(okHttpClient);
|
||||||
|
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient,
|
||||||
|
loadBalancedRetryFactories.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+56
@@ -0,0 +1,56 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.loadbalancer;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
|
||||||
|
import org.springframework.retry.support.RetryTemplate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A condition that verifies that {@link RetryTemplate} is on the classpath, a
|
||||||
|
* {@link LoadBalancedRetryFactory} bean is present and
|
||||||
|
* <code>spring.cloud.loadbalancer.retry.enabled</code> is not set to <code>false</code>.
|
||||||
|
*
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
|
* @since 2.2.6
|
||||||
|
*/
|
||||||
|
public class OnRetryNotEnabledCondition extends AnyNestedCondition {
|
||||||
|
|
||||||
|
public OnRetryNotEnabledCondition() {
|
||||||
|
super(ConfigurationPhase.REGISTER_BEAN);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ConditionalOnMissingClass("org.springframework.retry.support.RetryTemplate")
|
||||||
|
static class OnNoRetryTemplateCondition {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@ConditionalOnMissingBean(LoadBalancedRetryFactory.class)
|
||||||
|
static class OnRetryFactoryCondition {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled",
|
||||||
|
havingValue = "false")
|
||||||
|
static class OnLoadBalancerRetryEnabledCondition {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+188
@@ -0,0 +1,188 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.loadbalancer;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import feign.Client;
|
||||||
|
import feign.Request;
|
||||||
|
import feign.Response;
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
|
||||||
|
import org.springframework.cloud.client.ServiceInstance;
|
||||||
|
import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy;
|
||||||
|
import org.springframework.cloud.client.loadbalancer.LoadBalancedRecoveryCallback;
|
||||||
|
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext;
|
||||||
|
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
|
||||||
|
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy;
|
||||||
|
import org.springframework.cloud.client.loadbalancer.RetryableStatusCodeException;
|
||||||
|
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.http.HttpRequest;
|
||||||
|
import org.springframework.retry.RetryListener;
|
||||||
|
import org.springframework.retry.backoff.BackOffPolicy;
|
||||||
|
import org.springframework.retry.backoff.NoBackOffPolicy;
|
||||||
|
import org.springframework.retry.policy.NeverRetryPolicy;
|
||||||
|
import org.springframework.retry.support.RetryTemplate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A {@link Client} implementation that provides Spring Retry support for requests
|
||||||
|
* load-balanced with Spring Cloud LoadBalancer.
|
||||||
|
*
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
|
* @since 2.2.6
|
||||||
|
*/
|
||||||
|
public class RetryableFeignBlockingLoadBalancerClient implements Client {
|
||||||
|
|
||||||
|
private static final Log LOG = LogFactory
|
||||||
|
.getLog(FeignBlockingLoadBalancerClient.class);
|
||||||
|
|
||||||
|
private final Client delegate;
|
||||||
|
|
||||||
|
private final BlockingLoadBalancerClient loadBalancerClient;
|
||||||
|
|
||||||
|
private final LoadBalancedRetryFactory loadBalancedRetryFactory;
|
||||||
|
|
||||||
|
public RetryableFeignBlockingLoadBalancerClient(Client delegate,
|
||||||
|
BlockingLoadBalancerClient loadBalancerClient,
|
||||||
|
LoadBalancedRetryFactory loadBalancedRetryFactory) {
|
||||||
|
this.delegate = delegate;
|
||||||
|
this.loadBalancerClient = loadBalancerClient;
|
||||||
|
this.loadBalancedRetryFactory = loadBalancedRetryFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Response execute(Request request, Request.Options options) throws IOException {
|
||||||
|
final URI originalUri = URI.create(request.url());
|
||||||
|
String serviceId = originalUri.getHost();
|
||||||
|
final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory
|
||||||
|
.createRetryPolicy(serviceId, loadBalancerClient);
|
||||||
|
RetryTemplate retryTemplate = buildRetryTemplate(serviceId, request, retryPolicy);
|
||||||
|
return retryTemplate.execute(context -> {
|
||||||
|
Request feignRequest = null;
|
||||||
|
// On retries the policy will choose the server and set it in the context
|
||||||
|
// and extract the server and update the request being made
|
||||||
|
if (context instanceof LoadBalancedRetryContext) {
|
||||||
|
ServiceInstance serviceInstance = ((LoadBalancedRetryContext) context)
|
||||||
|
.getServiceInstance();
|
||||||
|
if (serviceInstance != null) {
|
||||||
|
if (LOG.isDebugEnabled()) {
|
||||||
|
LOG.debug(String.format(
|
||||||
|
"Using service instance from LoadBalancedRetryContext: %s",
|
||||||
|
serviceInstance));
|
||||||
|
}
|
||||||
|
String reconstructedUrl = loadBalancerClient
|
||||||
|
.reconstructURI(serviceInstance, originalUri).toString();
|
||||||
|
feignRequest = buildRequest(request, reconstructedUrl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (feignRequest == null) {
|
||||||
|
if (LOG.isWarnEnabled()) {
|
||||||
|
LOG.warn(
|
||||||
|
"Service instance was not resolved, executing the original request");
|
||||||
|
}
|
||||||
|
feignRequest = request;
|
||||||
|
}
|
||||||
|
Response response = delegate.execute(feignRequest, options);
|
||||||
|
int responseStatus = response.status();
|
||||||
|
if (retryPolicy != null && retryPolicy.retryableStatusCode(responseStatus)) {
|
||||||
|
if (LOG.isDebugEnabled()) {
|
||||||
|
LOG.debug(
|
||||||
|
String.format("Retrying on status code: %d", responseStatus));
|
||||||
|
}
|
||||||
|
response.close();
|
||||||
|
throw new RetryableStatusCodeException(serviceId, responseStatus,
|
||||||
|
response, URI.create(request.url()));
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}, new LoadBalancedRecoveryCallback<Response, Response>() {
|
||||||
|
@Override
|
||||||
|
protected Response createResponse(Response response, URI uri) {
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Request buildRequest(Request request, String reconstructedUrl) {
|
||||||
|
return Request.create(request.httpMethod(), reconstructedUrl, request.headers(),
|
||||||
|
request.body(), request.charset(), request.requestTemplate());
|
||||||
|
}
|
||||||
|
|
||||||
|
private RetryTemplate buildRetryTemplate(String serviceId, Request request,
|
||||||
|
LoadBalancedRetryPolicy retryPolicy) {
|
||||||
|
RetryTemplate retryTemplate = new RetryTemplate();
|
||||||
|
BackOffPolicy backOffPolicy = this.loadBalancedRetryFactory
|
||||||
|
.createBackOffPolicy(serviceId);
|
||||||
|
retryTemplate.setBackOffPolicy(
|
||||||
|
backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
|
||||||
|
RetryListener[] retryListeners = this.loadBalancedRetryFactory
|
||||||
|
.createRetryListeners(serviceId);
|
||||||
|
if (retryListeners != null && retryListeners.length != 0) {
|
||||||
|
retryTemplate.setListeners(retryListeners);
|
||||||
|
}
|
||||||
|
|
||||||
|
retryTemplate.setRetryPolicy(retryPolicy == null ? new NeverRetryPolicy()
|
||||||
|
: new InterceptorRetryPolicy(toHttpRequest(request), retryPolicy,
|
||||||
|
loadBalancerClient, serviceId));
|
||||||
|
return retryTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Visible for Sleuth instrumentation
|
||||||
|
public Client getDelegate() {
|
||||||
|
return delegate;
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpRequest toHttpRequest(Request request) {
|
||||||
|
return new HttpRequest() {
|
||||||
|
@Override
|
||||||
|
public HttpMethod getMethod() {
|
||||||
|
return HttpMethod.resolve(request.httpMethod().name());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getMethodValue() {
|
||||||
|
return getMethod().name();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public URI getURI() {
|
||||||
|
return URI.create(request.url());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public HttpHeaders getHeaders() {
|
||||||
|
Map<String, List<String>> headers = new HashMap<>();
|
||||||
|
Map<String, Collection<String>> feignHeaders = request.headers();
|
||||||
|
for (String key : feignHeaders.keySet()) {
|
||||||
|
headers.put(key, new ArrayList<>(feignHeaders.get(key)));
|
||||||
|
}
|
||||||
|
HttpHeaders httpHeaders = new HttpHeaders();
|
||||||
|
httpHeaders.putAll(headers);
|
||||||
|
return httpHeaders;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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.
|
||||||
|
|||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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.context.annotation.Configuration;
|
|||||||
/**
|
/**
|
||||||
* @author Spencer Gibb
|
* @author Spencer Gibb
|
||||||
*/
|
*/
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
class DefaultFeignLoadBalancedConfiguration {
|
class DefaultFeignLoadBalancedConfiguration {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
|||||||
+4
-5
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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,6 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import com.netflix.client.AbstractLoadBalancerAwareClient;
|
import com.netflix.client.AbstractLoadBalancerAwareClient;
|
||||||
import com.netflix.client.ClientException;
|
|
||||||
import com.netflix.client.ClientRequest;
|
import com.netflix.client.ClientRequest;
|
||||||
import com.netflix.client.IResponse;
|
import com.netflix.client.IResponse;
|
||||||
import com.netflix.client.RequestSpecificRetryHandler;
|
import com.netflix.client.RequestSpecificRetryHandler;
|
||||||
@@ -134,7 +133,7 @@ public class FeignLoadBalancer extends
|
|||||||
Map<String, Collection<String>> headers = new LinkedHashMap<>(
|
Map<String, Collection<String>> headers = new LinkedHashMap<>(
|
||||||
request.headers());
|
request.headers());
|
||||||
return Request.create(request.httpMethod(), getUri().toASCIIString(), headers,
|
return Request.create(request.httpMethod(), getUri().toASCIIString(), headers,
|
||||||
request.requestBody());
|
request.body(), request.charset(), request.requestTemplate());
|
||||||
}
|
}
|
||||||
|
|
||||||
Request toRequest() {
|
Request toRequest() {
|
||||||
@@ -169,7 +168,7 @@ public class FeignLoadBalancer extends
|
|||||||
Map<String, Collection<String>> feignHeaders = RibbonRequest.this
|
Map<String, Collection<String>> feignHeaders = RibbonRequest.this
|
||||||
.toRequest().headers();
|
.toRequest().headers();
|
||||||
for (String key : feignHeaders.keySet()) {
|
for (String key : feignHeaders.keySet()) {
|
||||||
headers.put(key, new ArrayList<String>(feignHeaders.get(key)));
|
headers.put(key, new ArrayList<>(feignHeaders.get(key)));
|
||||||
}
|
}
|
||||||
HttpHeaders httpHeaders = new HttpHeaders();
|
HttpHeaders httpHeaders = new HttpHeaders();
|
||||||
httpHeaders.putAll(headers);
|
httpHeaders.putAll(headers);
|
||||||
@@ -206,7 +205,7 @@ public class FeignLoadBalancer extends
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object getPayload() throws ClientException {
|
public Object getPayload() {
|
||||||
return this.response.body();
|
return this.response.body();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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.
|
||||||
|
|||||||
+6
-2
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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 org.springframework.boot.autoconfigure.AutoConfigureBefore;
|
|||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
import org.springframework.boot.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.netflix.ribbon.SpringClientFactory;
|
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
|
||||||
@@ -39,9 +40,12 @@ import org.springframework.context.annotation.Primary;
|
|||||||
* load balancer.
|
* load balancer.
|
||||||
*
|
*
|
||||||
* @author Dave Syer
|
* @author Dave Syer
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
*/
|
*/
|
||||||
@ConditionalOnClass({ ILoadBalancer.class, Feign.class })
|
@ConditionalOnClass({ ILoadBalancer.class, Feign.class })
|
||||||
@Configuration
|
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.ribbon.enabled",
|
||||||
|
matchIfMissing = true)
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
@AutoConfigureBefore(FeignAutoConfiguration.class)
|
@AutoConfigureBefore(FeignAutoConfiguration.class)
|
||||||
@EnableConfigurationProperties({ FeignHttpClientProperties.class })
|
@EnableConfigurationProperties({ FeignHttpClientProperties.class })
|
||||||
// Order is important here, last should be the default, first should be optional
|
// Order is important here, last should be the default, first should be optional
|
||||||
|
|||||||
+6
-96
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -16,37 +16,27 @@
|
|||||||
|
|
||||||
package org.springframework.cloud.openfeign.ribbon;
|
package org.springframework.cloud.openfeign.ribbon;
|
||||||
|
|
||||||
import java.util.Timer;
|
|
||||||
import java.util.TimerTask;
|
|
||||||
|
|
||||||
import javax.annotation.PreDestroy;
|
|
||||||
|
|
||||||
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;
|
||||||
import org.apache.http.client.config.RequestConfig;
|
|
||||||
import org.apache.http.config.RegistryBuilder;
|
|
||||||
import org.apache.http.conn.HttpClientConnectionManager;
|
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory;
|
|
||||||
import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory;
|
|
||||||
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
|
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
|
||||||
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
|
import org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration;
|
||||||
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;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Spencer Gibb
|
* @author Spencer Gibb
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
*/
|
*/
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
@ConditionalOnClass(ApacheHttpClient.class)
|
@ConditionalOnClass(ApacheHttpClient.class)
|
||||||
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
|
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
|
||||||
|
@Import(HttpClientFeignConfiguration.class)
|
||||||
class HttpClientFeignLoadBalancedConfiguration {
|
class HttpClientFeignLoadBalancedConfiguration {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@@ -57,84 +47,4 @@ class HttpClientFeignLoadBalancedConfiguration {
|
|||||||
return new LoadBalancerFeignClient(delegate, cachingFactory, clientFactory);
|
return new LoadBalancerFeignClient(delegate, cachingFactory, clientFactory);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Configuration
|
|
||||||
@ConditionalOnMissingBean(CloseableHttpClient.class)
|
|
||||||
protected static class HttpClientFeignConfiguration {
|
|
||||||
|
|
||||||
private final Timer connectionManagerTimer = new Timer(
|
|
||||||
"FeignApacheHttpClientConfiguration.connectionManagerTimer", true);
|
|
||||||
|
|
||||||
private CloseableHttpClient httpClient;
|
|
||||||
|
|
||||||
@Autowired(required = false)
|
|
||||||
private RegistryBuilder registryBuilder;
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
@ConditionalOnMissingBean(HttpClientConnectionManager.class)
|
|
||||||
public HttpClientConnectionManager connectionManager(
|
|
||||||
ApacheHttpClientConnectionManagerFactory connectionManagerFactory,
|
|
||||||
FeignHttpClientProperties httpClientProperties) {
|
|
||||||
final HttpClientConnectionManager connectionManager = connectionManagerFactory
|
|
||||||
.newConnectionManager(httpClientProperties.isDisableSslValidation(),
|
|
||||||
httpClientProperties.getMaxConnections(),
|
|
||||||
httpClientProperties.getMaxConnectionsPerRoute(),
|
|
||||||
httpClientProperties.getTimeToLive(),
|
|
||||||
httpClientProperties.getTimeToLiveUnit(),
|
|
||||||
this.registryBuilder);
|
|
||||||
this.connectionManagerTimer.schedule(new TimerTask() {
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
connectionManager.closeExpiredConnections();
|
|
||||||
}
|
|
||||||
}, 30000, httpClientProperties.getConnectionTimerRepeat());
|
|
||||||
return connectionManager;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
@ConditionalOnProperty(value = "feign.compression.response.enabled",
|
|
||||||
havingValue = "true")
|
|
||||||
public CloseableHttpClient customHttpClient(
|
|
||||||
HttpClientConnectionManager httpClientConnectionManager,
|
|
||||||
FeignHttpClientProperties httpClientProperties) {
|
|
||||||
HttpClientBuilder builder = HttpClientBuilder.create()
|
|
||||||
.disableCookieManagement().useSystemProperties();
|
|
||||||
this.httpClient = createClient(builder, httpClientConnectionManager,
|
|
||||||
httpClientProperties);
|
|
||||||
return this.httpClient;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
@ConditionalOnProperty(value = "feign.compression.response.enabled",
|
|
||||||
havingValue = "false", matchIfMissing = true)
|
|
||||||
public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory,
|
|
||||||
HttpClientConnectionManager httpClientConnectionManager,
|
|
||||||
FeignHttpClientProperties httpClientProperties) {
|
|
||||||
this.httpClient = createClient(httpClientFactory.createBuilder(),
|
|
||||||
httpClientConnectionManager, httpClientProperties);
|
|
||||||
return this.httpClient;
|
|
||||||
}
|
|
||||||
|
|
||||||
private CloseableHttpClient createClient(HttpClientBuilder builder,
|
|
||||||
HttpClientConnectionManager httpClientConnectionManager,
|
|
||||||
FeignHttpClientProperties httpClientProperties) {
|
|
||||||
RequestConfig defaultRequestConfig = RequestConfig.custom()
|
|
||||||
.setConnectTimeout(httpClientProperties.getConnectionTimeout())
|
|
||||||
.setRedirectsEnabled(httpClientProperties.isFollowRedirects())
|
|
||||||
.build();
|
|
||||||
CloseableHttpClient httpClient = builder
|
|
||||||
.setDefaultRequestConfig(defaultRequestConfig)
|
|
||||||
.setConnectionManager(httpClientConnectionManager).build();
|
|
||||||
return httpClient;
|
|
||||||
}
|
|
||||||
|
|
||||||
@PreDestroy
|
|
||||||
public void destroy() throws Exception {
|
|
||||||
this.connectionManagerTimer.cancel();
|
|
||||||
if (this.httpClient != null) {
|
|
||||||
this.httpClient.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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.
|
||||||
|
|||||||
+6
-51
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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,30 +16,26 @@
|
|||||||
|
|
||||||
package org.springframework.cloud.openfeign.ribbon;
|
package org.springframework.cloud.openfeign.ribbon;
|
||||||
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import javax.annotation.PreDestroy;
|
|
||||||
|
|
||||||
import feign.Client;
|
import feign.Client;
|
||||||
import feign.okhttp.OkHttpClient;
|
import feign.okhttp.OkHttpClient;
|
||||||
import okhttp3.ConnectionPool;
|
|
||||||
|
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory;
|
|
||||||
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
|
|
||||||
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
|
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
|
||||||
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
|
import org.springframework.cloud.openfeign.clientconfig.OkHttpFeignConfiguration;
|
||||||
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;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Spencer Gibb
|
* @author Spencer Gibb
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
*/
|
*/
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
@ConditionalOnClass(OkHttpClient.class)
|
@ConditionalOnClass(OkHttpClient.class)
|
||||||
@ConditionalOnProperty("feign.okhttp.enabled")
|
@ConditionalOnProperty("feign.okhttp.enabled")
|
||||||
|
@Import(OkHttpFeignConfiguration.class)
|
||||||
class OkHttpFeignLoadBalancedConfiguration {
|
class OkHttpFeignLoadBalancedConfiguration {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@@ -50,45 +46,4 @@ class OkHttpFeignLoadBalancedConfiguration {
|
|||||||
return new LoadBalancerFeignClient(delegate, cachingFactory, clientFactory);
|
return new LoadBalancerFeignClient(delegate, cachingFactory, clientFactory);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Configuration
|
|
||||||
@ConditionalOnMissingBean(okhttp3.OkHttpClient.class)
|
|
||||||
protected static class OkHttpFeignConfiguration {
|
|
||||||
|
|
||||||
private okhttp3.OkHttpClient okHttpClient;
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
@ConditionalOnMissingBean(ConnectionPool.class)
|
|
||||||
public ConnectionPool httpClientConnectionPool(
|
|
||||||
FeignHttpClientProperties httpClientProperties,
|
|
||||||
OkHttpClientConnectionPoolFactory connectionPoolFactory) {
|
|
||||||
Integer maxTotalConnections = httpClientProperties.getMaxConnections();
|
|
||||||
Long timeToLive = httpClientProperties.getTimeToLive();
|
|
||||||
TimeUnit ttlUnit = httpClientProperties.getTimeToLiveUnit();
|
|
||||||
return connectionPoolFactory.create(maxTotalConnections, timeToLive, ttlUnit);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory,
|
|
||||||
ConnectionPool connectionPool,
|
|
||||||
FeignHttpClientProperties httpClientProperties) {
|
|
||||||
Boolean followRedirects = httpClientProperties.isFollowRedirects();
|
|
||||||
Integer connectTimeout = httpClientProperties.getConnectionTimeout();
|
|
||||||
this.okHttpClient = httpClientFactory
|
|
||||||
.createBuilder(httpClientProperties.isDisableSslValidation())
|
|
||||||
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
|
|
||||||
.followRedirects(followRedirects).connectionPool(connectionPool)
|
|
||||||
.build();
|
|
||||||
return this.okHttpClient;
|
|
||||||
}
|
|
||||||
|
|
||||||
@PreDestroy
|
|
||||||
public void destroy() {
|
|
||||||
if (this.okHttpClient != null) {
|
|
||||||
this.okHttpClient.dispatcher().executorService().shutdown();
|
|
||||||
this.okHttpClient.connectionPool().evictAll();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-34
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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,8 +36,6 @@ import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser;
|
|||||||
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
|
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
|
||||||
import org.springframework.cloud.netflix.ribbon.RibbonProperties;
|
import org.springframework.cloud.netflix.ribbon.RibbonProperties;
|
||||||
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
|
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
|
||||||
import org.springframework.retry.RetryCallback;
|
|
||||||
import org.springframework.retry.RetryContext;
|
|
||||||
import org.springframework.retry.RetryListener;
|
import org.springframework.retry.RetryListener;
|
||||||
import org.springframework.retry.backoff.BackOffPolicy;
|
import org.springframework.retry.backoff.BackOffPolicy;
|
||||||
import org.springframework.retry.backoff.NoBackOffPolicy;
|
import org.springframework.retry.backoff.NoBackOffPolicy;
|
||||||
@@ -91,39 +89,34 @@ public class RetryableFeignLoadBalancer extends FeignLoadBalancer
|
|||||||
retryTemplate.setRetryPolicy(retryPolicy == null ? new NeverRetryPolicy()
|
retryTemplate.setRetryPolicy(retryPolicy == null ? new NeverRetryPolicy()
|
||||||
: new FeignRetryPolicy(request.toHttpRequest(), retryPolicy, this,
|
: new FeignRetryPolicy(request.toHttpRequest(), retryPolicy, this,
|
||||||
this.getClientName()));
|
this.getClientName()));
|
||||||
return retryTemplate.execute(new RetryCallback<RibbonResponse, IOException>() {
|
return retryTemplate.execute(retryContext -> {
|
||||||
@Override
|
Request feignRequest = null;
|
||||||
public RibbonResponse doWithRetry(RetryContext retryContext)
|
// on retries the policy will choose the server and set it in the context
|
||||||
throws IOException {
|
// extract the server and update the request being made
|
||||||
Request feignRequest = null;
|
if (retryContext instanceof LoadBalancedRetryContext) {
|
||||||
// on retries the policy will choose the server and set it in the context
|
ServiceInstance service = ((LoadBalancedRetryContext) retryContext)
|
||||||
// extract the server and update the request being made
|
.getServiceInstance();
|
||||||
if (retryContext instanceof LoadBalancedRetryContext) {
|
if (service != null) {
|
||||||
ServiceInstance service = ((LoadBalancedRetryContext) retryContext)
|
feignRequest = ((RibbonRequest) request
|
||||||
.getServiceInstance();
|
.replaceUri(reconstructURIWithServer(
|
||||||
if (service != null) {
|
new Server(service.getHost(), service.getPort()),
|
||||||
feignRequest = ((RibbonRequest) request
|
request.getUri()))).toRequest();
|
||||||
.replaceUri(reconstructURIWithServer(
|
|
||||||
new Server(service.getHost(), service.getPort()),
|
|
||||||
request.getUri()))).toRequest();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (feignRequest == null) {
|
|
||||||
feignRequest = request.toRequest();
|
|
||||||
}
|
|
||||||
Response response = request.client().execute(feignRequest, options);
|
|
||||||
if (retryPolicy != null
|
|
||||||
&& retryPolicy.retryableStatusCode(response.status())) {
|
|
||||||
byte[] byteArray = response.body() == null ? new byte[] {}
|
|
||||||
: StreamUtils
|
|
||||||
.copyToByteArray(response.body().asInputStream());
|
|
||||||
response.close();
|
|
||||||
throw new RibbonResponseStatusCodeException(
|
|
||||||
RetryableFeignLoadBalancer.this.clientName, response,
|
|
||||||
byteArray, request.getUri());
|
|
||||||
}
|
|
||||||
return new RibbonResponse(request.getUri(), response);
|
|
||||||
}
|
}
|
||||||
|
if (feignRequest == null) {
|
||||||
|
feignRequest = request.toRequest();
|
||||||
|
}
|
||||||
|
Response response = request.client().execute(feignRequest, options);
|
||||||
|
if (retryPolicy != null
|
||||||
|
&& retryPolicy.retryableStatusCode(response.status())) {
|
||||||
|
byte[] byteArray = response.body() == null ? new byte[] {}
|
||||||
|
: StreamUtils.copyToByteArray(response.body().asInputStream());
|
||||||
|
response.close();
|
||||||
|
throw new RibbonResponseStatusCodeException(
|
||||||
|
RetryableFeignLoadBalancer.this.clientName, response, byteArray,
|
||||||
|
request.getUri());
|
||||||
|
}
|
||||||
|
return new RibbonResponse(request.getUri(), response);
|
||||||
}, new LoadBalancedRecoveryCallback<RibbonResponse, Response>() {
|
}, new LoadBalancedRecoveryCallback<RibbonResponse, Response>() {
|
||||||
@Override
|
@Override
|
||||||
protected RibbonResponse createResponse(Response response, URI uri) {
|
protected RibbonResponse createResponse(Response response, URI uri) {
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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
@@ -0,0 +1,83 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.support;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
|
||||||
|
import feign.codec.EncodeException;
|
||||||
|
import feign.form.multipart.AbstractWriter;
|
||||||
|
import feign.form.multipart.Output;
|
||||||
|
import feign.form.util.PojoUtil;
|
||||||
|
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import static feign.form.ContentProcessor.CRLF;
|
||||||
|
import static feign.form.util.PojoUtil.isUserPojo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Darren Foong
|
||||||
|
*/
|
||||||
|
public abstract class AbstractFormWriter extends AbstractWriter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isApplicable(Object object) {
|
||||||
|
return !isTypeOrCollection(object, o -> o instanceof MultipartFile)
|
||||||
|
&& isTypeOrCollection(object, PojoUtil::isUserPojo);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void write(Output output, String key, Object object) throws EncodeException {
|
||||||
|
try {
|
||||||
|
String string = new StringBuilder()
|
||||||
|
.append("Content-Disposition: form-data; name=\"").append(key)
|
||||||
|
.append('"').append(CRLF).append("Content-Type: ")
|
||||||
|
.append(getContentType()).append("; charset=")
|
||||||
|
.append(output.getCharset().name()).append(CRLF).append(CRLF)
|
||||||
|
.append(writeAsString(object)).toString();
|
||||||
|
|
||||||
|
output.write(string);
|
||||||
|
}
|
||||||
|
catch (IOException e) {
|
||||||
|
throw new EncodeException(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract MediaType getContentType();
|
||||||
|
|
||||||
|
protected abstract String writeAsString(Object object) throws IOException;
|
||||||
|
|
||||||
|
private boolean isTypeOrCollection(Object object, Predicate<Object> isType) {
|
||||||
|
if (object.getClass().isArray()) {
|
||||||
|
Object[] array = (Object[]) object;
|
||||||
|
|
||||||
|
return array.length > 1 && isType.test(array[0]);
|
||||||
|
}
|
||||||
|
else if (object instanceof Iterable) {
|
||||||
|
Iterable<?> iterable = (Iterable<?>) object;
|
||||||
|
Iterator<?> iterator = iterable.iterator();
|
||||||
|
|
||||||
|
return iterator.hasNext() && isType.test(iterator.next());
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return isType.test(object);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+85
@@ -0,0 +1,85 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.support;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.lang.reflect.Type;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.zip.GZIPInputStream;
|
||||||
|
|
||||||
|
import feign.FeignException;
|
||||||
|
import feign.Response;
|
||||||
|
import feign.codec.Decoder;
|
||||||
|
|
||||||
|
import org.springframework.cloud.openfeign.encoding.HttpEncoding;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When response is compressed as gzip, this decompresses and uses {@link SpringDecoder}
|
||||||
|
* to decode.
|
||||||
|
*
|
||||||
|
* @author Jaesik Kim
|
||||||
|
*/
|
||||||
|
public class DefaultGzipDecoder implements Decoder {
|
||||||
|
|
||||||
|
private Decoder decoder;
|
||||||
|
|
||||||
|
public DefaultGzipDecoder(Decoder decoder) {
|
||||||
|
this.decoder = decoder;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object decode(final Response response, Type type)
|
||||||
|
throws IOException, FeignException {
|
||||||
|
Collection<String> encoding = response.headers()
|
||||||
|
.containsKey(HttpEncoding.CONTENT_ENCODING_HEADER)
|
||||||
|
? response.headers().get(HttpEncoding.CONTENT_ENCODING_HEADER)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
if (encoding != null) {
|
||||||
|
if (encoding.contains(HttpEncoding.GZIP_ENCODING)) {
|
||||||
|
String decompressedBody = decompress(response);
|
||||||
|
if (decompressedBody != null) {
|
||||||
|
Response decompressedResponse = response.toBuilder()
|
||||||
|
.body(decompressedBody.getBytes()).build();
|
||||||
|
return decoder.decode(decompressedResponse, type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return decoder.decode(response, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String decompress(Response response) throws IOException {
|
||||||
|
if (response.body() == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try (GZIPInputStream gzipInputStream = new GZIPInputStream(
|
||||||
|
response.body().asInputStream());
|
||||||
|
BufferedReader reader = new BufferedReader(
|
||||||
|
new InputStreamReader(gzipInputStream, StandardCharsets.UTF_8))) {
|
||||||
|
String outputString = "";
|
||||||
|
String line;
|
||||||
|
while ((line = reader.readLine()) != null) {
|
||||||
|
outputString += line;
|
||||||
|
}
|
||||||
|
return outputString;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.support;
|
||||||
|
|
||||||
|
import feign.codec.Decoder;
|
||||||
|
import feign.optionals.OptionalDecoder;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.ObjectFactory;
|
||||||
|
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
|
||||||
|
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configures Default Gzip Decoder.
|
||||||
|
*
|
||||||
|
* @author Jaesik Kim
|
||||||
|
*/
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@ConditionalOnProperty("feign.compression.response.enabled")
|
||||||
|
// The OK HTTP client uses "transparent" compression.
|
||||||
|
// If the accept-encoding header is present, it disables transparent compression
|
||||||
|
@ConditionalOnMissingBean(type = "okhttp3.OkHttpClient")
|
||||||
|
@AutoConfigureAfter(FeignAutoConfiguration.class)
|
||||||
|
public class DefaultGzipDecoderConfiguration {
|
||||||
|
|
||||||
|
private ObjectFactory<HttpMessageConverters> messageConverters;
|
||||||
|
|
||||||
|
public DefaultGzipDecoderConfiguration(
|
||||||
|
ObjectFactory<HttpMessageConverters> messageConverters) {
|
||||||
|
this.messageConverters = messageConverters;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean
|
||||||
|
@ConditionalOnProperty("feign.compression.response.useGzipDecoder")
|
||||||
|
public Decoder defaultGzipDecoder() {
|
||||||
|
return new OptionalDecoder(new ResponseEntityDecoder(
|
||||||
|
new DefaultGzipDecoder(new SpringDecoder(messageConverters))));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
|
|||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.support;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Darren Foong
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class JsonFormWriter extends AbstractFormWriter {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected MediaType getContentType() {
|
||||||
|
return MediaType.APPLICATION_JSON;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String writeAsString(Object object) throws IOException {
|
||||||
|
return objectMapper.writeValueAsString(object);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+19
-7
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2018 the original author or authors.
|
* Copyright 2013-2020 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.util.Iterator;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
import com.fasterxml.jackson.core.Version;
|
import com.fasterxml.jackson.core.Version;
|
||||||
@@ -33,9 +34,10 @@ import org.springframework.data.domain.Pageable;
|
|||||||
import org.springframework.data.domain.Sort;
|
import org.springframework.data.domain.Sort;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This jackson module provides support to deserialize spring {@link Page} objects.
|
* This Jackson module provides support to deserialize Spring {@link Page} objects.
|
||||||
*
|
*
|
||||||
* @author Pascal Büttiker
|
* @author Pascal Büttiker
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
*/
|
*/
|
||||||
public class PageJacksonModule extends Module {
|
public class PageJacksonModule extends Module {
|
||||||
|
|
||||||
@@ -64,10 +66,20 @@ public class PageJacksonModule extends Module {
|
|||||||
private final Page<T> delegate;
|
private final Page<T> delegate;
|
||||||
|
|
||||||
SimplePageImpl(@JsonProperty("content") List<T> content,
|
SimplePageImpl(@JsonProperty("content") List<T> content,
|
||||||
@JsonProperty("page") int number, @JsonProperty("size") int size,
|
@JsonProperty("number") int number, @JsonProperty("size") int size,
|
||||||
@JsonProperty("totalElements") long totalElements) {
|
@JsonProperty("totalElements") @JsonAlias({ "total-elements",
|
||||||
delegate = new PageImpl<>(content, PageRequest.of(number, size),
|
"total_elements", "totalelements",
|
||||||
totalElements);
|
"TotalElements" }) long totalElements,
|
||||||
|
@JsonProperty("sort") Sort sort) {
|
||||||
|
PageRequest pageRequest;
|
||||||
|
if (sort != null) {
|
||||||
|
pageRequest = PageRequest.of(number, size, sort);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
pageRequest = PageRequest.of(number, size);
|
||||||
|
}
|
||||||
|
delegate = new PageImpl<>(content, pageRequest, totalElements);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@JsonProperty
|
@JsonProperty
|
||||||
@@ -82,7 +94,7 @@ public class PageJacksonModule extends Module {
|
|||||||
return delegate.getTotalElements();
|
return delegate.getTotalElements();
|
||||||
}
|
}
|
||||||
|
|
||||||
@JsonProperty("page")
|
@JsonProperty
|
||||||
@Override
|
@Override
|
||||||
public int getNumber() {
|
public int getNumber() {
|
||||||
return delegate.getNumber();
|
return delegate.getNumber();
|
||||||
|
|||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2018 the original author or authors.
|
* Copyright 2013-2020 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.
|
||||||
@@ -120,7 +120,7 @@ public class PageableSpringEncoder implements Encoder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (Sort.Order order : sort) {
|
for (Sort.Order order : sort) {
|
||||||
sortQueries.add(order.getProperty() + "," + order.getDirection());
|
sortQueries.add(order.getProperty() + "%2C" + order.getDirection());
|
||||||
}
|
}
|
||||||
if (!sortQueries.isEmpty()) {
|
if (!sortQueries.isEmpty()) {
|
||||||
template.query(sortParameter, sortQueries);
|
template.query(sortParameter, sortQueries);
|
||||||
|
|||||||
+4
-4
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2021 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -26,16 +26,16 @@ import feign.Response;
|
|||||||
import feign.codec.Decoder;
|
import feign.codec.Decoder;
|
||||||
|
|
||||||
import org.springframework.http.HttpEntity;
|
import org.springframework.http.HttpEntity;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.util.LinkedMultiValueMap;
|
|
||||||
import org.springframework.util.MultiValueMap;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decoder adds compatibility for Spring MVC's ResponseEntity to any other decoder via
|
* Decoder adds compatibility for Spring MVC's ResponseEntity to any other decoder via
|
||||||
* composition.
|
* composition.
|
||||||
*
|
*
|
||||||
* @author chad jaros
|
* @author chad jaros
|
||||||
|
* @author Olga Maciaszek-Sharma
|
||||||
*/
|
*/
|
||||||
public class ResponseEntityDecoder implements Decoder {
|
public class ResponseEntityDecoder implements Decoder {
|
||||||
|
|
||||||
@@ -81,7 +81,7 @@ public class ResponseEntityDecoder implements Decoder {
|
|||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private <T> ResponseEntity<T> createResponse(Object instance, Response response) {
|
private <T> ResponseEntity<T> createResponse(Object instance, Response response) {
|
||||||
|
|
||||||
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
|
HttpHeaders headers = new HttpHeaders();
|
||||||
for (String key : response.headers().keySet()) {
|
for (String key : response.headers().keySet()) {
|
||||||
headers.put(key, new LinkedList<>(response.headers().get(key)));
|
headers.put(key, new LinkedList<>(response.headers().get(key)));
|
||||||
}
|
}
|
||||||
|
|||||||
+56
@@ -0,0 +1,56 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.support;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.Version;
|
||||||
|
import com.fasterxml.jackson.databind.Module;
|
||||||
|
import com.fasterxml.jackson.databind.module.SimpleDeserializers;
|
||||||
|
import com.fasterxml.jackson.databind.module.SimpleSerializers;
|
||||||
|
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This Jackson module provides support for serializing and deserializing for Spring
|
||||||
|
* {@link Sort} object.
|
||||||
|
*
|
||||||
|
* @author Can Bezmen
|
||||||
|
*/
|
||||||
|
public class SortJacksonModule extends Module {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getModuleName() {
|
||||||
|
return "SortModule";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Version version() {
|
||||||
|
return new Version(0, 1, 0, "", null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setupModule(SetupContext context) {
|
||||||
|
SimpleSerializers serializers = new SimpleSerializers();
|
||||||
|
serializers.addSerializer(Sort.class, new SortJsonComponent.SortSerializer());
|
||||||
|
context.addSerializers(serializers);
|
||||||
|
|
||||||
|
SimpleDeserializers deserializers = new SimpleDeserializers();
|
||||||
|
deserializers.addDeserializer(Sort.class,
|
||||||
|
new SortJsonComponent.SortDeserializer());
|
||||||
|
context.addDeserializers(deserializers);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+95
@@ -0,0 +1,95 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign.support;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonGenerator;
|
||||||
|
import com.fasterxml.jackson.core.JsonParser;
|
||||||
|
import com.fasterxml.jackson.core.TreeNode;
|
||||||
|
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||||
|
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||||
|
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||||
|
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||||
|
import feign.codec.EncodeException;
|
||||||
|
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This class provides provides support for serializing and deserializing for Spring
|
||||||
|
* {@link Sort} object.
|
||||||
|
*
|
||||||
|
* @author Can Bezmen
|
||||||
|
*/
|
||||||
|
public class SortJsonComponent {
|
||||||
|
|
||||||
|
public static class SortSerializer extends JsonSerializer<Sort> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void serialize(Sort value, JsonGenerator gen,
|
||||||
|
SerializerProvider serializers) throws IOException {
|
||||||
|
gen.writeStartArray();
|
||||||
|
value.iterator().forEachRemaining(v -> {
|
||||||
|
try {
|
||||||
|
gen.writeObject(v);
|
||||||
|
}
|
||||||
|
catch (IOException e) {
|
||||||
|
throw new EncodeException("Couldn't serialize object " + v);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
gen.writeEndArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Class<Sort> handledType() {
|
||||||
|
return Sort.class;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class SortDeserializer extends JsonDeserializer<Sort> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Sort deserialize(JsonParser jsonParser,
|
||||||
|
DeserializationContext deserializationContext) throws IOException {
|
||||||
|
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
|
||||||
|
if (treeNode.isArray()) {
|
||||||
|
ArrayNode arrayNode = (ArrayNode) treeNode;
|
||||||
|
List<Sort.Order> orders = new ArrayList<>();
|
||||||
|
for (JsonNode jsonNode : arrayNode) {
|
||||||
|
Sort.Order order = new Sort.Order(
|
||||||
|
Sort.Direction.valueOf(jsonNode.get("direction").textValue()),
|
||||||
|
jsonNode.get("property").textValue());
|
||||||
|
orders.add(order);
|
||||||
|
}
|
||||||
|
return Sort.by(orders);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Class<Sort> handledType() {
|
||||||
|
return Sort.class;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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.
|
||||||
|
|||||||
+86
-38
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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,10 +35,13 @@ import org.apache.commons.logging.LogFactory;
|
|||||||
|
|
||||||
import org.springframework.beans.factory.ObjectFactory;
|
import org.springframework.beans.factory.ObjectFactory;
|
||||||
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
|
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
|
||||||
|
import org.springframework.cloud.openfeign.encoding.HttpEncoding;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.HttpOutputMessage;
|
import org.springframework.http.HttpOutputMessage;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
|
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
|
||||||
|
import org.springframework.http.converter.GenericHttpMessageConverter;
|
||||||
|
import org.springframework.http.converter.HttpMessageConversionException;
|
||||||
import org.springframework.http.converter.HttpMessageConverter;
|
import org.springframework.http.converter.HttpMessageConverter;
|
||||||
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
|
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
@@ -49,16 +52,26 @@ import static org.springframework.cloud.openfeign.support.FeignUtils.getHttpHead
|
|||||||
/**
|
/**
|
||||||
* @author Spencer Gibb
|
* @author Spencer Gibb
|
||||||
* @author Scien Jus
|
* @author Scien Jus
|
||||||
|
* @author Ahmad Mozafarnia
|
||||||
|
* @author Aaron Whiteside
|
||||||
|
* @author Darren Foong
|
||||||
*/
|
*/
|
||||||
public class SpringEncoder implements Encoder {
|
public class SpringEncoder implements Encoder {
|
||||||
|
|
||||||
private static final Log log = LogFactory.getLog(SpringEncoder.class);
|
private static final Log log = LogFactory.getLog(SpringEncoder.class);
|
||||||
|
|
||||||
private final SpringFormEncoder springFormEncoder = new SpringFormEncoder();
|
private final SpringFormEncoder springFormEncoder;
|
||||||
|
|
||||||
private ObjectFactory<HttpMessageConverters> messageConverters;
|
private final ObjectFactory<HttpMessageConverters> messageConverters;
|
||||||
|
|
||||||
public SpringEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
|
public SpringEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
|
||||||
|
this.springFormEncoder = new SpringFormEncoder();
|
||||||
|
this.messageConverters = messageConverters;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SpringEncoder(SpringFormEncoder springFormEncoder,
|
||||||
|
ObjectFactory<HttpMessageConverters> messageConverters) {
|
||||||
|
this.springFormEncoder = springFormEncoder;
|
||||||
this.messageConverters = messageConverters;
|
this.messageConverters = messageConverters;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,8 +80,8 @@ public class SpringEncoder implements Encoder {
|
|||||||
throws EncodeException {
|
throws EncodeException {
|
||||||
// template.body(conversionService.convert(object, String.class));
|
// template.body(conversionService.convert(object, String.class));
|
||||||
if (requestBody != null) {
|
if (requestBody != null) {
|
||||||
Class<?> requestType = requestBody.getClass();
|
Collection<String> contentTypes = request.headers()
|
||||||
Collection<String> contentTypes = request.headers().get("Content-Type");
|
.get(HttpEncoding.CONTENT_TYPE);
|
||||||
|
|
||||||
MediaType requestContentType = null;
|
MediaType requestContentType = null;
|
||||||
if (contentTypes != null && !contentTypes.isEmpty()) {
|
if (contentTypes != null && !contentTypes.isEmpty()) {
|
||||||
@@ -76,44 +89,36 @@ public class SpringEncoder implements Encoder {
|
|||||||
requestContentType = MediaType.valueOf(type);
|
requestContentType = MediaType.valueOf(type);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (bodyType != null && bodyType.equals(MultipartFile.class)) {
|
if (Objects.equals(requestContentType, MediaType.MULTIPART_FORM_DATA)) {
|
||||||
if (Objects.equals(requestContentType, MediaType.MULTIPART_FORM_DATA)) {
|
this.springFormEncoder.encode(requestBody, bodyType, request);
|
||||||
this.springFormEncoder.encode(requestBody, bodyType, request);
|
return;
|
||||||
return;
|
}
|
||||||
}
|
else {
|
||||||
else {
|
if (bodyType == MultipartFile.class) {
|
||||||
String message = "Content-Type \"" + MediaType.MULTIPART_FORM_DATA
|
log.warn(
|
||||||
+ "\" not set for request body of type "
|
"For MultipartFile to be handled correctly, the 'consumes' parameter of @RequestMapping "
|
||||||
+ requestBody.getClass().getSimpleName();
|
+ "should be specified as MediaType.MULTIPART_FORM_DATA_VALUE");
|
||||||
throw new EncodeException(message);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (HttpMessageConverter<?> messageConverter : this.messageConverters
|
for (HttpMessageConverter messageConverter : this.messageConverters
|
||||||
.getObject().getConverters()) {
|
.getObject().getConverters()) {
|
||||||
if (messageConverter.canWrite(requestType, requestContentType)) {
|
FeignOutputMessage outputMessage;
|
||||||
if (log.isDebugEnabled()) {
|
try {
|
||||||
if (requestContentType != null) {
|
if (messageConverter instanceof GenericHttpMessageConverter) {
|
||||||
log.debug("Writing [" + requestBody + "] as \""
|
outputMessage = checkAndWrite(requestBody, bodyType,
|
||||||
+ requestContentType + "\" using [" + messageConverter
|
requestContentType,
|
||||||
+ "]");
|
(GenericHttpMessageConverter) messageConverter, request);
|
||||||
}
|
|
||||||
else {
|
|
||||||
log.debug("Writing [" + requestBody + "] using ["
|
|
||||||
+ messageConverter + "]");
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
else {
|
||||||
FeignOutputMessage outputMessage = new FeignOutputMessage(request);
|
outputMessage = checkAndWrite(requestBody, requestContentType,
|
||||||
try {
|
messageConverter, request);
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
HttpMessageConverter<Object> copy = (HttpMessageConverter<Object>) messageConverter;
|
|
||||||
copy.write(requestBody, requestContentType, outputMessage);
|
|
||||||
}
|
|
||||||
catch (IOException ex) {
|
|
||||||
throw new EncodeException("Error converting request body", ex);
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
catch (IOException | HttpMessageConversionException ex) {
|
||||||
|
throw new EncodeException("Error converting request body", ex);
|
||||||
|
}
|
||||||
|
if (outputMessage != null) {
|
||||||
// clear headers
|
// clear headers
|
||||||
request.headers(null);
|
request.headers(null);
|
||||||
// converters can modify headers, so update the request
|
// converters can modify headers, so update the request
|
||||||
@@ -139,7 +144,7 @@ public class SpringEncoder implements Encoder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
String message = "Could not write request: no suitable HttpMessageConverter "
|
String message = "Could not write request: no suitable HttpMessageConverter "
|
||||||
+ "found for request type [" + requestType.getName() + "]";
|
+ "found for request type [" + requestBody.getClass().getName() + "]";
|
||||||
if (requestContentType != null) {
|
if (requestContentType != null) {
|
||||||
message += " and content type [" + requestContentType + "]";
|
message += " and content type [" + requestContentType + "]";
|
||||||
}
|
}
|
||||||
@@ -147,6 +152,49 @@ public class SpringEncoder implements Encoder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private FeignOutputMessage checkAndWrite(Object body, MediaType contentType,
|
||||||
|
HttpMessageConverter converter, RequestTemplate request) throws IOException {
|
||||||
|
if (converter.canWrite(body.getClass(), contentType)) {
|
||||||
|
logBeforeWrite(body, contentType, converter);
|
||||||
|
FeignOutputMessage outputMessage = new FeignOutputMessage(request);
|
||||||
|
converter.write(body, contentType, outputMessage);
|
||||||
|
return outputMessage;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private FeignOutputMessage checkAndWrite(Object body, Type genericType,
|
||||||
|
MediaType contentType, GenericHttpMessageConverter converter,
|
||||||
|
RequestTemplate request) throws IOException {
|
||||||
|
if (converter.canWrite(genericType, body.getClass(), contentType)) {
|
||||||
|
logBeforeWrite(body, contentType, converter);
|
||||||
|
FeignOutputMessage outputMessage = new FeignOutputMessage(request);
|
||||||
|
converter.write(body, genericType, contentType, outputMessage);
|
||||||
|
return outputMessage;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void logBeforeWrite(Object requestBody, MediaType requestContentType,
|
||||||
|
HttpMessageConverter messageConverter) {
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
if (requestContentType != null) {
|
||||||
|
log.debug("Writing [" + requestBody + "] as \"" + requestContentType
|
||||||
|
+ "\" using [" + messageConverter + "]");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
log.debug(
|
||||||
|
"Writing [" + requestBody + "] using [" + messageConverter + "]");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private final class FeignOutputMessage implements HttpOutputMessage {
|
private final class FeignOutputMessage implements HttpOutputMessage {
|
||||||
|
|
||||||
private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||||
|
|||||||
+73
-25
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -28,6 +28,7 @@ import java.util.HashMap;
|
|||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
import feign.Contract;
|
import feign.Contract;
|
||||||
import feign.Feign;
|
import feign.Feign;
|
||||||
@@ -36,10 +37,14 @@ import feign.Param;
|
|||||||
import feign.Request;
|
import feign.Request;
|
||||||
|
|
||||||
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
|
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
|
||||||
|
import org.springframework.cloud.openfeign.CollectionFormat;
|
||||||
|
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;
|
||||||
import org.springframework.cloud.openfeign.annotation.RequestHeaderParameterProcessor;
|
import org.springframework.cloud.openfeign.annotation.RequestHeaderParameterProcessor;
|
||||||
import org.springframework.cloud.openfeign.annotation.RequestParamParameterProcessor;
|
import org.springframework.cloud.openfeign.annotation.RequestParamParameterProcessor;
|
||||||
|
import org.springframework.cloud.openfeign.annotation.RequestPartParameterProcessor;
|
||||||
|
import org.springframework.cloud.openfeign.encoding.HttpEncoding;
|
||||||
import org.springframework.context.ConfigurableApplicationContext;
|
import org.springframework.context.ConfigurableApplicationContext;
|
||||||
import org.springframework.context.ResourceLoaderAware;
|
import org.springframework.context.ResourceLoaderAware;
|
||||||
import org.springframework.core.DefaultParameterNameDiscoverer;
|
import org.springframework.core.DefaultParameterNameDiscoverer;
|
||||||
@@ -52,6 +57,8 @@ import org.springframework.core.convert.TypeDescriptor;
|
|||||||
import org.springframework.core.convert.support.DefaultConversionService;
|
import org.springframework.core.convert.support.DefaultConversionService;
|
||||||
import org.springframework.core.io.DefaultResourceLoader;
|
import org.springframework.core.io.DefaultResourceLoader;
|
||||||
import org.springframework.core.io.ResourceLoader;
|
import org.springframework.core.io.ResourceLoader;
|
||||||
|
import org.springframework.http.InvalidMediaTypeException;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
@@ -68,6 +75,10 @@ import static org.springframework.core.annotation.AnnotatedElementUtils.findMerg
|
|||||||
* @author Halvdan Hoem Grelland
|
* @author Halvdan Hoem Grelland
|
||||||
* @author Aram Peres
|
* @author Aram Peres
|
||||||
* @author Olga Maciaszek-Sharma
|
* @author Olga Maciaszek-Sharma
|
||||||
|
* @author Aaron Whiteside
|
||||||
|
* @author Artyom Romanenko
|
||||||
|
* @author Darren Foong
|
||||||
|
* @author Ram Anaswara
|
||||||
*/
|
*/
|
||||||
public class SpringMvcContract extends Contract.BaseContract
|
public class SpringMvcContract extends Contract.BaseContract
|
||||||
implements ResourceLoaderAware {
|
implements ResourceLoaderAware {
|
||||||
@@ -94,6 +105,8 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
|
|
||||||
private ResourceLoader resourceLoader = new DefaultResourceLoader();
|
private ResourceLoader resourceLoader = new DefaultResourceLoader();
|
||||||
|
|
||||||
|
private boolean decodeSlash;
|
||||||
|
|
||||||
public SpringMvcContract() {
|
public SpringMvcContract() {
|
||||||
this(Collections.emptyList());
|
this(Collections.emptyList());
|
||||||
}
|
}
|
||||||
@@ -106,20 +119,23 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
public SpringMvcContract(
|
public SpringMvcContract(
|
||||||
List<AnnotatedParameterProcessor> annotatedParameterProcessors,
|
List<AnnotatedParameterProcessor> annotatedParameterProcessors,
|
||||||
ConversionService conversionService) {
|
ConversionService conversionService) {
|
||||||
|
this(annotatedParameterProcessors, conversionService, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public SpringMvcContract(
|
||||||
|
List<AnnotatedParameterProcessor> annotatedParameterProcessors,
|
||||||
|
ConversionService conversionService, boolean decodeSlash) {
|
||||||
Assert.notNull(annotatedParameterProcessors,
|
Assert.notNull(annotatedParameterProcessors,
|
||||||
"Parameter processors can not be null.");
|
"Parameter processors can not be null.");
|
||||||
Assert.notNull(conversionService, "ConversionService can not be null.");
|
Assert.notNull(conversionService, "ConversionService can not be null.");
|
||||||
|
|
||||||
List<AnnotatedParameterProcessor> processors;
|
List<AnnotatedParameterProcessor> processors = getDefaultAnnotatedArgumentsProcessors();
|
||||||
if (!annotatedParameterProcessors.isEmpty()) {
|
processors.addAll(annotatedParameterProcessors);
|
||||||
processors = new ArrayList<>(annotatedParameterProcessors);
|
|
||||||
}
|
annotatedArgumentProcessors = toAnnotatedArgumentProcessorMap(processors);
|
||||||
else {
|
|
||||||
processors = getDefaultAnnotatedArgumentsProcessors();
|
|
||||||
}
|
|
||||||
this.annotatedArgumentProcessors = toAnnotatedArgumentProcessorMap(processors);
|
|
||||||
this.conversionService = conversionService;
|
this.conversionService = conversionService;
|
||||||
this.convertingExpanderFactory = new ConvertingExpanderFactory(conversionService);
|
convertingExpanderFactory = new ConvertingExpanderFactory(conversionService);
|
||||||
|
this.decodeSlash = decodeSlash;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static TypeDescriptor createTypeDescriptor(Method method, int paramIndex) {
|
private static TypeDescriptor createTypeDescriptor(Method method, int paramIndex) {
|
||||||
@@ -177,6 +193,9 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
pathValue = "/" + pathValue;
|
pathValue = "/" + pathValue;
|
||||||
}
|
}
|
||||||
data.template().uri(pathValue);
|
data.template().uri(pathValue);
|
||||||
|
if (data.template().decodeSlash() != decodeSlash) {
|
||||||
|
data.template().decodeSlash(decodeSlash);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -184,7 +203,7 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method method) {
|
public MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method method) {
|
||||||
this.processedMethods.put(Feign.configKey(targetType, method), method);
|
processedMethods.put(Feign.configKey(targetType, method), method);
|
||||||
MethodMetadata md = super.parseAndValidateMetadata(targetType, method);
|
MethodMetadata md = super.parseAndValidateMetadata(targetType, method);
|
||||||
|
|
||||||
RequestMapping classAnnotation = findMergedAnnotation(targetType,
|
RequestMapping classAnnotation = findMergedAnnotation(targetType,
|
||||||
@@ -210,6 +229,12 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
@Override
|
@Override
|
||||||
protected void processAnnotationOnMethod(MethodMetadata data,
|
protected void processAnnotationOnMethod(MethodMetadata data,
|
||||||
Annotation methodAnnotation, Method method) {
|
Annotation methodAnnotation, Method method) {
|
||||||
|
if (CollectionFormat.class.isInstance(methodAnnotation)) {
|
||||||
|
CollectionFormat collectionFormat = findMergedAnnotation(method,
|
||||||
|
CollectionFormat.class);
|
||||||
|
data.template().collectionFormat(collectionFormat.value());
|
||||||
|
}
|
||||||
|
|
||||||
if (!RequestMapping.class.isInstance(methodAnnotation) && !methodAnnotation
|
if (!RequestMapping.class.isInstance(methodAnnotation) && !methodAnnotation
|
||||||
.annotationType().isAnnotationPresent(RequestMapping.class)) {
|
.annotationType().isAnnotationPresent(RequestMapping.class)) {
|
||||||
return;
|
return;
|
||||||
@@ -235,6 +260,9 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
pathValue = "/" + pathValue;
|
pathValue = "/" + pathValue;
|
||||||
}
|
}
|
||||||
data.template().uri(pathValue, true);
|
data.template().uri(pathValue, true);
|
||||||
|
if (data.template().decodeSlash() != decodeSlash) {
|
||||||
|
data.template().decodeSlash(decodeSlash);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -247,13 +275,13 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
// headers
|
// headers
|
||||||
parseHeaders(data, method, methodMapping);
|
parseHeaders(data, method, methodMapping);
|
||||||
|
|
||||||
data.indexToExpander(new LinkedHashMap<Integer, Param.Expander>());
|
data.indexToExpander(new LinkedHashMap<>());
|
||||||
}
|
}
|
||||||
|
|
||||||
private String resolve(String value) {
|
private String resolve(String value) {
|
||||||
if (StringUtils.hasText(value)
|
if (StringUtils.hasText(value)
|
||||||
&& this.resourceLoader instanceof ConfigurableApplicationContext) {
|
&& resourceLoader instanceof ConfigurableApplicationContext) {
|
||||||
return ((ConfigurableApplicationContext) this.resourceLoader).getEnvironment()
|
return ((ConfigurableApplicationContext) resourceLoader).getEnvironment()
|
||||||
.resolvePlaceholders(value);
|
.resolvePlaceholders(value);
|
||||||
}
|
}
|
||||||
return value;
|
return value;
|
||||||
@@ -279,9 +307,9 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
|
|
||||||
AnnotatedParameterProcessor.AnnotatedParameterContext context = new SimpleAnnotatedParameterContext(
|
AnnotatedParameterProcessor.AnnotatedParameterContext context = new SimpleAnnotatedParameterContext(
|
||||||
data, paramIndex);
|
data, paramIndex);
|
||||||
Method method = this.processedMethods.get(data.configKey());
|
Method method = processedMethods.get(data.configKey());
|
||||||
for (Annotation parameterAnnotation : annotations) {
|
for (Annotation parameterAnnotation : annotations) {
|
||||||
AnnotatedParameterProcessor processor = this.annotatedArgumentProcessors
|
AnnotatedParameterProcessor processor = annotatedArgumentProcessors
|
||||||
.get(parameterAnnotation.annotationType());
|
.get(parameterAnnotation.annotationType());
|
||||||
if (processor != null) {
|
if (processor != null) {
|
||||||
Annotation processParameterAnnotation;
|
Annotation processParameterAnnotation;
|
||||||
@@ -294,11 +322,11 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isHttpAnnotation && data.indexToExpander().get(paramIndex) == null) {
|
if (!isMultipartFormData(data) && isHttpAnnotation
|
||||||
|
&& data.indexToExpander().get(paramIndex) == null) {
|
||||||
TypeDescriptor typeDescriptor = createTypeDescriptor(method, paramIndex);
|
TypeDescriptor typeDescriptor = createTypeDescriptor(method, paramIndex);
|
||||||
if (this.conversionService.canConvert(typeDescriptor,
|
if (conversionService.canConvert(typeDescriptor, STRING_TYPE_DESCRIPTOR)) {
|
||||||
STRING_TYPE_DESCRIPTOR)) {
|
Param.Expander expander = convertingExpanderFactory
|
||||||
Param.Expander expander = this.convertingExpanderFactory
|
|
||||||
.getExpander(typeDescriptor);
|
.getExpander(typeDescriptor);
|
||||||
if (expander != null) {
|
if (expander != null) {
|
||||||
data.indexToExpander().put(paramIndex, expander);
|
data.indexToExpander().put(paramIndex, expander);
|
||||||
@@ -355,10 +383,12 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
|
|
||||||
List<AnnotatedParameterProcessor> annotatedArgumentResolvers = new ArrayList<>();
|
List<AnnotatedParameterProcessor> annotatedArgumentResolvers = new ArrayList<>();
|
||||||
|
|
||||||
|
annotatedArgumentResolvers.add(new MatrixVariableParameterProcessor());
|
||||||
annotatedArgumentResolvers.add(new PathVariableParameterProcessor());
|
annotatedArgumentResolvers.add(new PathVariableParameterProcessor());
|
||||||
annotatedArgumentResolvers.add(new RequestParamParameterProcessor());
|
annotatedArgumentResolvers.add(new RequestParamParameterProcessor());
|
||||||
annotatedArgumentResolvers.add(new RequestHeaderParameterProcessor());
|
annotatedArgumentResolvers.add(new RequestHeaderParameterProcessor());
|
||||||
annotatedArgumentResolvers.add(new QueryMapParameterProcessor());
|
annotatedArgumentResolvers.add(new QueryMapParameterProcessor());
|
||||||
|
annotatedArgumentResolvers.add(new RequestPartParameterProcessor());
|
||||||
|
|
||||||
return annotatedArgumentResolvers;
|
return annotatedArgumentResolvers;
|
||||||
}
|
}
|
||||||
@@ -389,6 +419,24 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
&& parameterTypes != null && parameterTypes.length > parameterIndex;
|
&& parameterTypes != null && parameterTypes.length > parameterIndex;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean isMultipartFormData(MethodMetadata data) {
|
||||||
|
Collection<String> contentTypes = data.template().headers()
|
||||||
|
.get(HttpEncoding.CONTENT_TYPE);
|
||||||
|
|
||||||
|
if (contentTypes != null && !contentTypes.isEmpty()) {
|
||||||
|
String type = contentTypes.iterator().next();
|
||||||
|
try {
|
||||||
|
return Objects.equals(MediaType.valueOf(type),
|
||||||
|
MediaType.MULTIPART_FORM_DATA);
|
||||||
|
}
|
||||||
|
catch (InvalidMediaTypeException ignored) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @deprecated Not used internally anymore. Will be removed in the future.
|
* @deprecated Not used internally anymore. Will be removed in the future.
|
||||||
*/
|
*/
|
||||||
@@ -403,7 +451,7 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String expand(Object value) {
|
public String expand(Object value) {
|
||||||
return this.conversionService.convert(value, String.class);
|
return conversionService.convert(value, String.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -418,7 +466,7 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
|
|
||||||
Param.Expander getExpander(TypeDescriptor typeDescriptor) {
|
Param.Expander getExpander(TypeDescriptor typeDescriptor) {
|
||||||
return value -> {
|
return value -> {
|
||||||
Object converted = this.conversionService.convert(value, typeDescriptor,
|
Object converted = conversionService.convert(value, typeDescriptor,
|
||||||
STRING_TYPE_DESCRIPTOR);
|
STRING_TYPE_DESCRIPTOR);
|
||||||
return (String) converted;
|
return (String) converted;
|
||||||
};
|
};
|
||||||
@@ -441,17 +489,17 @@ public class SpringMvcContract extends Contract.BaseContract
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public MethodMetadata getMethodMetadata() {
|
public MethodMetadata getMethodMetadata() {
|
||||||
return this.methodMetadata;
|
return methodMetadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int getParameterIndex() {
|
public int getParameterIndex() {
|
||||||
return this.parameterIndex;
|
return parameterIndex;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setParameterName(String name) {
|
public void setParameterName(String name) {
|
||||||
nameParam(this.methodMetadata, name, this.parameterIndex);
|
nameParam(methodMetadata, name, parameterIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+18
@@ -8,6 +8,18 @@
|
|||||||
"description": "If true, an OpenFeign client will be wrapped with a Hystrix circuit breaker.",
|
"description": "If true, an OpenFeign client will be wrapped with a Hystrix circuit breaker.",
|
||||||
"defaultValue": "false"
|
"defaultValue": "false"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "feign.autoconfiguration.jackson.enabled",
|
||||||
|
"type": "java.lang.Boolean",
|
||||||
|
"description": "If true, PageJacksonModule and SortJacksonModule bean will be provided for Jackson page decoding.",
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "feign.circuitbreaker.enabled",
|
||||||
|
"type": "java.lang.Boolean",
|
||||||
|
"description": "If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker.",
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "feign.httpclient.enabled",
|
"name": "feign.httpclient.enabled",
|
||||||
"type": "java.lang.Boolean",
|
"type": "java.lang.Boolean",
|
||||||
@@ -26,6 +38,12 @@
|
|||||||
"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.response.useGzipDecoder",
|
||||||
|
"type": "java.lang.Boolean",
|
||||||
|
"description": "Enables the default gzip decoder to be used.",
|
||||||
|
"defaultValue": "false"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "feign.compression.request.enabled",
|
"name": "feign.compression.request.enabled",
|
||||||
"type": "java.lang.Boolean",
|
"type": "java.lang.Boolean",
|
||||||
|
|||||||
@@ -3,4 +3,5 @@ org.springframework.cloud.openfeign.ribbon.FeignRibbonClientAutoConfiguration,\
|
|||||||
org.springframework.cloud.openfeign.hateoas.FeignHalAutoConfiguration,\
|
org.springframework.cloud.openfeign.hateoas.FeignHalAutoConfiguration,\
|
||||||
org.springframework.cloud.openfeign.FeignAutoConfiguration,\
|
org.springframework.cloud.openfeign.FeignAutoConfiguration,\
|
||||||
org.springframework.cloud.openfeign.encoding.FeignAcceptGzipEncodingAutoConfiguration,\
|
org.springframework.cloud.openfeign.encoding.FeignAcceptGzipEncodingAutoConfiguration,\
|
||||||
org.springframework.cloud.openfeign.encoding.FeignContentGzipEncodingAutoConfiguration
|
org.springframework.cloud.openfeign.encoding.FeignContentGzipEncodingAutoConfiguration,\
|
||||||
|
org.springframework.cloud.openfeign.loadbalancer.FeignLoadBalancerAutoConfiguration
|
||||||
|
|||||||
+179
@@ -0,0 +1,179 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.cloud.openfeign.test.NoSecurityConfiguration;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.test.annotation.DirtiesContext;
|
||||||
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Jaesik Kim
|
||||||
|
*/
|
||||||
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
|
@SpringBootTest(classes = DefaultGzipDecoderTests.Application.class,
|
||||||
|
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||||
|
value = { "spring.application.name=defaultGzipDecoderTests",
|
||||||
|
"feign.compression.response.enabled=true",
|
||||||
|
"feign.compression.response.useGzipDecoder=true",
|
||||||
|
"feign.client.config.default.loggerLevel=full",
|
||||||
|
"logging.level.org.springframework.cloud.openfeign=DEBUG" })
|
||||||
|
@DirtiesContext
|
||||||
|
public class DefaultGzipDecoderTests extends FeignClientFactoryBean {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
FeignContext context;
|
||||||
|
|
||||||
|
@Value("${local.server.port}")
|
||||||
|
private int port = 0;
|
||||||
|
|
||||||
|
public DefaultGzipDecoderTests() {
|
||||||
|
setName("tests");
|
||||||
|
setContextId("test");
|
||||||
|
}
|
||||||
|
|
||||||
|
public TestClient testClient() {
|
||||||
|
setType(this.getClass());
|
||||||
|
return feign(context).target(TestClient.class, "http://localhost:" + this.port);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testBodyDecompress() {
|
||||||
|
ResponseEntity<Hello> response = testClient().getGzipResponse();
|
||||||
|
assertThat(response).as("response was null").isNotNull();
|
||||||
|
assertThat(response.getStatusCode()).as("wrong status code")
|
||||||
|
.isEqualTo(HttpStatus.OK);
|
||||||
|
Hello hello = response.getBody();
|
||||||
|
assertThat(hello).as("hello was null").isNotNull();
|
||||||
|
assertThat(hello).as("first hello didn't match")
|
||||||
|
.isEqualTo(new Hello("hello world via response"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testNullBodyDecompress() {
|
||||||
|
ResponseEntity<Hello> response = testClient().getNullResponse();
|
||||||
|
assertThat(response).as("response was null").isNotNull();
|
||||||
|
assertThat(response.getStatusCode()).as("wrong status code")
|
||||||
|
.isEqualTo(HttpStatus.OK);
|
||||||
|
Hello hello = response.getBody();
|
||||||
|
assertThat(hello).as("hello was not null").isNull();
|
||||||
|
assertThat(hello).as("null hello didn't match").isEqualTo(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCharsetDecompress() {
|
||||||
|
ResponseEntity<Hello> response = testClient().getUtf8Response();
|
||||||
|
assertThat(response).as("response was null").isNotNull();
|
||||||
|
assertThat(response.getStatusCode()).as("wrong status code")
|
||||||
|
.isEqualTo(HttpStatus.OK);
|
||||||
|
Hello hello = response.getBody();
|
||||||
|
assertThat(hello).as("hello was null").isNotNull();
|
||||||
|
assertThat(hello).as("utf8 hello didn't match")
|
||||||
|
.isEqualTo(new Hello("안녕하세요 means Hello in Korean"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class Hello {
|
||||||
|
|
||||||
|
private String message;
|
||||||
|
|
||||||
|
Hello() {
|
||||||
|
}
|
||||||
|
|
||||||
|
Hello(String message) {
|
||||||
|
this.message = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMessage() {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMessage(String message) {
|
||||||
|
this.message = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (o == null || getClass() != o.getClass()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Hello that = (Hello) o;
|
||||||
|
return Objects.equals(message, that.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
protected interface TestClient {
|
||||||
|
|
||||||
|
@GetMapping("/helloGzipResponse")
|
||||||
|
ResponseEntity<Hello> getGzipResponse();
|
||||||
|
|
||||||
|
@GetMapping("/nullGzipResponse")
|
||||||
|
ResponseEntity<Hello> getNullResponse();
|
||||||
|
|
||||||
|
@GetMapping("/utf8Response")
|
||||||
|
ResponseEntity<Hello> getUtf8Response();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@EnableAutoConfiguration
|
||||||
|
@RestController
|
||||||
|
@Import(NoSecurityConfiguration.class)
|
||||||
|
protected static class Application implements TestClient {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ResponseEntity<Hello> getGzipResponse() {
|
||||||
|
return ResponseEntity.ok(new Hello("hello world via response"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ResponseEntity<Hello> getNullResponse() {
|
||||||
|
return ResponseEntity.ok(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ResponseEntity<Hello> getUtf8Response() {
|
||||||
|
return ResponseEntity.ok(new Hello("안녕하세요 means Hello in Korean"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2015 the original author or authors.
|
* Copyright 2013-2020 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -48,7 +48,7 @@ public class EnableFeignClientsSpringDataTests {
|
|||||||
.cast(this.feignContext.getInstance("foo", Encoder.class));
|
.cast(this.feignContext.getInstance("foo", Encoder.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
@Import({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class,
|
@Import({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class,
|
||||||
FeignAutoConfiguration.class })
|
FeignAutoConfiguration.class })
|
||||||
protected static class PlainConfiguration {
|
protected static class PlainConfiguration {
|
||||||
|
|||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2015 the original author or authors.
|
* Copyright 2013-2020 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.
|
||||||
@@ -87,7 +87,7 @@ public class EnableFeignClientsTests {
|
|||||||
Feign.Builder.class.cast(this.context.getBeansOfType(Feign.Builder.class).get(0));
|
Feign.Builder.class.cast(this.context.getBeansOfType(Feign.Builder.class).get(0));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
@Import({ ArchaiusAutoConfiguration.class, FeignAutoConfiguration.class })
|
@Import({ ArchaiusAutoConfiguration.class, FeignAutoConfiguration.class })
|
||||||
protected static class PlainConfiguration {
|
protected static class PlainConfiguration {
|
||||||
|
|
||||||
|
|||||||
+160
@@ -0,0 +1,160 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2019 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
|
||||||
|
import feign.Feign;
|
||||||
|
import feign.Logger;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
|
import org.springframework.util.ReflectionUtils;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Matt King
|
||||||
|
*/
|
||||||
|
public class FeignBuilderCustomizerTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testBuilderCustomizer() {
|
||||||
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||||
|
FeignBuilderCustomizerTests.SampleConfiguration2.class);
|
||||||
|
|
||||||
|
FeignClientFactoryBean clientFactoryBean = context
|
||||||
|
.getBean(FeignClientFactoryBean.class);
|
||||||
|
FeignContext feignContext = context.getBean(FeignContext.class);
|
||||||
|
|
||||||
|
Feign.Builder builder = clientFactoryBean.feign(feignContext);
|
||||||
|
assertFeignBuilderField(builder, "logLevel", Logger.Level.HEADERS);
|
||||||
|
assertFeignBuilderField(builder, "decode404", true);
|
||||||
|
|
||||||
|
context.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertFeignBuilderField(Feign.Builder builder, String fieldName,
|
||||||
|
Object expectedValue) {
|
||||||
|
Field builderField = ReflectionUtils.findField(Feign.Builder.class, fieldName);
|
||||||
|
ReflectionUtils.makeAccessible(builderField);
|
||||||
|
|
||||||
|
Object value = ReflectionUtils.getField(builderField, builder);
|
||||||
|
assertThat(value).as("Expected value for the field '" + fieldName + "':")
|
||||||
|
.isEqualTo(expectedValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testBuildCustomizerOrdered() {
|
||||||
|
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||||
|
FeignBuilderCustomizerTests.SampleConfiguration3.class);
|
||||||
|
|
||||||
|
FeignClientFactoryBean clientFactoryBean = context
|
||||||
|
.getBean(FeignClientFactoryBean.class);
|
||||||
|
FeignContext feignContext = context.getBean(FeignContext.class);
|
||||||
|
|
||||||
|
Feign.Builder builder = clientFactoryBean.feign(feignContext);
|
||||||
|
assertFeignBuilderField(builder, "logLevel", Logger.Level.FULL);
|
||||||
|
assertFeignBuilderField(builder, "decode404", true);
|
||||||
|
|
||||||
|
context.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static FeignClientFactoryBean defaultFeignClientFactoryBean() {
|
||||||
|
FeignClientFactoryBean feignClientFactoryBean = new FeignClientFactoryBean();
|
||||||
|
feignClientFactoryBean.setContextId("test");
|
||||||
|
feignClientFactoryBean.setName("test");
|
||||||
|
feignClientFactoryBean.setType(FeignClientFactoryTests.TestType.class);
|
||||||
|
feignClientFactoryBean.setPath("");
|
||||||
|
feignClientFactoryBean.setUrl("http://some.absolute.url");
|
||||||
|
return feignClientFactoryBean;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@Import(FeignClientsConfiguration.class)
|
||||||
|
protected static class SampleConfiguration2 {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignContext feignContext() {
|
||||||
|
return new FeignContext();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignClientProperties feignClientProperties() {
|
||||||
|
return new FeignClientProperties();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignBuilderCustomizer feignBuilderCustomizer() {
|
||||||
|
return builder -> builder.logLevel(Logger.Level.HEADERS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignBuilderCustomizer feignBuilderCustomizer2() {
|
||||||
|
return Feign.Builder::decode404;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignClientFactoryBean feignClientFactoryBean() {
|
||||||
|
return defaultFeignClientFactoryBean();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@Import(FeignClientsConfiguration.class)
|
||||||
|
protected static class SampleConfiguration3 {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignContext feignContext() {
|
||||||
|
return new FeignContext();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignClientProperties feignClientProperties() {
|
||||||
|
return new FeignClientProperties();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Order(1)
|
||||||
|
FeignBuilderCustomizer feignBuilderCustomizer() {
|
||||||
|
return builder -> builder.logLevel(Logger.Level.HEADERS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@Order(2)
|
||||||
|
FeignBuilderCustomizer feignBuilderCustomizer1() {
|
||||||
|
return builder -> builder.logLevel(Logger.Level.FULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignBuilderCustomizer feignBuilderCustomizer2() {
|
||||||
|
return Feign.Builder::decode404;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignClientFactoryBean feignClientFactoryBean() {
|
||||||
|
return defaultFeignClientFactoryBean();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+6
-4
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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.
|
||||||
@@ -109,6 +109,7 @@ public class FeignClientBuilderTests {
|
|||||||
assertFactoryBeanField(builder, "type", TestFeignClient.class);
|
assertFactoryBeanField(builder, "type", TestFeignClient.class);
|
||||||
assertFactoryBeanField(builder, "name", "TestClient");
|
assertFactoryBeanField(builder, "name", "TestClient");
|
||||||
assertFactoryBeanField(builder, "contextId", "TestClient");
|
assertFactoryBeanField(builder, "contextId", "TestClient");
|
||||||
|
assertFactoryBeanField(builder, "inheritParentContext", true);
|
||||||
|
|
||||||
// and:
|
// and:
|
||||||
assertFactoryBeanField(builder, "url",
|
assertFactoryBeanField(builder, "url",
|
||||||
@@ -127,10 +128,10 @@ public class FeignClientBuilderTests {
|
|||||||
public void forType_allFieldsSetOnBuilder() {
|
public void forType_allFieldsSetOnBuilder() {
|
||||||
// when:
|
// when:
|
||||||
final FeignClientBuilder.Builder builder = this.feignClientBuilder
|
final FeignClientBuilder.Builder builder = this.feignClientBuilder
|
||||||
.forType(TestFeignClient.class, "TestClient").decode404(true)
|
.forType(TestFeignClient.class, "TestClient").inheritParentContext(false)
|
||||||
.fallback(TestFeignClientFallback.class)
|
.fallback(TestFeignClientFallback.class)
|
||||||
.fallbackFactory(TestFeignClientFallbackFactory.class).path("Path/")
|
.fallbackFactory(TestFeignClientFallbackFactory.class).decode404(true)
|
||||||
.url("Url/").contextId("TestContext");
|
.url("Url/").path("/Path").contextId("TestContext");
|
||||||
|
|
||||||
// then:
|
// then:
|
||||||
assertFactoryBeanField(builder, "applicationContext", this.applicationContext);
|
assertFactoryBeanField(builder, "applicationContext", this.applicationContext);
|
||||||
@@ -142,6 +143,7 @@ public class FeignClientBuilderTests {
|
|||||||
assertFactoryBeanField(builder, "url", "http://Url/");
|
assertFactoryBeanField(builder, "url", "http://Url/");
|
||||||
assertFactoryBeanField(builder, "path", "/Path");
|
assertFactoryBeanField(builder, "path", "/Path");
|
||||||
assertFactoryBeanField(builder, "decode404", true);
|
assertFactoryBeanField(builder, "decode404", true);
|
||||||
|
assertFactoryBeanField(builder, "inheritParentContext", false);
|
||||||
assertFactoryBeanField(builder, "fallback", TestFeignClientFallback.class);
|
assertFactoryBeanField(builder, "fallback", TestFeignClientFallback.class);
|
||||||
assertFactoryBeanField(builder, "fallbackFactory",
|
assertFactoryBeanField(builder, "fallbackFactory",
|
||||||
TestFeignClientFallbackFactory.class);
|
TestFeignClientFallbackFactory.class);
|
||||||
|
|||||||
+172
@@ -0,0 +1,172 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2020-2020 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import feign.Contract;
|
||||||
|
import feign.InvocationHandlerFactory;
|
||||||
|
import feign.RequestLine;
|
||||||
|
import feign.Response;
|
||||||
|
import feign.codec.ErrorDecoder;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.cloud.openfeign.support.SpringMvcContract;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.test.annotation.DirtiesContext;
|
||||||
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
|
import org.springframework.test.util.ReflectionTestUtils;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMethod;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author Michael Cramer
|
||||||
|
*/
|
||||||
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
|
@SpringBootTest(classes = FeignClientErrorDecoderTests.TestConfiguration.class)
|
||||||
|
@DirtiesContext
|
||||||
|
public class FeignClientErrorDecoderTests {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private FeignContext context;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private FooClient foo;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private BarClient bar;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void clientsAvailable() {
|
||||||
|
assertThat(this.foo).isNotNull();
|
||||||
|
assertThat(this.bar).isNotNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void errorDecoderInConfiguration() {
|
||||||
|
assertThat(this.context.getInstance("foo", ErrorDecoder.class))
|
||||||
|
.isInstanceOf(ErrorDecoder.Default.class);
|
||||||
|
assertThat(this.context.getInstance("bar", ErrorDecoder.class)).isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void useConfiguredErrorDecoderWhenAlsoErrorDecoderFactoryIsAvailable() {
|
||||||
|
Object errorDecoder = getErrorDecoderFromClient(this.foo);
|
||||||
|
assertThat(errorDecoder).isInstanceOf(ErrorDecoder.Default.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void useErrorDecoderFromErrorDecoderFactory() {
|
||||||
|
Object errorDecoder = getErrorDecoderFromClient(this.bar);
|
||||||
|
assertThat(errorDecoder).isInstanceOf(ErrorDecoderImpl.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings({ "unchecked", "ConstantConditions" })
|
||||||
|
private Object getErrorDecoderFromClient(final Object client) {
|
||||||
|
Object invocationHandler = ReflectionTestUtils.getField(client, "h");
|
||||||
|
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch = (Map<Method, InvocationHandlerFactory.MethodHandler>) ReflectionTestUtils
|
||||||
|
.getField(invocationHandler, "dispatch");
|
||||||
|
Method key = new ArrayList<>(dispatch.keySet()).get(0);
|
||||||
|
return ReflectionTestUtils.getField(
|
||||||
|
ReflectionTestUtils.getField(dispatch.get(key), "asyncResponseHandler"),
|
||||||
|
"errorDecoder");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@EnableFeignClients(clients = { FooClient.class, BarClient.class })
|
||||||
|
@EnableAutoConfiguration
|
||||||
|
protected static class TestConfiguration {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@FeignClient(name = "foo", url = "http://foo", configuration = FooConfiguration.class)
|
||||||
|
interface FooClient {
|
||||||
|
|
||||||
|
@RequestLine("GET /")
|
||||||
|
String get();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class FooConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
Contract feignContract() {
|
||||||
|
return new Contract.Default();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignErrorDecoderFactory errorDecoderFactory() {
|
||||||
|
return new FeignErrorDecoderFactoryImpl();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
ErrorDecoder feignErrorDecoder() {
|
||||||
|
return new ErrorDecoder.Default();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@FeignClient(name = "bar", url = "http://bar", configuration = BarConfiguration.class)
|
||||||
|
interface BarClient {
|
||||||
|
|
||||||
|
@RequestMapping(value = "/", method = RequestMethod.GET)
|
||||||
|
String get();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class BarConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
Contract feignContract() {
|
||||||
|
return new SpringMvcContract();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignErrorDecoderFactory errorDecoderFactory() {
|
||||||
|
return new FeignErrorDecoderFactoryImpl();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class FeignErrorDecoderFactoryImpl implements FeignErrorDecoderFactory {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ErrorDecoder create(final Class<?> type) {
|
||||||
|
return new ErrorDecoderImpl();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class ErrorDecoderImpl implements ErrorDecoder {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Exception decode(final String methodKey, final Response response) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+81
-1
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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,14 +16,30 @@
|
|||||||
|
|
||||||
package org.springframework.cloud.openfeign;
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.lang.reflect.Proxy;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import feign.Client;
|
||||||
|
import feign.InvocationHandlerFactory;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
|
||||||
|
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||||
|
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
|
||||||
|
import org.springframework.cloud.loadbalancer.config.LoadBalancerAutoConfiguration;
|
||||||
|
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
|
||||||
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.test.util.ReflectionTestUtils;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.springframework.web.bind.annotation.RequestMethod.GET;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author Spencer Gibb
|
* @author Spencer Gibb
|
||||||
@@ -49,10 +65,74 @@ public class FeignClientFactoryTests {
|
|||||||
assertThat(foobar).as("bar was not null").isNull();
|
assertThat(foobar).as("bar was not null").isNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldRedirectToDelegateWhenUrlSet() {
|
||||||
|
new ApplicationContextRunner().withUserConfiguration(TestConfig.class)
|
||||||
|
.run(this::defaultClientUsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings({ "unchecked", "ConstantConditions" })
|
||||||
|
private void defaultClientUsed(AssertableApplicationContext context) {
|
||||||
|
Proxy target = context.getBean(FeignClientFactoryBean.class).getTarget();
|
||||||
|
Object invocationHandler = ReflectionTestUtils.getField(target, "h");
|
||||||
|
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch = (Map<Method, InvocationHandlerFactory.MethodHandler>) ReflectionTestUtils
|
||||||
|
.getField(invocationHandler, "dispatch");
|
||||||
|
Method key = new ArrayList<>(dispatch.keySet()).get(0);
|
||||||
|
Object client = ReflectionTestUtils.getField(dispatch.get(key), "client");
|
||||||
|
assertThat(client).isInstanceOf(Client.Default.class);
|
||||||
|
}
|
||||||
|
|
||||||
private FeignClientSpecification getSpec(String name, Class<?> configClass) {
|
private FeignClientSpecification getSpec(String name, Class<?> configClass) {
|
||||||
return new FeignClientSpecification(name, new Class[] { configClass });
|
return new FeignClientSpecification(name, new Class[] { configClass });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface TestType {
|
||||||
|
|
||||||
|
@RequestMapping(value = "/", method = GET)
|
||||||
|
String hello();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
static class TestConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
BlockingLoadBalancerClient loadBalancerClient() {
|
||||||
|
return new BlockingLoadBalancerClient(new LoadBalancerClientFactory());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignContext feignContext() {
|
||||||
|
FeignContext feignContext = new FeignContext();
|
||||||
|
feignContext.setConfigurations(
|
||||||
|
Collections.singletonList(new FeignClientSpecification("test",
|
||||||
|
new Class[] { LoadBalancerAutoConfiguration.class })));
|
||||||
|
return feignContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignClientProperties feignClientProperties() {
|
||||||
|
return new FeignClientProperties();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
Targeter targeter() {
|
||||||
|
return new DefaultTargeter();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FeignClientFactoryBean feignClientFactoryBean() {
|
||||||
|
FeignClientFactoryBean feignClientFactoryBean = new FeignClientFactoryBean();
|
||||||
|
feignClientFactoryBean.setContextId("test");
|
||||||
|
feignClientFactoryBean.setName("test");
|
||||||
|
feignClientFactoryBean.setType(TestType.class);
|
||||||
|
feignClientFactoryBean.setPath("");
|
||||||
|
feignClientFactoryBean.setUrl("http://some.absolute.url");
|
||||||
|
return feignClientFactoryBean;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
static class FooConfig {
|
static class FooConfig {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
|||||||
+55
-51
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2013-2019 the original author or authors.
|
* Copyright 2013-2020 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,13 +17,13 @@
|
|||||||
package org.springframework.cloud.openfeign;
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
import feign.Contract;
|
import feign.Contract;
|
||||||
|
import feign.ExceptionPropagationPolicy;
|
||||||
import feign.Feign;
|
import feign.Feign;
|
||||||
import feign.Logger;
|
import feign.Logger;
|
||||||
import feign.QueryMapEncoder;
|
import feign.QueryMapEncoder;
|
||||||
import feign.Request;
|
import feign.Request;
|
||||||
import feign.RequestInterceptor;
|
import feign.RequestInterceptor;
|
||||||
import feign.RequestLine;
|
import feign.RequestLine;
|
||||||
import feign.RequestTemplate;
|
|
||||||
import feign.Retryer;
|
import feign.Retryer;
|
||||||
import feign.auth.BasicAuthRequestInterceptor;
|
import feign.auth.BasicAuthRequestInterceptor;
|
||||||
import feign.codec.Decoder;
|
import feign.codec.Decoder;
|
||||||
@@ -33,8 +33,7 @@ import feign.hystrix.HystrixFeign;
|
|||||||
import feign.optionals.OptionalDecoder;
|
import feign.optionals.OptionalDecoder;
|
||||||
import feign.querymap.BeanQueryMapEncoder;
|
import feign.querymap.BeanQueryMapEncoder;
|
||||||
import feign.slf4j.Slf4jLogger;
|
import feign.slf4j.Slf4jLogger;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
|
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
|
||||||
@@ -46,7 +45,6 @@ import org.springframework.context.annotation.Bean;
|
|||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.context.annotation.Import;
|
import org.springframework.context.annotation.Import;
|
||||||
import org.springframework.test.annotation.DirtiesContext;
|
import org.springframework.test.annotation.DirtiesContext;
|
||||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestMethod;
|
import org.springframework.web.bind.annotation.RequestMethod;
|
||||||
|
|
||||||
@@ -55,10 +53,9 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||||||
/**
|
/**
|
||||||
* @author Spencer Gibb
|
* @author Spencer Gibb
|
||||||
*/
|
*/
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
|
||||||
@SpringBootTest(classes = FeignClientOverrideDefaultsTests.TestConfiguration.class)
|
@SpringBootTest(classes = FeignClientOverrideDefaultsTests.TestConfiguration.class)
|
||||||
@DirtiesContext
|
@DirtiesContext
|
||||||
public class FeignClientOverrideDefaultsTests {
|
class FeignClientOverrideDefaultsTests {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private FeignContext context;
|
private FeignContext context;
|
||||||
@@ -70,87 +67,92 @@ public class FeignClientOverrideDefaultsTests {
|
|||||||
private BarClient bar;
|
private BarClient bar;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void clientsAvailable() {
|
void clientsAvailable() {
|
||||||
assertThat(this.foo).isNotNull();
|
assertThat(foo).isNotNull();
|
||||||
assertThat(this.bar).isNotNull();
|
assertThat(bar).isNotNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void overrideDecoder() {
|
void overrideDecoder() {
|
||||||
Decoder.Default.class.cast(this.context.getInstance("foo", Decoder.class));
|
Decoder.Default.class.cast(context.getInstance("foo", Decoder.class));
|
||||||
OptionalDecoder.class.cast(this.context.getInstance("bar", Decoder.class));
|
OptionalDecoder.class.cast(context.getInstance("bar", Decoder.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void overrideEncoder() {
|
void overrideEncoder() {
|
||||||
Encoder.Default.class.cast(this.context.getInstance("foo", Encoder.class));
|
Encoder.Default.class.cast(context.getInstance("foo", Encoder.class));
|
||||||
PageableSpringEncoder.class.cast(this.context.getInstance("bar", Encoder.class));
|
PageableSpringEncoder.class.cast(context.getInstance("bar", Encoder.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void overrideLogger() {
|
void overrideLogger() {
|
||||||
Logger.JavaLogger.class.cast(this.context.getInstance("foo", Logger.class));
|
Logger.JavaLogger.class.cast(context.getInstance("foo", Logger.class));
|
||||||
Slf4jLogger.class.cast(this.context.getInstance("bar", Logger.class));
|
Slf4jLogger.class.cast(context.getInstance("bar", Logger.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void overrideContract() {
|
void overrideContract() {
|
||||||
Contract.Default.class.cast(this.context.getInstance("foo", Contract.class));
|
Contract.Default.class.cast(context.getInstance("foo", Contract.class));
|
||||||
SpringMvcContract.class.cast(this.context.getInstance("bar", Contract.class));
|
SpringMvcContract.class.cast(context.getInstance("bar", Contract.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void overrideLoggerLevel() {
|
void overrideLoggerLevel() {
|
||||||
assertThat(this.context.getInstance("foo", Logger.Level.class)).isNull();
|
assertThat(context.getInstance("foo", Logger.Level.class)).isNull();
|
||||||
assertThat(this.context.getInstance("bar", Logger.Level.class))
|
assertThat(context.getInstance("bar", Logger.Level.class))
|
||||||
.isEqualTo(Logger.Level.HEADERS);
|
.isEqualTo(Logger.Level.HEADERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void overrideRetryer() {
|
void overrideRetryer() {
|
||||||
assertThat(this.context.getInstance("foo", Retryer.class))
|
assertThat(context.getInstance("foo", Retryer.class))
|
||||||
.isEqualTo(Retryer.NEVER_RETRY);
|
.isEqualTo(Retryer.NEVER_RETRY);
|
||||||
Retryer.Default.class.cast(this.context.getInstance("bar", Retryer.class));
|
Retryer.Default.class.cast(context.getInstance("bar", Retryer.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void overrideErrorDecoder() {
|
void overrideErrorDecoder() {
|
||||||
assertThat(this.context.getInstance("foo", ErrorDecoder.class)).isNull();
|
assertThat(context.getInstance("foo", ErrorDecoder.class)).isNull();
|
||||||
ErrorDecoder.Default.class
|
ErrorDecoder.Default.class.cast(context.getInstance("bar", ErrorDecoder.class));
|
||||||
.cast(this.context.getInstance("bar", ErrorDecoder.class));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void overrideBuilder() {
|
void overrideBuilder() {
|
||||||
HystrixFeign.Builder.class
|
HystrixFeign.Builder.class.cast(context.getInstance("foo", Feign.Builder.class));
|
||||||
.cast(this.context.getInstance("foo", Feign.Builder.class));
|
Feign.Builder.class.cast(context.getInstance("bar", Feign.Builder.class));
|
||||||
Feign.Builder.class.cast(this.context.getInstance("bar", Feign.Builder.class));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void overrideRequestOptions() {
|
void overrideRequestOptions() {
|
||||||
assertThat(this.context.getInstance("foo", Request.Options.class)).isNull();
|
assertThat(context.getInstance("foo", Request.Options.class)).isNull();
|
||||||
Request.Options options = this.context.getInstance("bar", Request.Options.class);
|
Request.Options options = context.getInstance("bar", Request.Options.class);
|
||||||
assertThat(options.connectTimeoutMillis()).isEqualTo(1);
|
assertThat(options.connectTimeoutMillis()).isEqualTo(1);
|
||||||
assertThat(options.readTimeoutMillis()).isEqualTo(1);
|
assertThat(options.readTimeoutMillis()).isEqualTo(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void overrideQueryMapEncoder() {
|
void overrideQueryMapEncoder() {
|
||||||
QueryMapEncoder.Default.class
|
QueryMapEncoder.Default.class
|
||||||
.cast(this.context.getInstance("foo", QueryMapEncoder.class));
|
.cast(context.getInstance("foo", QueryMapEncoder.class));
|
||||||
BeanQueryMapEncoder.class
|
BeanQueryMapEncoder.class.cast(context.getInstance("bar", QueryMapEncoder.class));
|
||||||
.cast(this.context.getInstance("bar", QueryMapEncoder.class));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void addRequestInterceptor() {
|
void addRequestInterceptor() {
|
||||||
assertThat(this.context.getInstances("foo", RequestInterceptor.class).size())
|
assertThat(context.getInstances("foo", RequestInterceptor.class).size())
|
||||||
.isEqualTo(1);
|
.isEqualTo(1);
|
||||||
assertThat(this.context.getInstances("bar", RequestInterceptor.class).size())
|
assertThat(context.getInstances("bar", RequestInterceptor.class).size())
|
||||||
.isEqualTo(2);
|
.isEqualTo(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void exceptionPropagationPolicy() {
|
||||||
|
assertThat(context.getInstances("foo", ExceptionPropagationPolicy.class))
|
||||||
|
.isEmpty();
|
||||||
|
assertThat(context.getInstances("bar", ExceptionPropagationPolicy.class))
|
||||||
|
.containsValues(ExceptionPropagationPolicy.UNWRAP);
|
||||||
|
}
|
||||||
|
|
||||||
@FeignClient(name = "foo", url = "https://foo",
|
@FeignClient(name = "foo", url = "https://foo",
|
||||||
configuration = FooConfiguration.class)
|
configuration = FooConfiguration.class)
|
||||||
interface FooClient {
|
interface FooClient {
|
||||||
@@ -169,7 +171,7 @@ public class FeignClientOverrideDefaultsTests {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Configuration
|
@Configuration(proxyBeanMethods = false)
|
||||||
@EnableFeignClients(clients = { FooClient.class, BarClient.class })
|
@EnableFeignClients(clients = { FooClient.class, BarClient.class })
|
||||||
@Import({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class,
|
@Import({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class,
|
||||||
FeignAutoConfiguration.class })
|
FeignAutoConfiguration.class })
|
||||||
@@ -177,10 +179,7 @@ public class FeignClientOverrideDefaultsTests {
|
|||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
RequestInterceptor defaultRequestInterceptor() {
|
RequestInterceptor defaultRequestInterceptor() {
|
||||||
return new RequestInterceptor() {
|
return template -> {
|
||||||
@Override
|
|
||||||
public void apply(RequestTemplate template) {
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,6 +251,11 @@ public class FeignClientOverrideDefaultsTests {
|
|||||||
return new BeanQueryMapEncoder();
|
return new BeanQueryMapEncoder();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public ExceptionPropagationPolicy exceptionPropagationPolicy() {
|
||||||
|
return ExceptionPropagationPolicy.UNWRAP;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+152
@@ -0,0 +1,152 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2019 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.springframework.cloud.openfeign;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import feign.Feign;
|
||||||
|
import feign.Logger;
|
||||||
|
import feign.RequestInterceptor;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||||
|
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.test.annotation.DirtiesContext;
|
||||||
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
|
import org.springframework.util.ReflectionUtils;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author matt king
|
||||||
|
*/
|
||||||
|
@DirtiesContext
|
||||||
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
|
@SpringBootTest(classes = FeignClientUsingConfigurerTest.Application.class, value = {
|
||||||
|
"feign.client.config.default.loggerLevel=full",
|
||||||
|
"feign.client.config.default.requestInterceptors[0]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.FooRequestInterceptor",
|
||||||
|
"feign.client.config.default.requestInterceptors[1]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.BarRequestInterceptor" })
|
||||||
|
public class FeignClientUsingConfigurerTest {
|
||||||
|
|
||||||
|
private static final String BEAN_NAME_PREFIX = "org.springframework.cloud.openfeign.FeignClientUsingConfigurerTest$";
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ConfigurableListableBeanFactory beanFactory;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private FeignContext context;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testFeignClient() {
|
||||||
|
FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) beanFactory
|
||||||
|
.getBeanDefinition(BEAN_NAME_PREFIX + "TestFeignClient")
|
||||||
|
.getAttribute("feignClientsRegistrarFactoryBean");
|
||||||
|
Feign.Builder builder = factoryBean.feign(context);
|
||||||
|
|
||||||
|
List<RequestInterceptor> interceptors = (List) getBuilderValue(builder,
|
||||||
|
"requestInterceptors");
|
||||||
|
assertThat(interceptors.size()).as("interceptors not set").isEqualTo(3);
|
||||||
|
assertThat(getBuilderValue(builder, "logLevel")).as("log level not set")
|
||||||
|
.isEqualTo(Logger.Level.FULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object getBuilderValue(Feign.Builder builder, String member) {
|
||||||
|
Field builderField = ReflectionUtils.findField(Feign.Builder.class, member);
|
||||||
|
ReflectionUtils.makeAccessible(builderField);
|
||||||
|
|
||||||
|
return ReflectionUtils.getField(builderField, builder);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testNoInheritFeignClient() {
|
||||||
|
FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) beanFactory
|
||||||
|
.getBeanDefinition(BEAN_NAME_PREFIX + "NoInheritFeignClient")
|
||||||
|
.getAttribute("feignClientsRegistrarFactoryBean");
|
||||||
|
Feign.Builder builder = factoryBean.feign(context);
|
||||||
|
|
||||||
|
List<RequestInterceptor> interceptors = (List) getBuilderValue(builder,
|
||||||
|
"requestInterceptors");
|
||||||
|
|
||||||
|
assertThat(interceptors).as("interceptors not set").isEmpty();
|
||||||
|
assertThat(factoryBean.isInheritParentContext())
|
||||||
|
.as("is inheriting from parent configuration").isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testNoInheritFeignClient_ignoreProperties() {
|
||||||
|
FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) beanFactory
|
||||||
|
.getBeanDefinition(BEAN_NAME_PREFIX + "NoInheritFeignClient")
|
||||||
|
.getAttribute("feignClientsRegistrarFactoryBean");
|
||||||
|
Feign.Builder builder = factoryBean.feign(context);
|
||||||
|
|
||||||
|
assertThat(getBuilderValue(builder, "logLevel")).as("log level not set")
|
||||||
|
.isEqualTo(Logger.Level.HEADERS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@EnableAutoConfiguration
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@EnableFeignClients(clients = { TestFeignClient.class, NoInheritFeignClient.class })
|
||||||
|
protected static class Application {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public RequestInterceptor requestInterceptor() {
|
||||||
|
return requestTemplate -> {
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class NoInheritConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public Logger.Level logLevel() {
|
||||||
|
return Logger.Level.HEADERS;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public FeignClientConfigurer feignClientConfigurer() {
|
||||||
|
return new FeignClientConfigurer() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean inheritParentConfiguration() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@FeignClient("testFeignClient")
|
||||||
|
interface TestFeignClient {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@FeignClient(name = "noInheritFeignClient",
|
||||||
|
configuration = NoInheritConfiguration.class)
|
||||||
|
interface NoInheritFeignClient {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user