Compare commits

..
46 Commits
Author SHA1 Message Date
buildmaster 93fcf38c24 Update SNAPSHOT to 3.0.3 2021-05-27 21:18:46 +00:00
buildmaster be929043c3 Bumping versions to 3.0.4-SNAPSHOT after release 2021-05-27 08:11:04 +00:00
buildmaster c7316b008a Going back to snapshots 2021-05-27 08:11:04 +00:00
buildmaster 989616ebe6 Update SNAPSHOT to 3.0.3 2021-05-27 08:08:49 +00:00
Olga MaciaszekSharma 58b0c7866c Merge remote-tracking branch 'origin/2.2.x' into main 2021-05-24 16:02:34 +02:00
Nick Smith 421df91a80 Filters out null matrix parameters 2021-05-24 15:58:27 +02:00
Olga MaciaszekSharma 5aa1b7a529 Merge remote-tracking branch 'origin/2.2.x' into main 2021-05-12 13:56:49 +02:00
Olga MaciaszekSharma ec1f2ad5bb Refactor FeignHalConfiguration to use HalMediaTypeConfiguration under the hood. Fixes gh-541. 2021-05-12 13:51:43 +02:00
Olga MaciaszekSharma fbcebb372c Switch to a different HalInstantiator constructor for Boot 2.5 compatibility. Fixes gh-536. 2021-04-27 16:22:03 +02:00
Olga MaciaszekSharma 1a00bbf705 Merge 2.2.x 2021-04-26 19:28:17 +02:00
Olga MaciaszekSharma 5baa8c8ed5 Remove master references. 2021-04-26 19:24:36 +02:00
Olga MaciaszekSharma d0e035b8ff Switch from master to main. 2021-04-26 17:48:29 +02:00
Olga MaciaszekSharma 1615a5a68c Switch GH actions to main. 2021-04-26 17:36:44 +02:00
Olga MaciaszekSharma 0c1ab36fe1 Merge remote-tracking branch 'origin/2.2.x' 2021-04-22 18:14:37 +02:00
buildmaster 0684ee4bc2 Bumping versions to 2.2.9.BUILD-SNAPSHOT after release 2021-04-21 17:11:52 +00:00
buildmaster 0b34d89adc Going back to snapshots 2021-04-21 17:11:52 +00:00
buildmaster c33bc490cd Update SNAPSHOT to 2.2.8.RELEASE 2021-04-21 17:10:24 +00:00
Olga MaciaszekSharma d738b3b224 Upgrade Feign to 10.12. Fixes gh-530. 2021-04-21 10:23:38 +02:00
buildmaster 0c1d281970 Bumping versions 2021-04-20 21:33:18 +00:00
Olga MaciaszekSharma 26fb4deb18 Merge remote-tracking branch 'origin/2.2.x' 2021-04-20 17:28:31 +02:00
Olga MaciaszekSharma 0bf0426f60 Update GH actions setup. 2021-04-20 16:50:36 +02:00
Leandro Quiroga 9f9ce39789 Fix typo. 2021-04-20 16:50:18 +02:00
buildmaster 4454c820cf Bumping versions 2021-04-20 11:36:51 +00:00
Andrii BohutskyiandAndrii Bohutskyi b8e966fe14 Support circuit breaker group name (#520)
Fixes gh-514

Co-authored-by: Andrii Bohutskyi <abohutskyi@playtika.com>
2021-04-20 11:41:51 +02:00
Jasbir e47255e79d Make feign.Request.Options as refreshable beans inside Feign clients (#526) 2021-04-19 18:27:28 +02:00
Olga MaciaszekSharma 96268d16da Fix checkstyle and formatting. 2021-04-13 15:21:46 +02:00
Olga MaciaszekSharma ac019b4af1 Merge 2.2.x 2021-04-13 15:20:29 +02:00
Olga MaciaszekSharma 4d0caec7ee Fix checkstyle and formatting. 2021-04-13 15:17:00 +02:00
Olga MaciaszekSharma b8aea256da Merge remote-tracking branch 'origin/2.2.x'
# Please enter a commit message to explain why this merge is necessary,
# especially if it merges an updated upstream into a topic branch.
#
# Lines starting with '#' will be ignored, and an empty message aborts
# the commit.
2021-04-13 15:11:13 +02:00
Olga MaciaszekSharma f653a6730d Merge remote-tracking branch 'origin/2.2.x' 2021-04-13 15:08:50 +02:00
Olga MaciaszekSharma 92f7ba9901 Fix GH actions setup 2021-04-13 15:08:27 +02:00
Olga MaciaszekSharma b2c208ba5f Fix GH actions setup 2021-04-13 15:08:00 +02:00
Olga MaciaszekSharma e2a54c1359 Fix GH actions setup 2021-04-13 15:04:10 +02:00
Olga MaciaszekSharma cdfd3695c2 Add GH actions build icon. 2021-04-13 15:03:23 +02:00
Olga MaciaszekSharma a5412cc872 Merge remote-tracking branch 'origin/2.2.x' 2021-04-13 14:54:18 +02:00
Olga MaciaszekSharma 59216f2f82 Switch to building the project with GH actions. 2021-04-13 14:53:48 +02:00
Olga MaciaszekSharma aa01ccb5b2 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientBuilder.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientBuilderTests.java
2021-04-13 13:11:21 +02:00
Sam Kruglov 4d827623f0 Add FeignClientBuilder.Builder#customize(FeignBuilderCustomizer) (#499) (#515) 2021-04-13 12:57:35 +02:00
Olga MaciaszekSharma 86713156f6 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientFactoryBean.java
2021-04-12 14:35:43 +02:00
Olga MaciaszekSharma 5e494aa196 Add more logging. Fixes gh-517. 2021-04-12 14:29:45 +02:00
buildmaster 9db146761a Bumping versions 2021-03-30 11:36:40 +00:00
John Niang af418a04ac Expose request attributes for circuit breaker async invocation (#510) 2021-03-30 11:39:07 +02:00
spencergibb bcea218513 Ignore tests that use reflection in jdk 16 2021-03-18 18:52:34 -04:00
buildmaster 1c49f88e2b Bumping versions 2021-03-18 11:36:51 +00:00
buildmaster 3dbaf056ec Bumping versions to 3.0.3-SNAPSHOT after release 2021-03-17 21:46:51 +00:00
buildmaster 5637465ec8 Going back to snapshots 2021-03-17 21:46:50 +00:00
41 changed files with 981 additions and 160 deletions
-38
View File
@@ -1,38 +0,0 @@
version: 2
jobs:
build:
docker:
- image: springcloud/pipeline-base
environment:
_JAVA_OPTIONS: "-Xms1024m -Xmx2048m"
TERM: dumb
branches:
ignore:
- gh-pages # list of branches to ignore
steps:
- checkout
- restore_cache:
key: sc-openfeign-{{ .Branch }}
- run:
name: "Download dependencies"
command: ./mvnw -s .settings.xml -U --fail-never dependency:go-offline || true
- save_cache:
key: sc-openfeign-{{ .Branch }}
paths:
- ~/.m2
- run:
name: "Running build"
command: ./mvnw -s .settings.xml clean org.jacoco:jacoco-maven-plugin:prepare-agent install -U -P sonar -nsu --batch-mode -Dmaven.test.redirectTestOutputToFile=true -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- run:
name: "Aggregate test results"
when: always
command: |
mkdir -p $CIRCLE_TEST_REPORTS/junit/
find . -type f -regex ".*/target/.*-reports/.*" -exec cp {} $CIRCLE_TEST_REPORTS/junit/ \;
bash <(curl -s https://codecov.io/bash)
- store_artifacts:
path: /junit/
destination: artifacts
- store_test_results:
path: /junit/
destination: testartifacts
+4 -4
View File
@@ -3,7 +3,7 @@
Spring Cloud is released under the non-restrictive Apache 2.0 license,
and follows a very standard Github development process, using Github
tracker for issues and merging pull requests into master. If you want
tracker for issues and merging pull requests into main. If you want
to contribute even something trivial please do not hesitate, but
follow the guidelines below.
@@ -17,7 +17,7 @@ given the ability to merge pull requests.
## Code of Conduct
This project adheres to the Contributor Covenant [code of
conduct](https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report
conduct](https://github.com/spring-cloud/spring-cloud-build/blob/main/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report
unacceptable behavior to spring-code-of-conduct@pivotal.io.
## Code Conventions and Housekeeping
@@ -27,7 +27,7 @@ added after the original pull request but before a merge.
* Use the Spring Framework code format conventions. If you use Eclipse
you can import formatter settings using the
`eclipse-code-formatter.xml` file from the
[Spring Cloud Build](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml) project. If using IntelliJ, you can use the
[Spring Cloud Build](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/spring-cloud-dependencies-parent/eclipse-code-formatter.xml) project. If using IntelliJ, you can use the
[Eclipse Code Formatter Plugin](https://plugins.jetbrains.com/plugin/6546) to import the same file.
* Make sure all new `.java` files to have a simple Javadoc class comment with at least an
`@author` tag identifying you, and preferably at least a paragraph on what the class is
@@ -38,7 +38,7 @@ added after the original pull request but before a merge.
than cosmetic changes).
* Add some Javadocs and, if you change the namespace, some XSD doc elements.
* A few unit tests would help a lot as well -- someone has to do it.
* If no-one else is using your branch, please rebase it against the current master (or
* If no-one else is using your branch, please rebase it against the current main (or
other target branch in the main project).
* When writing a commit message please follow [these conventions](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html),
if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit
+35
View File
@@ -0,0 +1,35 @@
# This workflow will build a Java project with Maven
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Build
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
java: ["8", "11", "16"]
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Cache local Maven repository
uses: actions/cache@v2
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Build with Maven
run: ./mvnw clean install -B -U
+3 -3
View File
@@ -5,9 +5,9 @@ Edit the files in the src/main/asciidoc/ directory instead.
////
image:https://circleci.com/gh/spring-cloud/spring-cloud-openfeign.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-openfeign"]
image::https://github.com/spring-cloud/spring-cloud-openfeign/workflows/Build/badge.svg?branch=main&style=svg["Build",link="https://github.com/spring-cloud/spring-cloud-openfeign/actions"]
image:https://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
image:https://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/main/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
image:https://api.codacy.com/project/badge/Grade/97b04c4e609c4b4f86b415e4437a6484["Codacy code quality", link="https://www.codacy.com/app/Spring-Cloud/spring-cloud-openfeign?utm_source=github.com&utm_medium=referral&utm_content=spring-cloud/spring-cloud-openfeign&utm_campaign=Badge_Grade"]
@@ -319,4 +319,4 @@ IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply chec
== License
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/master/LICENSE.txt[here].
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/main/LICENSE.txt[here].
+1 -1
View File
@@ -6,7 +6,7 @@
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId>
<version>3.0.2</version>
<version>3.0.3</version>
</parent>
<artifactId>spring-cloud-openfeign-docs</artifactId>
<packaging>jar</packaging>
+5 -5
View File
@@ -1,6 +1,6 @@
image:https://circleci.com/gh/spring-cloud/spring-cloud-openfeign.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-openfeign"]
image::https://github.com/spring-cloud/spring-cloud-openfeign/workflows/Build/badge.svg?branch=main&style=svg["Build",link="https://github.com/spring-cloud/spring-cloud-openfeign/actions"]
image:https://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
image:https://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/main/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
image:https://api.codacy.com/project/badge/Grade/97b04c4e609c4b4f86b415e4437a6484["Codacy code quality", link="https://www.codacy.com/app/Spring-Cloud/spring-cloud-openfeign?utm_source=github.com&utm_medium=referral&utm_content=spring-cloud/spring-cloud-openfeign&utm_campaign=Badge_Grade"]
@@ -14,12 +14,12 @@ include::intro.adoc[]
== Building
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/building-jdk8.adoc[]
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/docs/src/main/asciidoc/building-jdk8.adoc[]
== Contributing
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[]
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/docs/src/main/asciidoc/contributing.adoc[]
== License
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/master/LICENSE.txt[here].
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-openfeign/main/LICENSE.txt[here].
+2
View File
@@ -3,10 +3,12 @@
|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.circuitbreaker.group.enabled | `false` | If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker with with group.
|feign.client.config | |
|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-config | `default` |
|feign.client.default-to-properties | `true` |
|feign.client.refresh-enabled | `false` | Enables options value refresh capability for Feign.
|feign.compression.request.enabled | `false` | Enables the request sent by Feign to be compressed.
|feign.compression.request.mime-types | `[text/xml, application/xml, application/json]` | The list of supported mime types.
|feign.compression.request.min-request-size | `2048` | The minimum threshold content size.
+6 -6
View File
@@ -39,7 +39,7 @@ function check_if_anything_to_sync() {
}
function retrieve_current_branch() {
# Code getting the name of the current branch. For master we want to publish as we did until now
# Code getting the name of the current branch. For main we want to publish as we did until now
# https://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch
# If there is a branch already passed will reuse it - otherwise will try to find it
CURRENT_BRANCH=${BRANCH}
@@ -134,8 +134,8 @@ function add_docs_from_target() {
# Copies the docs by using the retrieved properties from Maven build
function copy_docs_for_current_version() {
if [[ "${CURRENT_BRANCH}" == "master" ]] ; then
echo -e "Current branch is master - will copy the current docs only to the root folder"
if [[ "${CURRENT_BRANCH}" == "main" ]] ; then
echo -e "Current branch is main - will copy the current docs only to the root folder"
for f in docs/target/generated-docs/*; do
file=${f#docs/target/generated-docs/*}
if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then
@@ -216,7 +216,7 @@ function commit_changes_if_applicable() {
git commit -a -m "Sync docs from ${CURRENT_BRANCH} to gh-pages" && COMMIT_SUCCESSFUL="yes" || echo "Failed to commit changes"
# Uncomment the following push if you want to auto push to
# the gh-pages branch whenever you commit to master locally.
# the gh-pages branch whenever you commit to main locally.
# This is a little extreme. Use with care!
###################################################################
if [[ "${COMMIT_SUCCESSFUL}" == "yes" ]] ; then
@@ -249,7 +249,7 @@ The idea of this script is to update gh-pages branch with the generated docs. Wi
the script will work in the following manner:
- if there's no gh-pages / target for docs module then the script ends
- for master branch the generated docs are copied to the root of gh-pages branch
- for main branch the generated docs are copied to the root of gh-pages branch
- for any other branch (if that branch is whitelisted) a subfolder with branch name is created
and docs are copied there
- if the version switch is passed (-v) then a tag with (v) prefix will be retrieved and a folder
@@ -327,4 +327,4 @@ build_docs_if_applicable
retrieve_doc_properties
stash_changes
add_docs_from_target
checkout_previous_branch
checkout_previous_branch
+1 -1
View File
@@ -27,7 +27,7 @@ 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].
We welcome contributions. You can read more on how to contribute to the project https://github.com/spring-cloud/spring-cloud-openfeign/blob/main/README.adoc#3-contributing[here].
## Community Support
@@ -55,7 +55,7 @@ public interface StoreClient {
}
----
In the `@FeignClient` annotation the String value ("stores" above) is an arbitrary client name, which is used to create a https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/blocking/client/BlockingLoadBalancerClient.java[Spring Cloud LoadBalancer client].
In the `@FeignClient` annotation the String value ("stores" above) is an arbitrary client name, which is used to create a https://github.com/spring-cloud/spring-cloud-commons/blob/main/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/blocking/client/BlockingLoadBalancerClient.java[Spring Cloud LoadBalancer client].
You can also specify a URL using the `url` attribute
(absolute value or just a hostname). The name of the bean in the
application context is the fully qualified name of the interface.
@@ -345,10 +345,13 @@ public class FooConfiguration {
The circuit breaker name follows this pattern `<feignClientName>#<calledMethod>`. When calling a `@FeignClient` with name `foo` and the called interface method is `bar` then the circuit breaker name will be `foo_bar`.
To enable Spring Cloud CircuitBreaker group set the `feign.circuitbreaker.group.enabled` property to `true` (by default `false`).
[[spring-cloud-feign-circuitbreaker-fallback]]
=== Feign Spring Cloud CircuitBreaker Fallbacks
Spring Cloud CircuitBreaker supports the notion of a fallback: a default code path that is executed when 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.
Spring Cloud CircuitBreaker supports the notion of a fallback: a default code path that is executed when the circuit is open or there is an error. To enable fallbacks for a given `@FeignClient` set the `fallback` attribute to the class name that implements the fallback. You also need to declare your implementation as a Spring bean.
[source,java,indent=0]
----
@@ -717,6 +720,17 @@ You may consider enabling Jackson Modules for the support `org.springframework.d
feign.autoconfiguration.jackson.enabled=true
----
=== Spring `@RefreshScope` Support
If Feign client refresh is enabled, each feign client is created with `feign.Request.Options` as a refresh-scoped bean. This means properties such as `connectTimeout` and `readTimeout` can be refreshed against any Feign client instance through `POST /actuator/refresh`.
By default, refresh behavior in Feign clients is disabled. Use the following property to enable refresh behavior:
[source,java]
----
feign.client.refresh-enabled=true
----
TIP: DO NOT annotate the `@FeignClient` interface with the `@RefreshScope` annotation.
== Configuration properties
To see the list of all Spring Cloud OpenFeign related configuration properties please check link:appendix.html[the Appendix page].
+3 -3
View File
@@ -4,14 +4,14 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-openfeign</artifactId>
<version>3.0.2</version>
<version>3.0.3</version>
<packaging>pom</packaging>
<name>Spring Cloud OpenFeign</name>
<description>Spring Cloud OpenFeign</description>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-build</artifactId>
<version>3.0.2</version>
<version>3.0.3</version>
<relativePath/>
</parent>
<scm>
@@ -26,7 +26,7 @@
<properties>
<main.basedir>${basedir}</main.basedir>
<jackson.version>2.11.3</jackson.version>
<spring-cloud-commons.version>3.0.2</spring-cloud-commons.version>
<spring-cloud-commons.version>3.0.3</spring-cloud-commons.version>
<!-- Plugin versions -->
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
+1 -1
View File
@@ -6,7 +6,7 @@
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId>
<version>3.0.2</version>
<version>3.0.3</version>
<relativePath>..</relativePath> <!-- lookup parent from repository -->
</parent>
<artifactId>spring-cloud-openfeign-core</artifactId>
@@ -42,6 +42,7 @@ import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@@ -77,6 +78,7 @@ import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResour
* @author Tim Peeters
* @author Olga Maciaszek-Sharma
* @author Nguyen Ky Thanh
* @author Andrii Bohutskyi
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Feign.class)
@@ -147,8 +149,9 @@ public class FeignAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(CircuitBreakerFactory.class)
public Targeter circuitBreakerFeignTargeter(CircuitBreakerFactory circuitBreakerFactory) {
return new FeignCircuitBreakerTargeter(circuitBreakerFactory);
public Targeter circuitBreakerFeignTargeter(CircuitBreakerFactory circuitBreakerFactory,
@Value("${feign.circuitbreaker.group.enabled:false}") boolean circuitBreakerGroupEnabled) {
return new FeignCircuitBreakerTargeter(circuitBreakerFactory, circuitBreakerGroupEnabled);
}
}
@@ -26,6 +26,7 @@ import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
* Allows Feign interfaces to work with {@link CircuitBreaker}.
*
* @author Marcin Grzejszczak
* @author Andrii Bohutskyi
* @since 3.0.0
*/
public final class FeignCircuitBreaker {
@@ -50,6 +51,8 @@ public final class FeignCircuitBreaker {
private String feignClientName;
private boolean circuitBreakerGroupEnabled;
Builder circuitBreakerFactory(CircuitBreakerFactory circuitBreakerFactory) {
this.circuitBreakerFactory = circuitBreakerFactory;
return this;
@@ -60,6 +63,11 @@ public final class FeignCircuitBreaker {
return this;
}
Builder circuitBreakerGroupEnabled(boolean circuitBreakerGroupEnabled) {
this.circuitBreakerGroupEnabled = circuitBreakerGroupEnabled;
return this;
}
public <T> T target(Target<T> target, T fallback) {
return build(fallback != null ? new FallbackFactory.Default<T>(fallback) : null).newInstance(target);
}
@@ -74,8 +82,9 @@ public final class FeignCircuitBreaker {
}
public Feign build(final FallbackFactory<?> nullableFallbackFactory) {
super.invocationHandlerFactory((target, dispatch) -> new FeignCircuitBreakerInvocationHandler(
circuitBreakerFactory, target, dispatch, nullableFallbackFactory));
super.invocationHandlerFactory(
(target, dispatch) -> new FeignCircuitBreakerInvocationHandler(circuitBreakerFactory,
feignClientName, target, dispatch, nullableFallbackFactory, circuitBreakerGroupEnabled));
return super.build();
}
@@ -30,6 +30,8 @@ import feign.Target;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import static feign.Util.checkNotNull;
@@ -37,6 +39,8 @@ class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
private final CircuitBreakerFactory factory;
private final String feignClientName;
private final Target<?> target;
private final Map<Method, InvocationHandlerFactory.MethodHandler> dispatch;
@@ -45,13 +49,18 @@ class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
private final Map<Method, Method> fallbackMethodMap;
FeignCircuitBreakerInvocationHandler(CircuitBreakerFactory factory, Target<?> target,
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch, FallbackFactory<?> nullableFallbackFactory) {
private final boolean circuitBreakerGroupEnabled;
FeignCircuitBreakerInvocationHandler(CircuitBreakerFactory factory, String feignClientName, Target<?> target,
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch, FallbackFactory<?> nullableFallbackFactory,
boolean circuitBreakerGroupEnabled) {
this.factory = factory;
this.feignClientName = feignClientName;
this.target = checkNotNull(target, "target");
this.dispatch = checkNotNull(dispatch, "dispatch");
this.fallbackMethodMap = toFallbackMethod(dispatch);
this.nullableFallbackFactory = nullableFallbackFactory;
this.circuitBreakerGroupEnabled = circuitBreakerGroupEnabled;
}
@Override
@@ -74,7 +83,8 @@ class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
return toString();
}
String circuitName = Feign.configKey(target.type(), method);
CircuitBreaker circuitBreaker = this.factory.create(circuitName);
CircuitBreaker circuitBreaker = circuitBreakerGroupEnabled ? factory.create(circuitName, feignClientName)
: factory.create(circuitName);
Supplier<Object> supplier = asSupplier(method, args);
if (this.nullableFallbackFactory != null) {
Function<Throwable, Object> fallbackFunction = throwable -> {
@@ -92,8 +102,10 @@ class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
}
private Supplier<Object> asSupplier(final Method method, final Object[] args) {
final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return () -> {
try {
RequestContextHolder.setRequestAttributes(requestAttributes);
return this.dispatch.get(method).invoke(args);
}
catch (RuntimeException throwable) {
@@ -102,6 +114,9 @@ class FeignCircuitBreakerInvocationHandler implements InvocationHandler {
catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
finally {
RequestContextHolder.resetRequestAttributes();
}
};
}
@@ -27,8 +27,11 @@ class FeignCircuitBreakerTargeter implements Targeter {
private final CircuitBreakerFactory circuitBreakerFactory;
FeignCircuitBreakerTargeter(CircuitBreakerFactory circuitBreakerFactory) {
private final boolean circuitBreakerGroupEnabled;
FeignCircuitBreakerTargeter(CircuitBreakerFactory circuitBreakerFactory, boolean circuitBreakerGroupEnabled) {
this.circuitBreakerFactory = circuitBreakerFactory;
this.circuitBreakerGroupEnabled = circuitBreakerGroupEnabled;
}
@Override
@@ -81,7 +84,8 @@ class FeignCircuitBreakerTargeter implements Targeter {
}
private FeignCircuitBreaker.Builder builder(String feignClientName, FeignCircuitBreaker.Builder builder) {
return builder.circuitBreakerFactory(this.circuitBreakerFactory).feignClientName(feignClientName);
return builder.circuitBreakerFactory(circuitBreakerFactory).feignClientName(feignClientName)
.circuitBreakerGroupEnabled(circuitBreakerGroupEnabled);
}
}
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign;
import feign.Feign;
import org.springframework.context.ApplicationContext;
/**
@@ -26,6 +28,7 @@ import org.springframework.context.ApplicationContext;
*
* @author Sven Döring
* @author Matt King
* @author Sam Kruglov
*/
public class FeignClientBuilder {
@@ -76,6 +79,18 @@ public class FeignClientBuilder {
return this;
}
/**
* Applies a {@link FeignBuilderCustomizer} to the underlying
* {@link Feign.Builder}. May be called multiple times.
* @param customizer applied in the same order as supplied here after applying
* customizers found in the context.
* @return the {@link Builder} with the customizer added
*/
public Builder<T> customize(final FeignBuilderCustomizer customizer) {
this.feignClientFactoryBean.addCustomizer(customizer);
return this;
}
public Builder<T> contextId(final String contextId) {
this.feignClientFactoryBean.setContextId(contextId);
return this;
@@ -36,6 +36,8 @@ import feign.Target.HardCodedTarget;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
@@ -63,6 +65,8 @@ import org.springframework.util.StringUtils;
* @author Ilia Ilinykh
* @author Marcin Grzejszczak
* @author Jonatan Ivanov
* @author Sam Kruglov
* @author Jasbir Singh
*/
public class FeignClientFactoryBean
implements FactoryBean<Object>, InitializingBean, ApplicationContextAware, BeanFactoryAware {
@@ -72,6 +76,8 @@ public class FeignClientFactoryBean
* lifecycle race condition.
***********************************/
private static Log LOG = LogFactory.getLog(FeignClientFactoryBean.class);
private Class<?> type;
private String name;
@@ -100,6 +106,10 @@ public class FeignClientFactoryBean
private boolean followRedirects = new Request.Options().isFollowRedirects();
private boolean refreshableClient = false;
private final List<FeignBuilderCustomizer> additionalCustomizers = new ArrayList<>();
@Override
public void afterPropertiesSet() {
Assert.hasText(contextId, "Context id must be set");
@@ -133,6 +143,7 @@ public class FeignClientFactoryBean
customizerMap.values().stream().sorted(AnnotationAwareOrderComparator.INSTANCE)
.forEach(feignBuilderCustomizer -> feignBuilderCustomizer.customize(builder));
}
additionalCustomizers.forEach(customizer -> customizer.customize(builder));
}
protected void configureFeign(FeignContext context, Feign.Builder builder) {
@@ -180,6 +191,10 @@ public class FeignClientFactoryBean
}
}
Request.Options options = getInheritedAwareOptional(context, Request.Options.class);
if (options == null) {
options = getOptionsByName(context, contextId);
}
if (options != null) {
builder.options(options);
readTimeoutMillis = options.readTimeoutMillis();
@@ -223,12 +238,15 @@ public class FeignClientFactoryBean
builder.logLevel(config.getLoggerLevel());
}
connectTimeoutMillis = config.getConnectTimeout() != null ? config.getConnectTimeout() : connectTimeoutMillis;
readTimeoutMillis = config.getReadTimeout() != null ? config.getReadTimeout() : readTimeoutMillis;
followRedirects = config.isFollowRedirects() != null ? config.isFollowRedirects() : followRedirects;
if (!refreshableClient) {
connectTimeoutMillis = config.getConnectTimeout() != null ? config.getConnectTimeout()
: connectTimeoutMillis;
readTimeoutMillis = config.getReadTimeout() != null ? config.getReadTimeout() : readTimeoutMillis;
followRedirects = config.isFollowRedirects() != null ? config.isFollowRedirects() : followRedirects;
builder.options(new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS, readTimeoutMillis,
TimeUnit.MILLISECONDS, followRedirects));
builder.options(new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS, readTimeoutMillis,
TimeUnit.MILLISECONDS, followRedirects));
}
if (config.getRetryer() != null) {
Retryer retryer = getOrInstantiate(config.getRetryer());
@@ -334,6 +352,20 @@ public class FeignClientFactoryBean
"No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalancer?");
}
/**
* Meant to get Options bean from context with bean name.
* @param context context of Feign client
* @param contextId name of feign client
* @return returns Options found in context
*/
protected Request.Options getOptionsByName(FeignContext context, String contextId) {
if (refreshableClient) {
return context.getInstance(contextId, Request.Options.class.getCanonicalName() + "-" + contextId,
Request.Options.class);
}
return null;
}
@Override
public Object getObject() {
return getTarget();
@@ -350,6 +382,12 @@ public class FeignClientFactoryBean
Feign.Builder builder = feign(context);
if (!StringUtils.hasText(url)) {
if (url != null && LOG.isWarnEnabled()) {
LOG.warn("The provided URL is empty. Will try picking an instance via load-balancing.");
}
else if (LOG.isDebugEnabled()) {
LOG.debug("URL not provided. Will use LoadBalancer.");
}
if (!name.startsWith("http")) {
url = "http://" + name;
}
@@ -460,6 +498,10 @@ public class FeignClientFactoryBean
this.inheritParentContext = inheritParentContext;
}
public void addCustomizer(FeignBuilderCustomizer customizer) {
additionalCustomizers.add(customizer);
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@@ -486,6 +528,10 @@ public class FeignClientFactoryBean
this.fallbackFactory = fallbackFactory;
}
public void setRefreshableClient(boolean refreshableClient) {
this.refreshableClient = refreshableClient;
}
@Override
public boolean equals(Object o) {
if (this == o) {
@@ -502,13 +548,14 @@ public class FeignClientFactoryBean
&& Objects.equals(path, that.path) && Objects.equals(type, that.type) && Objects.equals(url, that.url)
&& Objects.equals(connectTimeoutMillis, that.connectTimeoutMillis)
&& Objects.equals(readTimeoutMillis, that.readTimeoutMillis)
&& Objects.equals(followRedirects, that.followRedirects);
&& Objects.equals(followRedirects, that.followRedirects)
&& Objects.equals(refreshableClient, that.refreshableClient);
}
@Override
public int hashCode() {
return Objects.hash(applicationContext, beanFactory, decode404, inheritParentContext, fallback, fallbackFactory,
name, path, type, url, readTimeoutMillis, connectTimeoutMillis, followRedirects);
name, path, type, url, readTimeoutMillis, connectTimeoutMillis, followRedirects, refreshableClient);
}
@Override
@@ -520,8 +567,8 @@ public class FeignClientFactoryBean
.append(", ").append("beanFactory=").append(beanFactory).append(", ").append("fallback=")
.append(fallback).append(", ").append("fallbackFactory=").append(fallbackFactory).append("}")
.append("connectTimeoutMillis=").append(connectTimeoutMillis).append("}").append("readTimeoutMillis=")
.append(readTimeoutMillis).append("}").append("followRedirects=").append(followRedirects).append("}")
.toString();
.append(readTimeoutMillis).append("}").append("followRedirects=").append(followRedirects)
.append("refreshableClient=").append(refreshableClient).append("}").toString();
}
@Override
@@ -29,6 +29,9 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import feign.Request;
import org.springframework.aop.scope.ScopedProxyUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition;
@@ -63,6 +66,7 @@ import org.springframework.util.StringUtils;
* @author Michal Domagala
* @author Marcin Grzejszczak
* @author Olga Maciaszek-Sharma
* @author Jasbir Singh
*/
class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
@@ -213,6 +217,7 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar, ResourceLo
factoryBean.setName(name);
factoryBean.setContextId(contextId);
factoryBean.setType(clazz);
factoryBean.setRefreshableClient(isClientRefreshEnabled());
BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(clazz, () -> {
factoryBean.setUrl(getUrl(beanFactory, attributes));
factoryBean.setPath(getPath(beanFactory, attributes));
@@ -249,6 +254,8 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar, ResourceLo
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, qualifiers);
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
registerOptionsBeanDefinition(registry, contextId);
}
private void validate(Map<String, Object> attributes) {
@@ -408,4 +415,28 @@ class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar, ResourceLo
this.environment = environment;
}
/**
* This method is meant to create {@link Request.Options} beans definition with
* refreshScope.
* @param registry spring bean definition registry
* @param contextId name of feign client
*/
private void registerOptionsBeanDefinition(BeanDefinitionRegistry registry, String contextId) {
if (isClientRefreshEnabled()) {
String beanName = Request.Options.class.getCanonicalName() + "-" + contextId;
BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder
.genericBeanDefinition(OptionsFactoryBean.class);
definitionBuilder.setScope("refresh");
definitionBuilder.addPropertyValue("contextId", contextId);
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(definitionBuilder.getBeanDefinition(),
beanName);
definitionHolder = ScopedProxyUtils.createScopedProxy(definitionHolder, registry, true);
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);
}
}
private boolean isClientRefreshEnabled() {
return environment.getProperty("feign.client.refresh-enabled", Boolean.class, false);
}
}
@@ -30,6 +30,7 @@ import org.springframework.lang.Nullable;
* @author Spencer Gibb
* @author Dave Syer
* @author Matt King
* @author Jasbir Singh
*/
public class FeignContext extends NamedContextFactory<FeignClientSpecification> {
@@ -52,4 +53,8 @@ public class FeignContext extends NamedContextFactory<FeignClientSpecification>
return getContext(name).getBeansOfType(type);
}
public <T> T getInstance(String contextName, String beanName, Class<T> type) {
return getContext(contextName).getBean(beanName, type);
}
}
@@ -0,0 +1,86 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import feign.Request;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* This factory bean is meant to create {@link Request.Options} instance as per the
* applicable configurations.
*
* @author Jasbir Singh
*/
public class OptionsFactoryBean implements FactoryBean<Request.Options>, ApplicationContextAware {
private ApplicationContext applicationContext;
private String contextId;
private Request.Options options;
@Override
public Class<?> getObjectType() {
return Request.Options.class;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public Request.Options getObject() throws Exception {
if (options != null) {
return options;
}
options = new Request.Options();
FeignClientProperties properties = applicationContext.getBean(FeignClientProperties.class);
options = createOptionsWithApplicableValues(properties.getConfig().get(properties.getDefaultConfig()), options);
options = createOptionsWithApplicableValues(properties.getConfig().get(contextId), options);
return options;
}
public void setContextId(String contextId) {
this.contextId = contextId;
}
private Request.Options createOptionsWithApplicableValues(
FeignClientProperties.FeignClientConfiguration clientConfiguration, Request.Options options) {
if (Objects.isNull(clientConfiguration)) {
return options;
}
int connectTimeoutMillis = Objects.nonNull(clientConfiguration.getConnectTimeout())
? clientConfiguration.getConnectTimeout() : options.connectTimeoutMillis();
int readTimeoutMillis = Objects.nonNull(clientConfiguration.getReadTimeout())
? clientConfiguration.getReadTimeout() : options.readTimeoutMillis();
boolean followRedirects = Objects.nonNull(clientConfiguration.isFollowRedirects())
? clientConfiguration.isFollowRedirects() : options.isFollowRedirects();
return new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS, readTimeoutMillis,
TimeUnit.MILLISECONDS, followRedirects);
}
}
@@ -72,8 +72,8 @@ public class MatrixVariableParameterProcessor implements AnnotatedParameterProce
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());
return paramMap.keySet().stream().filter(key -> paramMap.get(key) != null)
.map(key -> ";" + key + "=" + paramMap.get(key).toString()).collect(Collectors.joining());
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2020 the original author or authors.
* Copyright 2016-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,75 +16,48 @@
package org.springframework.cloud.openfeign.hateoas;
import java.util.Arrays;
import java.util.Collections;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration;
import org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration;
import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.hateoas.mediatype.MessageResolver;
import org.springframework.hateoas.mediatype.hal.CurieProvider;
import org.springframework.hateoas.mediatype.hal.DefaultCurieProvider;
import org.springframework.hateoas.mediatype.hal.HalConfiguration;
import org.springframework.hateoas.mediatype.hal.Jackson2HalModule;
import org.springframework.hateoas.server.LinkRelationProvider;
import org.springframework.hateoas.mediatype.hal.HalMediaTypeConfiguration;
import org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter;
import static org.springframework.hateoas.MediaTypes.HAL_JSON;
/**
* @author Hector Espert
* @author Olga Maciaszek-Sharma
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
@ConditionalOnClass(RepresentationModel.class)
@AutoConfigureAfter({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
RepositoryRestMvcAutoConfiguration.class })
@AutoConfigureBefore(HypermediaAutoConfiguration.class)
public class FeignHalAutoConfiguration {
@Bean
@ConditionalOnBean(HalMediaTypeConfiguration.class)
@ConditionalOnMissingBean
public TypeConstrainedMappingJackson2HttpMessageConverter halJacksonHttpMessageConverter(
ObjectProvider<ObjectMapper> objectMapper, ObjectProvider<HalConfiguration> halConfiguration,
ObjectProvider<MessageResolver> messageResolver, ObjectProvider<CurieProvider> curieProvider,
ObjectProvider<LinkRelationProvider> linkRelationProvider) {
ObjectProvider<ObjectMapper> objectMapper, HalMediaTypeConfiguration halConfiguration) {
ObjectMapper mapper = objectMapper.getIfAvailable(ObjectMapper::new).copy();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
HalConfiguration configuration = halConfiguration.getIfAvailable(HalConfiguration::new);
CurieProvider curieProviderInstance = curieProvider
.getIfAvailable(() -> new DefaultCurieProvider(Collections.emptyMap()));
Jackson2HalModule.HalHandlerInstantiator halHandlerInstantiator = new Jackson2HalModule.HalHandlerInstantiator(
linkRelationProvider.getIfAvailable(), curieProviderInstance, messageResolver.getIfAvailable(),
configuration);
mapper.setHandlerInstantiator(halHandlerInstantiator);
if (!Jackson2HalModule.isAlreadyRegisteredIn(mapper)) {
Jackson2HalModule halModule = new Jackson2HalModule();
mapper.registerModule(halModule);
}
halConfiguration.configureObjectMapper(mapper);
TypeConstrainedMappingJackson2HttpMessageConverter converter = new TypeConstrainedMappingJackson2HttpMessageConverter(
RepresentationModel.class);
converter.setSupportedMediaTypes(Arrays.asList(HAL_JSON));
converter.setSupportedMediaTypes(Collections.singletonList(HAL_JSON));
converter.setObjectMapper(mapper);
return converter;
}
@@ -14,6 +14,12 @@
"description": "If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker.",
"defaultValue": "false"
},
{
"name": "feign.circuitbreaker.group.enabled",
"type": "java.lang.Boolean",
"description": "If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker with with group.",
"defaultValue": "false"
},
{
"name": "feign.httpclient.enabled",
"type": "java.lang.Boolean",
@@ -55,6 +61,12 @@
"type": "java.lang.Boolean",
"description": "Enables metrics capability for Feign.",
"defaultValue": "true"
},
{
"name": "feign.client.refresh-enabled",
"type": "java.lang.Boolean",
"description": "Enables options value refresh capability for Feign.",
"defaultValue": "false"
}
]
}
@@ -30,6 +30,7 @@ import static org.mockito.Mockito.mock;
/**
* @author Tim Peeters
* @author Olga Maciaszek-Sharma
* @author Andrii Bohutskyi
*/
class FeignAutoConfigurationTests {
@@ -45,14 +46,33 @@ class FeignAutoConfigurationTests {
@Test
void shouldInstantiateFeignCircuitBreakerTargeterWhenEnabled() {
runner.withBean(CircuitBreakerFactory.class, () -> mock(CircuitBreakerFactory.class))
.withPropertyValues("feign.circuitbreaker.enabled=true").run(ctx -> {
assertOnlyOneTargeterPresent(ctx, FeignCircuitBreakerTargeter.class);
assertThatFeignCircuitBreakerTargeterHasGroupEnabledPropertyWithValue(ctx, false);
});
}
@Test
void shouldInstantiateFeignCircuitBreakerTargeterWithEnabledGroup() {
runner.withBean(CircuitBreakerFactory.class, () -> mock(CircuitBreakerFactory.class))
.withPropertyValues("feign.circuitbreaker.enabled=true")
.run(ctx -> assertOnlyOneTargeterPresent(ctx, FeignCircuitBreakerTargeter.class));
.withPropertyValues("feign.circuitbreaker.group.enabled=true").run(ctx -> {
assertOnlyOneTargeterPresent(ctx, FeignCircuitBreakerTargeter.class);
assertThatFeignCircuitBreakerTargeterHasGroupEnabledPropertyWithValue(ctx, true);
});
}
private void assertOnlyOneTargeterPresent(ConfigurableApplicationContext ctx, Class<?> beanClass) {
assertThat(ctx.getBeansOfType(Targeter.class)).hasSize(1).hasValueSatisfying(new Condition<>(
beanClass::isInstance, String.format("Targeter should be an instance of %s", beanClass)));
}
private void assertThatFeignCircuitBreakerTargeterHasGroupEnabledPropertyWithValue(
ConfigurableApplicationContext ctx, boolean expectedValue) {
final FeignCircuitBreakerTargeter bean = ctx.getBean(FeignCircuitBreakerTargeter.class);
assertThat(bean).hasFieldOrPropertyWithValue("circuitBreakerGroupEnabled", expectedValue);
}
}
@@ -33,6 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Matt King
* @author Sam Kruglov
*/
public class FeignBuilderCustomizerTests {
@@ -74,6 +75,24 @@ public class FeignBuilderCustomizerTests {
context.close();
}
@Test
public void testBuildCustomizerOrderedWithAdditional() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
FeignBuilderCustomizerTests.SampleConfiguration3.class);
FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class);
clientFactoryBean.addCustomizer(builder -> builder.logLevel(Logger.Level.BASIC));
clientFactoryBean.addCustomizer(Feign.Builder::doNotCloseAfterDecode);
FeignContext feignContext = context.getBean(FeignContext.class);
Feign.Builder builder = clientFactoryBean.feign(feignContext);
assertFeignBuilderField(builder, "logLevel", Logger.Level.BASIC);
assertFeignBuilderField(builder, "decode404", true);
assertFeignBuilderField(builder, "closeAfterDecode", false);
context.close();
}
private static FeignClientFactoryBean defaultFeignClientFactoryBean() {
FeignClientFactoryBean feignClientFactoryBean = new FeignClientFactoryBean();
feignClientFactoryBean.setContextId("test");
@@ -24,6 +24,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import feign.Feign;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Rule;
@@ -39,6 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Sven Döring
* @author Sam Kruglov
*/
public class FeignClientBuilderTests {
@@ -56,6 +58,12 @@ public class FeignClientBuilderTests {
private static void assertFactoryBeanField(final FeignClientBuilder.Builder builder, final String fieldName,
final Object expectedValue) {
final Object value = getFactoryBeanField(builder, fieldName);
assertThat(value).as("Expected value for the field '" + fieldName + "':").isEqualTo(expectedValue);
}
@SuppressWarnings("unchecked")
private static <T> T getFactoryBeanField(final FeignClientBuilder.Builder builder, final String fieldName) {
final Field factoryBeanField = ReflectionUtils.findField(FeignClientBuilder.Builder.class,
"feignClientFactoryBean");
ReflectionUtils.makeAccessible(factoryBeanField);
@@ -64,8 +72,7 @@ public class FeignClientBuilderTests {
final Field field = ReflectionUtils.findField(FeignClientFactoryBean.class, fieldName);
ReflectionUtils.makeAccessible(field);
final Object value = ReflectionUtils.getField(field, factoryBean);
assertThat(value).as("Expected value for the field '" + fieldName + "':").isEqualTo(expectedValue);
return (T) ReflectionUtils.getField(field, factoryBean);
}
@Before
@@ -136,7 +143,7 @@ public class FeignClientBuilderTests {
// when:
final FeignClientBuilder.Builder builder = this.feignClientBuilder
.forType(TestFeignClient.class, new FeignClientFactoryBean(), "TestClient").decode404(true)
.path("Path/").url("Url/").contextId("TestContext");
.path("Path/").url("Url/").contextId("TestContext").customize(Feign.Builder::doNotCloseAfterDecode);
// then:
assertFactoryBeanField(builder, "applicationContext", this.applicationContext);
@@ -148,6 +155,8 @@ public class FeignClientBuilderTests {
assertFactoryBeanField(builder, "url", "http://Url/");
assertFactoryBeanField(builder, "path", "/Path");
assertFactoryBeanField(builder, "decode404", true);
List<FeignBuilderCustomizer> additionalCustomizers = getFactoryBeanField(builder, "additionalCustomizers");
assertThat(additionalCustomizers).hasSize(1);
}
@Test
@@ -25,8 +25,9 @@ import feign.InvocationHandlerFactory;
import feign.RequestLine;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -35,7 +36,6 @@ 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;
@@ -46,7 +46,6 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Michael Cramer
* @author Jonatan Ivanov
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = FeignClientErrorDecoderTests.TestConfiguration.class)
@DirtiesContext
public class FeignClientErrorDecoderTests {
@@ -73,12 +72,14 @@ public class FeignClientErrorDecoderTests {
}
@Test
@DisabledForJreRange(min = JRE.JAVA_16)
public void useConfiguredErrorDecoderWhenAlsoErrorDecoderFactoryIsAvailable() {
Object errorDecoder = getErrorDecoderFromClient(this.foo);
assertThat(errorDecoder).isInstanceOf(ErrorDecoder.Default.class);
}
@Test
@DisabledForJreRange(min = JRE.JAVA_16)
public void useErrorDecoderFromErrorDecoderFactory() {
Object errorDecoder = getErrorDecoderFromClient(this.bar);
assertThat(errorDecoder).isInstanceOf(ErrorDecoderImpl.class);
@@ -25,7 +25,9 @@ import java.util.Map;
import feign.Client;
import feign.InvocationHandlerFactory;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
@@ -66,6 +68,7 @@ public class FeignClientFactoryTests {
}
@Test
@DisabledForJreRange(min = JRE.JAVA_16)
public void shouldRedirectToDelegateWhenUrlSet() {
new ApplicationContextRunner().withUserConfiguration(TestConfig.class).run(this::defaultClientUsed);
}
@@ -46,8 +46,9 @@ import feign.codec.EncodeException;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import feign.micrometer.MicrometerCapability;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@@ -61,7 +62,6 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@@ -72,7 +72,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
@@ -82,7 +82,6 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Jonatan Ivanov
*/
@SuppressWarnings("FieldMayBeFinal")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = FeignClientUsingPropertiesTests.Application.class, webEnvironment = RANDOM_PORT)
@TestPropertySource("classpath:feign-properties.properties")
@DirtiesContext
@@ -161,16 +160,14 @@ public class FeignClientUsingPropertiesTests {
assertThat(response).isEqualTo("OK");
}
@Test(expected = RetryableException.class)
@Test
public void testBar() {
barClient().bar();
fail("it should timeout");
assertThatThrownBy(() -> barClient().bar()).isInstanceOf(RetryableException.class);
}
@Test(expected = SocketTimeoutException.class)
@Test
public void testUnwrap() throws Exception {
unwrapClient().unwrap();
fail("it should timeout");
assertThatThrownBy(() -> unwrapClient().unwrap()).isInstanceOf(SocketTimeoutException.class);
}
@Test
@@ -205,6 +202,7 @@ public class FeignClientUsingPropertiesTests {
}
@Test
@DisabledForJreRange(min = JRE.JAVA_16)
public void readTimeoutShouldWorkWhenConnectTimeoutNotSet() {
FeignClientFactoryBean readTimeoutFactoryBean = new FeignClientFactoryBean();
readTimeoutFactoryBean.setContextId("readTimeout");
@@ -221,6 +219,7 @@ public class FeignClientUsingPropertiesTests {
}
@Test
@DisabledForJreRange(min = JRE.JAVA_16)
public void connectTimeoutShouldWorkWhenReadTimeoutNotSet() {
FeignClientFactoryBean readTimeoutFactoryBean = new FeignClientFactoryBean();
readTimeoutFactoryBean.setContextId("connectTimeout");
@@ -250,6 +249,7 @@ public class FeignClientUsingPropertiesTests {
}
@Test
@DisabledForJreRange(min = JRE.JAVA_16)
public void shouldSetFollowRedirects() {
FeignClientFactoryBean testFactoryBean = new FeignClientFactoryBean();
testFactoryBean.setContextId("test");
@@ -0,0 +1,185 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign;
import java.util.concurrent.TimeUnit;
import feign.Request;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.context.support.GenericWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jasbir Singh
*/
@SpringBootTest
@TestPropertySource("classpath:feign-refreshable-properties.properties")
@DirtiesContext
public class FeignClientWithRefreshableOptionsTest {
@Autowired
private ApplicationContext applicationContext;
@Autowired
private RefreshScope refreshScope;
@Autowired
private Application.RefreshableClient refreshableClient;
@Autowired
private Application.ReadTimeoutClient readTimeoutClient;
@Autowired
private Application.ConnectTimeoutClient connectTimeoutClient;
@Autowired
private Application.OverrideOptionsClient overrideOptionsClient;
@Autowired
private FeignClientProperties clientProperties;
@Test
public void overridedOptionsBeanShouldBePresentInsteadOfRefreshable() {
OptionsTestClient.OptionsResponseForTests options = overrideOptionsClient.override();
assertConnectionAndReadTimeout(options, 1, 1);
}
@Test
public void refreshScopeBeanDefinitionShouldBePresent() {
BeanDefinition beanDefinition = ((GenericWebApplicationContext) applicationContext)
.getBeanDefinition(Request.Options.class.getCanonicalName() + "-" + "refreshableClient");
BeanDefinition originBeanDefinition = beanDefinition.getOriginatingBeanDefinition();
assertThat(originBeanDefinition.getBeanClassName()).isEqualTo(OptionsFactoryBean.class.getCanonicalName());
assertThat(originBeanDefinition.getScope()).isEqualTo("refresh");
}
@Test
public void withConfigDefaultConnectTimeoutAndReadTimeout() {
OptionsTestClient.OptionsResponseForTests options = refreshableClient.refreshable();
assertConnectionAndReadTimeout(options, 5000, 5000);
}
@Test
public void readTimeoutShouldWorkWhenConnectTimeoutNotSet() {
OptionsTestClient.OptionsResponseForTests options = readTimeoutClient.readTimeout();
assertConnectionAndReadTimeout(options, 5000, 2000);
}
@Test
public void connectTimeoutShouldWorkWhenReadTimeoutNotSet() {
OptionsTestClient.OptionsResponseForTests options = connectTimeoutClient.connectTimeout();
assertConnectionAndReadTimeout(options, 2000, 5000);
}
@Test
public void connectTimeoutShouldNotChangeWithoutContextRefresh() {
OptionsTestClient.OptionsResponseForTests options = connectTimeoutClient.connectTimeout();
assertConnectionAndReadTimeout(options, 2000, 5000);
clientProperties.getConfig().get("connectTimeout").setConnectTimeout(5000);
options = connectTimeoutClient.connectTimeout();
assertConnectionAndReadTimeout(options, 2000, 5000);
}
@Test
public void connectTimeoutShouldChangeAfterContextRefresh() {
OptionsTestClient.OptionsResponseForTests options = connectTimeoutClient.connectTimeout();
assertConnectionAndReadTimeout(options, 2000, 5000);
clientProperties.getConfig().get("connectTimeout").setConnectTimeout(5000);
refreshScope.refreshAll();
options = connectTimeoutClient.connectTimeout();
assertConnectionAndReadTimeout(options, 5000, 5000);
}
private void assertConnectionAndReadTimeout(OptionsTestClient.OptionsResponseForTests options,
int expectedConnectTimeoutInMillis, int expectedReadTimeoutInMillis) {
assertThat(options.getConnectTimeout()).isEqualTo(expectedConnectTimeoutInMillis);
assertThat(options.getReadTimeout()).isEqualTo(expectedReadTimeoutInMillis);
}
@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties(FeignClientProperties.class)
@EnableFeignClients(clients = { Application.OverrideOptionsClient.class, Application.RefreshableClient.class,
Application.ReadTimeoutClient.class, Application.ConnectTimeoutClient.class })
protected static class Application {
@Bean
OptionsTestClient client() {
return new OptionsTestClient();
}
@FeignClient(name = "overrideOptionsClient", configuration = OverrideConfig.class)
protected interface OverrideOptionsClient {
@GetMapping("/override")
OptionsTestClient.OptionsResponseForTests override();
}
@FeignClient(name = "refreshableClient")
protected interface RefreshableClient {
@GetMapping("/refreshable")
OptionsTestClient.OptionsResponseForTests refreshable();
}
@FeignClient(name = "readTimeout")
protected interface ReadTimeoutClient {
@GetMapping("/readTimeout")
OptionsTestClient.OptionsResponseForTests readTimeout();
}
@FeignClient(name = "connectTimeout")
protected interface ConnectTimeoutClient {
@GetMapping("/connectTimeout")
OptionsTestClient.OptionsResponseForTests connectTimeout();
}
@Configuration
protected class OverrideConfig {
@Bean
public Request.Options options() {
return new Request.Options(1, TimeUnit.MILLISECONDS, 1, TimeUnit.MILLISECONDS, true);
}
}
}
}
@@ -66,10 +66,18 @@ public class FeignHttpClientConfigurationTests {
@Test
public void disableSslTest() throws Exception {
HttpClientConnectionManager connectionManager = this.context.getBean(HttpClientConnectionManager.class);
Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(connectionManager);
assertThat(socketFactoryRegistry.lookup("https")).isNotNull();
assertThat(this.getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers()).isNull();
try {
HttpClientConnectionManager connectionManager = this.context.getBean(HttpClientConnectionManager.class);
Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(connectionManager);
assertThat(socketFactoryRegistry.lookup("https")).isNotNull();
assertThat(this.getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers()).isNull();
}
catch (RuntimeException e) {
// FIXME: java 16 need junit 5 compatible modified classpath extension
if (e.getMessage() == null || !e.getMessage().startsWith("Unable to make field private final")) {
ReflectionUtils.rethrowRuntimeException(e);
}
}
}
private Lookup<ConnectionSocketFactory> getConnectionSocketFactoryLookup(
@@ -0,0 +1,113 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import feign.Client;
import feign.Request;
import feign.Response;
/**
* @author Jasbir Singh
*/
public class OptionsTestClient implements Client {
private static ObjectMapper mapper;
static {
mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule()).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Override
public Response execute(Request request, Request.Options options) throws IOException {
return Response.builder().status(200).request(request).headers(headers()).body(prepareResponse(options))
.build();
}
private Map<String, Collection<String>> headers() {
Map<String, Collection<String>> headers = new LinkedHashMap<>();
headers.put("Content-Type", Collections.singletonList("application/json"));
return headers;
}
private byte[] prepareResponse(Request.Options options) {
try {
OptionsResponseForTests response = new OptionsResponseForTests(options.connectTimeoutMillis(),
TimeUnit.MILLISECONDS, options.readTimeoutMillis(), TimeUnit.MILLISECONDS);
return mapper.writeValueAsString(response).getBytes();
}
catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
static class OptionsResponseForTests {
private long connectTimeout;
private TimeUnit connectTimeoutUnit;
private long readTimeout;
private TimeUnit readTimeoutUnit;
OptionsResponseForTests(long connectTimeout, TimeUnit connectTimeoutUnit, long readTimeout,
TimeUnit readTimeoutUnit) {
this.connectTimeout = connectTimeout;
this.connectTimeoutUnit = connectTimeoutUnit;
this.readTimeout = readTimeout;
this.readTimeoutUnit = readTimeoutUnit;
}
public long getConnectTimeout() {
return connectTimeout;
}
public TimeUnit getConnectTimeoutUnit() {
return connectTimeoutUnit;
}
public long getReadTimeout() {
return readTimeout;
}
public TimeUnit getReadTimeoutUnit() {
return readTimeoutUnit;
}
@Override
public String toString() {
return "OptionsResponseForTests{" + "connectTimeout=" + connectTimeout + ", connectTimeoutUnit="
+ connectTimeoutUnit + ", readTimeout=" + readTimeout + ", readTimeoutUnit=" + readTimeoutUnit
+ '}';
}
}
}
@@ -0,0 +1,60 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.circuitbreaker;
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
/**
* Asynchronous circuit breaker.
*
* @author John Niang
*/
class AsyncCircuitBreaker implements CircuitBreaker {
final Duration timeout;
final ExecutorService executorService;
AsyncCircuitBreaker(Duration timeout) {
this(timeout, Executors.newCachedThreadPool());
}
AsyncCircuitBreaker(Duration timeout, ExecutorService executorService) {
this.timeout = timeout;
this.executorService = executorService;
}
@Override
public <T> T run(Supplier<T> toRun, Function<Throwable, T> fallback) {
Future<T> future = executorService.submit(toRun::get);
try {
return future.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
}
catch (Throwable t) {
return fallback.apply(t);
}
}
}
@@ -0,0 +1,177 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.circuitbreaker;
import java.time.Duration;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Function;
import javax.servlet.http.HttpServletRequest;
import feign.RequestInterceptor;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.ConfigBuilder;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.test.NoSecurityConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpHeaders;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Tests for asynchronous circuit breaker.
*
* @author John Niang
*/
@SpringBootTest(classes = AsyncCircuitBreakerTest.Application.class, webEnvironment = RANDOM_PORT,
properties = "feign.circuitbreaker.enabled=true")
@AutoConfigureMockMvc
class AsyncCircuitBreakerTest {
@Autowired
MockMvc mvc;
@Test
void shouldWorkNormally() throws Exception {
mvc.perform(get("/hello/proxy")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string("openfeign"));
}
@Test
void shouldNotProxyAnyHeadersWithoutHeaderSet() throws Exception {
mvc.perform(get("/headers/" + HttpHeaders.AUTHORIZATION + "/proxy")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(""));
}
@Test
void shouldProxyHeaderWhenHeaderSet() throws Exception {
String authorization = UUID.randomUUID().toString();
mvc.perform(get("/headers/" + HttpHeaders.AUTHORIZATION + "/proxy").header(HttpHeaders.AUTHORIZATION,
authorization)).andDo(print()).andExpect(status().isOk()).andExpect(content().string(authorization));
}
@EnableAutoConfiguration
@Configuration(proxyBeanMethods = false)
@EnableFeignClients(clients = { TestClient.class })
@Import({ NoSecurityConfiguration.class, TestController.class })
static class Application {
@Bean
CircuitBreakerFactory<Duration, ConfigBuilder<Duration>> circuitBreakerFactory() {
return new CircuitBreakerFactory<Duration, ConfigBuilder<Duration>>() {
Function<String, Duration> defaultConfiguration = id -> Duration.ofMillis(1000);
@Override
public CircuitBreaker create(String id) {
Duration timeout = super.getConfigurations().computeIfAbsent(id, defaultConfiguration);
return new AsyncCircuitBreaker(timeout);
}
@Override
protected ConfigBuilder<Duration> configBuilder(String id) {
return () -> Duration.ofMillis(100);
}
@Override
public void configureDefault(Function<String, Duration> defaultConfiguration) {
this.defaultConfiguration = defaultConfiguration;
}
};
}
@Bean
RequestInterceptor proxyHeaderRequestInterceptor() {
return template -> {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
String authorization = Objects.requireNonNull(requestAttributes).getRequest()
.getHeader(HttpHeaders.AUTHORIZATION);
if (authorization != null) {
// proxy authorization header
template.header(HttpHeaders.AUTHORIZATION, authorization);
}
};
}
}
@RestController
static class TestController {
final ObjectProvider<TestClient> testClient;
TestController(ObjectProvider<TestClient> testClient) {
this.testClient = testClient;
}
@GetMapping("/hello")
String hello() {
return "openfeign";
}
@GetMapping("/hello/proxy")
String helloProxy() {
return testClient.getObject().hello();
}
@GetMapping("/headers/{headerName}")
String header(HttpServletRequest request, @PathVariable String headerName) {
return request.getHeader(headerName);
}
@GetMapping("/headers/{headerName}/proxy")
String headerProxy(@PathVariable String headerName) {
return testClient.getObject().header(headerName);
}
}
@FeignClient(name = "async-circuit-breaker-test", url = "http://localhost:${local.server.port}")
interface TestClient {
@GetMapping("/hello")
String hello();
@GetMapping("/headers/{headerName}")
String header(@PathVariable String headerName);
}
}
@@ -16,7 +16,7 @@
package org.springframework.cloud.openfeign.hateoas;
import java.util.Arrays;
import java.util.Collections;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
@@ -26,9 +26,11 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.hateoas.mediatype.MessageResolver;
import org.springframework.hateoas.mediatype.hal.CurieProvider;
import org.springframework.hateoas.mediatype.hal.HalConfiguration;
import org.springframework.hateoas.mediatype.hal.HalMediaTypeConfiguration;
import org.springframework.hateoas.mediatype.hal.Jackson2HalModule;
import org.springframework.hateoas.server.LinkRelationProvider;
import org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter;
@@ -41,24 +43,25 @@ import static org.springframework.hateoas.MediaTypes.HAL_JSON;
/**
* @author Hector Espert
* @author Olga Maciaszek-Sharma
*/
@RunWith(MockitoJUnitRunner.class)
public class FeignHalAutoConfigurationTests {
@Mock
private ObjectProvider<ObjectMapper> objectMapper;
@Mock
private ObjectProvider<HalConfiguration> halConfiguration;
@Mock
private ObjectProvider<LinkRelationProvider> relProvider;
private ObjectProvider<ObjectMapper> objectMapper;
@Mock
private LinkRelationProvider relProvider;
@Mock
private ObjectProvider<CurieProvider> curieProvider;
@Mock
private ObjectProvider<MessageResolver> messageResolver;
private MessageResolver messageResolver;
@InjectMocks
private FeignHalAutoConfiguration feignHalAutoConfiguration;
@@ -69,17 +72,17 @@ public class FeignHalAutoConfigurationTests {
when(objectMapper.getIfAvailable(any())).thenReturn(mapper);
when(halConfiguration.getIfAvailable(any())).thenReturn(mock(HalConfiguration.class));
when(relProvider.getIfAvailable()).thenReturn(mock(LinkRelationProvider.class));
when(curieProvider.getIfAvailable(any())).thenReturn(mock(CurieProvider.class));
when(messageResolver.getIfAvailable()).thenReturn(mock(MessageResolver.class));
HalMediaTypeConfiguration halMediaTypeConfiguration = new HalMediaTypeConfiguration(relProvider, curieProvider,
halConfiguration, messageResolver, new DefaultListableBeanFactory());
TypeConstrainedMappingJackson2HttpMessageConverter converter = feignHalAutoConfiguration
.halJacksonHttpMessageConverter(objectMapper, halConfiguration, messageResolver, curieProvider,
relProvider);
.halJacksonHttpMessageConverter(objectMapper, halMediaTypeConfiguration);
assertThat(converter).isNotNull();
assertThat(converter.getObjectMapper()).isNotNull();
assertThat(converter.getSupportedMediaTypes()).isEqualTo(Arrays.asList(HAL_JSON));
assertThat(converter.getSupportedMediaTypes()).isEqualTo(Collections.singletonList(HAL_JSON));
assertThat(Jackson2HalModule.isAlreadyRegisteredIn(converter.getObjectMapper())).isTrue();
}
@@ -63,7 +63,7 @@ import static org.mockito.Mockito.when;
* {@link FeignBlockingLoadBalancerClient} and its delegates.
*
* @see <a href=
* "https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/blocking/client/BlockingLoadBalancerClientTests.java">BlockingLoadBalancerClientTests</a>
* "https://github.com/spring-cloud/spring-cloud-commons/blob/main/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/blocking/client/BlockingLoadBalancerClientTests.java">BlockingLoadBalancerClientTests</a>
* @author Olga Maciaszek-Sharma
*/
@ExtendWith(MockitoExtension.class)
@@ -66,7 +66,7 @@ import static org.mockito.Mockito.when;
* {@link RetryableFeignBlockingLoadBalancerClient} and its delegates.
*
* @see <a href=
* "https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/blocking/client/BlockingLoadBalancerClientTests.java">BlockingLoadBalancerClientTests</a>
* "https://github.com/spring-cloud/spring-cloud-commons/blob/main/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/blocking/client/BlockingLoadBalancerClientTests.java">BlockingLoadBalancerClientTests</a>
* @author Olga Maciaszek-Sharma
*/
@ExtendWith(MockitoExtension.class)
@@ -0,0 +1,10 @@
# This configuration used by test class FeignClientWithRefreshableOptionsTest
logging.level.org.springframework.cloud.openfeign=debug
feign.client.default-to-properties=true
feign.client.default-config=default
feign.client.refresh-enabled=true
feign.client.config.default.connectTimeout=5000
feign.client.config.default.readTimeout=5000
feign.client.config.default.loggerLevel=full
feign.client.config.connectTimeout.connectTimeout=2000
feign.client.config.readTimeout.readTimeout=2000
+3 -3
View File
@@ -6,16 +6,16 @@
<parent>
<artifactId>spring-cloud-dependencies-parent</artifactId>
<groupId>org.springframework.cloud</groupId>
<version>3.0.2</version>
<version>3.0.3</version>
<relativePath/>
</parent>
<artifactId>spring-cloud-openfeign-dependencies</artifactId>
<version>3.0.2</version>
<version>3.0.3</version>
<packaging>pom</packaging>
<name>spring-cloud-openfeign-dependencies</name>
<description>Spring Cloud OpenFeign Dependencies</description>
<properties>
<feign.version>10.10.1</feign.version>
<feign.version>10.12</feign.version>
<feign-form.version>3.8.0</feign-form.version>
<spring-security-oauth2-autoconfigure.version>2.1.2.RELEASE</spring-security-oauth2-autoconfigure.version>
</properties>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId>
<version>3.0.2</version>
<version>3.0.3</version>
<relativePath>..</relativePath>
</parent>
<artifactId>spring-cloud-starter-openfeign</artifactId>