mirror of
https://github.com/spring-cloud/spring-cloud-netflix.git
synced 2026-09-18 16:19:18 +00:00
Compare commits
91
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
39630c11ef | ||
|
|
64bf3dfb8a | ||
|
|
69a27e8624 | ||
|
|
377cbfd297 | ||
|
|
9dea1692b4 | ||
|
|
86022d2709 | ||
|
|
04291884f5 | ||
|
|
6479c7cf2d | ||
|
|
1987e75f16 | ||
|
|
53a45b32d5 | ||
|
|
99295878f3 | ||
|
|
941980b5ce | ||
|
|
1b830d7025 | ||
|
|
3db89dab01 | ||
|
|
6e37692be9 | ||
|
|
69acb32596 | ||
|
|
5b9664e283 | ||
|
|
98dafc9e36 | ||
|
|
8314bb47a0 | ||
|
|
17692c1253 | ||
|
|
706d97f3a2 | ||
|
|
27be2ff18a | ||
|
|
afaea29441 | ||
|
|
c1886f3707 | ||
|
|
0a07ca18a2 | ||
|
|
cd9cd7be5a | ||
|
|
e8bd633d8f | ||
|
|
5fe67e7543 | ||
|
|
221eb0937c | ||
|
|
cef6996030 | ||
|
|
6c5037e646 | ||
|
|
7ba896ffa4 | ||
|
|
06dddd01d5 | ||
|
|
2b564713ba | ||
|
|
98f919c127 | ||
|
|
df9e581dc5 | ||
|
|
c2dcdacaa2 | ||
|
|
7fbf5a51de | ||
|
|
078db236b8 | ||
|
|
132cf9e4f7 | ||
|
|
ccb0f5c5a0 | ||
|
|
c0725c534e | ||
|
|
ac4d92f58d | ||
|
|
5cc8194b53 | ||
|
|
9cea0ebe23 | ||
|
|
0dca49318c | ||
|
|
fa07416bd8 | ||
|
|
06b41d5019 | ||
|
|
147d50f2c2 | ||
|
|
ded713ecc1 | ||
|
|
890f1ef4d6 | ||
|
|
25796a27f0 | ||
|
|
327b126207 | ||
|
|
58c819c76b | ||
|
|
f74977f663 | ||
|
|
e6c8caeb0f | ||
|
|
5298970764 | ||
|
|
4f3e472519 | ||
|
|
ec87f1f750 | ||
|
|
ef5817b0e6 | ||
|
|
a77a09a01f | ||
|
|
1b1612aeba | ||
|
|
2ada08039a | ||
|
|
ecdcfa4a2f | ||
|
|
a354b2a656 | ||
|
|
7335b773be | ||
|
|
6fef357742 | ||
|
|
5844550f9a | ||
|
|
23b594e5ec | ||
|
|
9f787e9a79 | ||
|
|
c44426f579 | ||
|
|
bceb01b59e | ||
|
|
daa1959a02 | ||
|
|
d34bae53c0 | ||
|
|
48b08d6fc9 | ||
|
|
a03a87636a | ||
|
|
9b4314b113 | ||
|
|
0c483e1144 | ||
|
|
cfdbda6e62 | ||
|
|
3d43fa35a4 | ||
|
|
c48f8f89cc | ||
|
|
315a3802d3 | ||
|
|
d01496ab7e | ||
|
|
f344c5807d | ||
|
|
ab59e9a08a | ||
|
|
5243e46018 | ||
|
|
b467a2f462 | ||
|
|
97ee8144be | ||
|
|
4ba8c4ae53 | ||
|
|
695787a326 | ||
|
|
e32db575b8 |
@@ -0,0 +1,32 @@
|
||||
name: Deploy Docs
|
||||
on:
|
||||
push:
|
||||
branches-ignore: [ gh-pages ]
|
||||
tags: '**'
|
||||
repository_dispatch:
|
||||
types: request-build-reference # legacy
|
||||
#schedule:
|
||||
#- cron: '0 10 * * *' # Once per day at 10am UTC
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
actions: write
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
# if: github.repository_owner == 'spring-cloud'
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
ref: docs-build
|
||||
fetch-depth: 1
|
||||
- name: Dispatch (partial build)
|
||||
if: github.ref_type == 'branch'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: gh workflow run deploy-docs.yml -r $(git rev-parse --abbrev-ref HEAD) -f build-refname=${{ github.ref_name }}
|
||||
- name: Dispatch (full build)
|
||||
if: github.ref_type == 'tag'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: gh workflow run deploy-docs.yml -r $(git rev-parse --abbrev-ref HEAD)
|
||||
+15
@@ -1,3 +1,6 @@
|
||||
/application.yml
|
||||
/application.properties
|
||||
asciidoctor.css
|
||||
*~
|
||||
#*
|
||||
*#
|
||||
@@ -5,6 +8,7 @@
|
||||
.classpath
|
||||
.project
|
||||
.settings/
|
||||
.settings
|
||||
.springBeans
|
||||
target/
|
||||
bin/
|
||||
@@ -18,5 +22,16 @@ _site/
|
||||
.shelf
|
||||
*.swp
|
||||
*.swo
|
||||
/spring-cloud-release-tools*.jar
|
||||
antrun
|
||||
.vscode/
|
||||
.flattened-pom.xml
|
||||
node
|
||||
node_modules
|
||||
build
|
||||
_configprops.adoc
|
||||
_spans.adoc
|
||||
_metrics.adoc
|
||||
_conventions.adoc
|
||||
package.json
|
||||
package-lock.json
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
17
|
||||
+2
-1
@@ -1 +1,2 @@
|
||||
-DaltSnapshotDeploymentRepository=repo.spring.io::default::https://repo.spring.io/libs-snapshot-local -P spring
|
||||
-DaltSnapshotDeploymentRepository=repo.spring.io::default::https://repo.spring.io/libs-snapshot-local
|
||||
-P spring
|
||||
|
||||
-107
@@ -1,107 +0,0 @@
|
||||
/*
|
||||
Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you 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.
|
||||
*/
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
public class MavenWrapperDownloader {
|
||||
|
||||
/**
|
||||
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
|
||||
*/
|
||||
private static final String DEFAULT_DOWNLOAD_URL =
|
||||
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar";
|
||||
|
||||
/**
|
||||
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
|
||||
* use instead of the default one.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
|
||||
".mvn/wrapper/maven-wrapper.properties";
|
||||
|
||||
/**
|
||||
* Path where the maven-wrapper.jar will be saved to.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_JAR_PATH =
|
||||
".mvn/wrapper/maven-wrapper.jar";
|
||||
|
||||
/**
|
||||
* Name of the property which should be used to override the default download url for the wrapper.
|
||||
*/
|
||||
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
|
||||
|
||||
public static void main(String args[]) {
|
||||
System.out.println("- Downloader started");
|
||||
File baseDirectory = new File(args[0]);
|
||||
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
|
||||
|
||||
// If the maven-wrapper.properties exists, read it and check if it contains a custom
|
||||
// wrapperUrl parameter.
|
||||
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
|
||||
String url = DEFAULT_DOWNLOAD_URL;
|
||||
if(mavenWrapperPropertyFile.exists()) {
|
||||
FileInputStream mavenWrapperPropertyFileInputStream = null;
|
||||
try {
|
||||
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
|
||||
Properties mavenWrapperProperties = new Properties();
|
||||
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
|
||||
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
|
||||
} catch (IOException e) {
|
||||
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
|
||||
} finally {
|
||||
try {
|
||||
if(mavenWrapperPropertyFileInputStream != null) {
|
||||
mavenWrapperPropertyFileInputStream.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Ignore ...
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading from: : " + url);
|
||||
|
||||
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
|
||||
if(!outputFile.getParentFile().exists()) {
|
||||
if(!outputFile.getParentFile().mkdirs()) {
|
||||
System.out.println(
|
||||
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
|
||||
try {
|
||||
downloadFileFromURL(url, outputFile);
|
||||
System.out.println("Done");
|
||||
System.exit(0);
|
||||
} catch (Throwable e) {
|
||||
System.out.println("- Error downloading");
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
|
||||
URL website = new URL(urlString);
|
||||
ReadableByteChannel rbc;
|
||||
rbc = Channels.newChannel(website.openStream());
|
||||
FileOutputStream fos = new FileOutputStream(destination);
|
||||
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
|
||||
fos.close();
|
||||
rbc.close();
|
||||
}
|
||||
|
||||
}
|
||||
BIN
Binary file not shown.
+18
-1
@@ -1 +1,18 @@
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.4/apache-maven-3.9.4-bin.zip
|
||||
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar
|
||||
|
||||
+10
-352
@@ -5,375 +5,33 @@ Edit the files in the src/main/asciidoc/ directory instead.
|
||||
////
|
||||
|
||||
|
||||
:doctype: book
|
||||
:idprefix:
|
||||
:idseparator: -
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:tabsize: 4
|
||||
:numbered:
|
||||
:sectanchors:
|
||||
:sectnums:
|
||||
:icons: font
|
||||
:hide-uri-scheme:
|
||||
:docinfo: shared,private
|
||||
|
||||
:sc-ext: java
|
||||
:project-full-name: Spring Cloud Netflix
|
||||
|
||||
image::https://circleci.com/gh/spring-cloud/spring-cloud-netflix/tree/main.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-netflix/tree/main"]
|
||||
image::https://codecov.io/gh/spring-cloud/spring-cloud-netflix/branch/main/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-netflix/branch/main"]
|
||||
|
||||
|
||||
:doctype: book
|
||||
:idprefix:
|
||||
:idseparator: -
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:tabsize: 4
|
||||
:numbered:
|
||||
:sectanchors:
|
||||
:sectnums:
|
||||
:icons: font
|
||||
:hide-uri-scheme:
|
||||
:docinfo: shared,private
|
||||
|
||||
:sc-ext: java
|
||||
:project-full-name: Spring Cloud Netflix
|
||||
|
||||
This project provides Netflix OSS integrations for Spring Boot apps through autoconfiguration
|
||||
and binding to the Spring Environment and other Spring programming model idioms. With a few
|
||||
simple annotations you can quickly enable and configure the common patterns inside your
|
||||
application and build large distributed systems with battle-tested Netflix components. The
|
||||
patterns provided include Service Discovery (Eureka).
|
||||
|
||||
|
||||
== Features
|
||||
[[features]]
|
||||
= Features
|
||||
|
||||
* Service Discovery: Eureka instances can be registered and clients can discover the instances using Spring-managed beans
|
||||
* Service Discovery: an embedded Eureka server can be created with declarative Java configuration
|
||||
|
||||
|
||||
== Building
|
||||
|
||||
|
||||
:jdkversion: 17
|
||||
|
||||
=== Basic Compile and Test
|
||||
|
||||
To build the source you will need to install JDK {jdkversion}.
|
||||
|
||||
Spring Cloud uses Maven for most build-related activities, and you
|
||||
should be able to get off the ground quite quickly by cloning the
|
||||
project you are interested in and typing
|
||||
|
||||
----
|
||||
$ ./mvnw install
|
||||
----
|
||||
|
||||
NOTE: You can also install Maven (>=3.3.3) yourself and run the `mvn` command
|
||||
in place of `./mvnw` in the examples below. If you do that you also
|
||||
might need to add `-P spring` if your local Maven settings do not
|
||||
contain repository declarations for spring pre-release artifacts.
|
||||
|
||||
NOTE: Be aware that you might need to increase the amount of memory
|
||||
available to Maven by setting a `MAVEN_OPTS` environment variable with
|
||||
a value like `-Xmx512m -XX:MaxPermSize=128m`. We try to cover this in
|
||||
the `.mvn` configuration, so if you find you have to do it to make a
|
||||
build succeed, please raise a ticket to get the settings added to
|
||||
source control.
|
||||
|
||||
The projects that require middleware (i.e. Redis) for testing generally
|
||||
require that a local instance of [Docker](https://www.docker.com/get-started) is installed and running.
|
||||
|
||||
|
||||
=== Documentation
|
||||
|
||||
The spring-cloud-build module has a "docs" profile, and if you switch
|
||||
that on it will try to build asciidoc sources from
|
||||
`src/main/asciidoc`. As part of that process it will look for a
|
||||
`README.adoc` and process it by loading all the includes, but not
|
||||
parsing or rendering it, just copying it to `${main.basedir}`
|
||||
(defaults to `${basedir}`, i.e. the root of the project). If there are
|
||||
any changes in the README it will then show up after a Maven build as
|
||||
a modified file in the correct place. Just commit it and push the change.
|
||||
|
||||
=== Working with the code
|
||||
If you don't have an IDE preference we would recommend that you use
|
||||
https://www.springsource.com/developer/sts[Spring Tools Suite] or
|
||||
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
|
||||
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
|
||||
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
|
||||
marketplace".
|
||||
|
||||
NOTE: Older versions of m2e do not support Maven 3.3, so once the
|
||||
projects are imported into Eclipse you will also need to tell
|
||||
m2eclipse to use the right profile for the projects. If you
|
||||
see many different errors related to the POMs in the projects, check
|
||||
that you have an up to date installation. If you can't upgrade m2e,
|
||||
add the "spring" profile to your `settings.xml`. Alternatively you can
|
||||
copy the repository settings from the "spring" profile of the parent
|
||||
pom into your `settings.xml`.
|
||||
|
||||
==== Importing into eclipse without m2eclipse
|
||||
If you prefer not to use m2eclipse you can generate eclipse project metadata using the
|
||||
following command:
|
||||
|
||||
[indent=0]
|
||||
----
|
||||
$ ./mvnw eclipse:eclipse
|
||||
----
|
||||
|
||||
The generated eclipse projects can be imported by selecting `import existing projects`
|
||||
from the `file` menu.
|
||||
|
||||
[[building]]
|
||||
= Building
|
||||
|
||||
Unresolved directive in <stdin> - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/docs/src/main/asciidoc/building-jdk8.adoc[]
|
||||
|
||||
NOTE: To build the module `spring-cloud-netflix-hystrix-contract` along with the entire Netflix project run the
|
||||
`build.sh` script in the `scripts` directory.
|
||||
|
||||
== Contributing
|
||||
[[contributing]]
|
||||
= Contributing
|
||||
|
||||
:spring-cloud-build-branch: master
|
||||
Unresolved directive in <stdin> - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/docs/src/main/asciidoc/contributing.adoc[]
|
||||
|
||||
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
|
||||
to contribute even something trivial please do not hesitate, but
|
||||
follow the guidelines below.
|
||||
|
||||
=== Sign the Contributor License Agreement
|
||||
Before we accept a non-trivial patch or pull request we will need you to sign the
|
||||
https://cla.pivotal.io/sign/spring[Contributor License Agreement].
|
||||
Signing the contributor's agreement does not grant anyone commit rights to the main
|
||||
repository, but it does mean that we can accept your contributions, and you will get an
|
||||
author credit if we do. Active contributors might be asked to join the core team, and
|
||||
given the ability to merge pull requests.
|
||||
|
||||
=== Code of Conduct
|
||||
This project adheres to the Contributor Covenant https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc[code of
|
||||
conduct]. By participating, you are expected to uphold this code. Please report
|
||||
unacceptable behavior to spring-code-of-conduct@pivotal.io.
|
||||
|
||||
=== Code Conventions and Housekeeping
|
||||
None of these is essential for a pull request, but they will all help. They can also be
|
||||
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
|
||||
https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml[Spring
|
||||
Cloud Build] project. If using IntelliJ, you can use the
|
||||
https://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter
|
||||
Plugin] 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
|
||||
for.
|
||||
* Add the ASF license header comment to all new `.java` files (copy from existing files
|
||||
in the project)
|
||||
* Add yourself as an `@author` to the .java files that you modify substantially (more
|
||||
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
|
||||
other target branch in the main project).
|
||||
* When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions],
|
||||
if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit
|
||||
message (where XXXX is the issue number).
|
||||
|
||||
=== Checkstyle
|
||||
|
||||
Spring Cloud Build comes with a set of checkstyle rules. You can find them in the `spring-cloud-build-tools` module. The most notable files under the module are:
|
||||
|
||||
.spring-cloud-build-tools/
|
||||
----
|
||||
└── src
|
||||
├── checkstyle
|
||||
│ └── checkstyle-suppressions.xml <3>
|
||||
└── main
|
||||
└── resources
|
||||
├── checkstyle-header.txt <2>
|
||||
└── checkstyle.xml <1>
|
||||
----
|
||||
<1> Default Checkstyle rules
|
||||
<2> File header setup
|
||||
<3> Default suppression rules
|
||||
|
||||
==== Checkstyle configuration
|
||||
|
||||
Checkstyle rules are *disabled by default*. To add checkstyle to your project just define the following properties and plugins.
|
||||
|
||||
.pom.xml
|
||||
----
|
||||
<properties>
|
||||
<maven-checkstyle-plugin.failsOnError>true</maven-checkstyle-plugin.failsOnError> <1>
|
||||
<maven-checkstyle-plugin.failsOnViolation>true
|
||||
</maven-checkstyle-plugin.failsOnViolation> <2>
|
||||
<maven-checkstyle-plugin.includeTestSourceDirectory>true
|
||||
</maven-checkstyle-plugin.includeTestSourceDirectory> <3>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin> <4>
|
||||
<groupId>io.spring.javaformat</groupId>
|
||||
<artifactId>spring-javaformat-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin> <5>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-checkstyle-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
<reporting>
|
||||
<plugins>
|
||||
<plugin> <5>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-checkstyle-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</reporting>
|
||||
</build>
|
||||
----
|
||||
<1> Fails the build upon Checkstyle errors
|
||||
<2> Fails the build upon Checkstyle violations
|
||||
<3> Checkstyle analyzes also the test sources
|
||||
<4> Add the Spring Java Format plugin that will reformat your code to pass most of the Checkstyle formatting rules
|
||||
<5> Add checkstyle plugin to your build and reporting phases
|
||||
|
||||
If you need to suppress some rules (e.g. line length needs to be longer), then it's enough for you to define a file under `${project.root}/src/checkstyle/checkstyle-suppressions.xml` with your suppressions. Example:
|
||||
|
||||
.projectRoot/src/checkstyle/checkstyle-suppresions.xml
|
||||
----
|
||||
<?xml version="1.0"?>
|
||||
<!DOCTYPE suppressions PUBLIC
|
||||
"-//Puppy Crawl//DTD Suppressions 1.1//EN"
|
||||
"https://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
|
||||
<suppressions>
|
||||
<suppress files=".*ConfigServerApplication\.java" checks="HideUtilityClassConstructor"/>
|
||||
<suppress files=".*ConfigClientWatch\.java" checks="LineLengthCheck"/>
|
||||
</suppressions>
|
||||
----
|
||||
|
||||
It's advisable to copy the `${spring-cloud-build.rootFolder}/.editorconfig` and `${spring-cloud-build.rootFolder}/.springformat` to your project. That way, some default formatting rules will be applied. You can do so by running this script:
|
||||
|
||||
```bash
|
||||
$ curl https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/.editorconfig -o .editorconfig
|
||||
$ touch .springformat
|
||||
```
|
||||
|
||||
=== IDE setup
|
||||
|
||||
==== Intellij IDEA
|
||||
|
||||
In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin.
|
||||
The following files can be found in the https://github.com/spring-cloud/spring-cloud-build/tree/master/spring-cloud-build-tools[Spring Cloud Build] project.
|
||||
|
||||
.spring-cloud-build-tools/
|
||||
----
|
||||
└── src
|
||||
├── checkstyle
|
||||
│ └── checkstyle-suppressions.xml <3>
|
||||
└── main
|
||||
└── resources
|
||||
├── checkstyle-header.txt <2>
|
||||
├── checkstyle.xml <1>
|
||||
└── intellij
|
||||
├── Intellij_Project_Defaults.xml <4>
|
||||
└── Intellij_Spring_Boot_Java_Conventions.xml <5>
|
||||
----
|
||||
<1> Default Checkstyle rules
|
||||
<2> File header setup
|
||||
<3> Default suppression rules
|
||||
<4> Project defaults for Intellij that apply most of Checkstyle rules
|
||||
<5> Project style conventions for Intellij that apply most of Checkstyle rules
|
||||
|
||||
.Code style
|
||||
|
||||
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-code-style.png[Code style]
|
||||
|
||||
Go to `File` -> `Settings` -> `Editor` -> `Code style`. There click on the icon next to the `Scheme` section. There, click on the `Import Scheme` value and pick the `Intellij IDEA code style XML` option. Import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml` file.
|
||||
|
||||
.Inspection profiles
|
||||
|
||||
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-inspections.png[Code style]
|
||||
|
||||
Go to `File` -> `Settings` -> `Editor` -> `Inspections`. There click on the icon next to the `Profile` section. There, click on the `Import Profile` and import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml` file.
|
||||
|
||||
.Checkstyle
|
||||
|
||||
To have Intellij work with Checkstyle, you have to install the `Checkstyle` plugin. It's advisable to also install the `Assertions2Assertj` to automatically convert the JUnit assertions
|
||||
|
||||
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-checkstyle.png[Checkstyle]
|
||||
|
||||
Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on the `+` icon in the `Configuration file` section. There, you'll have to define where the checkstyle rules should be picked from. In the image above, we've picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build's GitHub repository (e.g. for the `checkstyle.xml` : `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml`). We need to provide the following variables:
|
||||
|
||||
- `checkstyle.header.file` - please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` URL.
|
||||
- `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` URL.
|
||||
- `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`.
|
||||
|
||||
IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources.
|
||||
|
||||
=== Duplicate Finder
|
||||
|
||||
Spring Cloud Build brings along the `basepom:duplicate-finder-maven-plugin`, that enables flagging duplicate and conflicting classes and resources on the java classpath.
|
||||
|
||||
==== Duplicate Finder configuration
|
||||
|
||||
Duplicate finder is *enabled by default* and will run in the `verify` phase of your Maven build, but it will only take effect in your project if you add the `duplicate-finder-maven-plugin` to the `build` section of the projecst's `pom.xml`.
|
||||
|
||||
.pom.xml
|
||||
[source,xml]
|
||||
----
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.basepom.maven</groupId>
|
||||
<artifactId>duplicate-finder-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
----
|
||||
|
||||
For other properties, we have set defaults as listed in the https://github.com/basepom/duplicate-finder-maven-plugin/wiki[plugin documentation].
|
||||
|
||||
You can easily override them but setting the value of the selected property prefixed with `duplicate-finder-maven-plugin`. For example, set `duplicate-finder-maven-plugin.skip` to `true` in order to skip duplicates check in your build.
|
||||
|
||||
If you need to add `ignoredClassPatterns` or `ignoredResourcePatterns` to your setup, make sure to add them in the plugin configuration section of your project:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.basepom.maven</groupId>
|
||||
<artifactId>duplicate-finder-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<ignoredClassPatterns>
|
||||
<ignoredClassPattern>org.joda.time.base.BaseDateTime</ignoredClassPattern>
|
||||
<ignoredClassPattern>.*module-info</ignoredClassPattern>
|
||||
</ignoredClassPatterns>
|
||||
<ignoredResourcePatterns>
|
||||
<ignoredResourcePattern>changelog.txt</ignoredResourcePattern>
|
||||
</ignoredResourcePatterns>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
----
|
||||
|
||||
|
||||
== License
|
||||
[[license]]
|
||||
= License
|
||||
|
||||
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-netflix/main/LICENSE.txt[here].
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
antora:
|
||||
extensions:
|
||||
- '@springio/antora-extensions/partial-build-extension'
|
||||
- require: '@springio/antora-extensions/latest-version-extension'
|
||||
- require: '@springio/antora-extensions/inject-collector-cache-config-extension'
|
||||
- '@antora/collector-extension'
|
||||
- '@antora/atlas-extension'
|
||||
- require: '@springio/antora-extensions/root-component-extension'
|
||||
root_component_name: 'cloud-netflix'
|
||||
site:
|
||||
title: Spring Cloud Netflix
|
||||
url: https://docs.spring.io/spring-cloud-netflix/reference/
|
||||
content:
|
||||
sources:
|
||||
- url: ./..
|
||||
branches: HEAD
|
||||
start_path: docs
|
||||
worktrees: true
|
||||
asciidoc:
|
||||
attributes:
|
||||
page-stackoverflow-url: https://stackoverflow.com/tags/spring-cloud
|
||||
page-pagination: ''
|
||||
hide-uri-scheme: '@'
|
||||
tabs-sync-option: '@'
|
||||
chomp: 'all'
|
||||
extensions:
|
||||
- '@asciidoctor/tabs'
|
||||
- '@springio/asciidoctor-extensions'
|
||||
sourcemap: true
|
||||
urls:
|
||||
latest_version_segment: ''
|
||||
runtime:
|
||||
log:
|
||||
failure_level: warn
|
||||
format: pretty
|
||||
ui:
|
||||
bundle:
|
||||
url: https://github.com/spring-io/antora-ui-spring/releases/download/v0.3.5/ui-bundle.zip
|
||||
@@ -0,0 +1,12 @@
|
||||
name: cloud-netflix
|
||||
version: true
|
||||
title: Spring Cloud Netflix
|
||||
nav:
|
||||
- modules/ROOT/nav.adoc
|
||||
ext:
|
||||
collector:
|
||||
run:
|
||||
command: ./mvnw --no-transfer-progress -B process-resources -Pdocs -pl docs -Dantora-maven-plugin.phase=none -Dgenerate-docs.phase=none -Dgenerate-readme.phase=none -Dgenerate-cloud-resources.phase=none -Dmaven-dependency-plugin-for-docs.phase=none -Dmaven-dependency-plugin-for-docs-classes.phase=none -DskipTests
|
||||
local: true
|
||||
scan:
|
||||
dir: ./target/classes/antora-resources/
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 225 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 39 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,5 @@
|
||||
* xref:index.adoc[Introduction]
|
||||
* xref:spring-cloud-netflix.adoc[]
|
||||
* xref:appendix.adoc[]
|
||||
** xref:configprops.adoc[]
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
:doctype: book
|
||||
:idprefix:
|
||||
:idseparator: -
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:tabsize: 4
|
||||
:numbered:
|
||||
:sectanchors:
|
||||
@@ -12,4 +10,4 @@
|
||||
:docinfo: shared,private
|
||||
|
||||
:sc-ext: java
|
||||
:project-full-name: Spring Cloud Netflix
|
||||
:project-full-name: Spring Cloud Netflix
|
||||
@@ -1,14 +1,13 @@
|
||||
:numbered!:
|
||||
[appendix]
|
||||
[[common-application-properties]]
|
||||
== Common application properties
|
||||
= Common application properties
|
||||
:page-section-summary-toc: 1
|
||||
|
||||
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.
|
||||
This appendix provides a list of common Spring Cloud Netflix 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[]
|
||||
@@ -0,0 +1,6 @@
|
||||
[[configuration-properties]]
|
||||
= Configuration Properties
|
||||
|
||||
Below you can find a list of configuration properties.
|
||||
|
||||
include::partial$_configprops.adoc[]
|
||||
@@ -1,4 +1,3 @@
|
||||
include::_attributes.adoc[]
|
||||
|
||||
This project provides Netflix OSS integrations for Spring Boot apps through autoconfiguration
|
||||
and binding to the Spring Environment and other Spring programming model idioms. With a few
|
||||
+38
-31
@@ -1,20 +1,5 @@
|
||||
include::_attributes.adoc[]
|
||||
|
||||
|
||||
:github-tag: main
|
||||
:github-repo: spring-cloud/spring-cloud-netflix
|
||||
:github-raw: https://raw.github.com/{github-repo}/{github-tag}
|
||||
:github-code: https://github.com/{github-repo}/tree/{github-tag}
|
||||
:all: {asterisk}{asterisk}
|
||||
:nofooter:
|
||||
:branch: main
|
||||
|
||||
= Spring Cloud Netflix
|
||||
|
||||
*{spring-cloud-version}*
|
||||
|
||||
include::intro.adoc[]
|
||||
|
||||
[[features]]
|
||||
= Spring Cloud Netflix Features
|
||||
|
||||
== Service Discovery: Eureka Clients
|
||||
|
||||
@@ -112,6 +97,19 @@ NOTE: Because of a limitation in Eureka, it is not possible to support per-serve
|
||||
|
||||
If you want to customize the RestTemplate used by the Eureka HTTP Client you may want to create a bean of `EurekaClientHttpRequestFactorySupplier` and provide your own logic for generating a `ClientHttpRequestFactory` instance.
|
||||
|
||||
All default timeout-related properties for RestTemplate used by the Eureka HTTP Client are set to 3 minutes (in keeping with Apache HC5 default `RequestConfig` and `SocketConfig`). Therefore, to specify the timeout values, you must specify the value directly with the properties in `eureka.client.rest-template-timeout`. (All timeout properties are in milliseconds.)
|
||||
|
||||
.application.yml
|
||||
[source,yaml]
|
||||
----
|
||||
eureka:
|
||||
client:
|
||||
rest-template-timeout:
|
||||
connect-timeout: 5000
|
||||
connect-request-timeout: 8000
|
||||
socket-timeout: 10000
|
||||
----
|
||||
|
||||
=== Status Page and Health Indicator
|
||||
|
||||
The status page and health indicators for a Eureka instance default to `/info` and `/health` respectively, which are the default locations of useful endpoints in a Spring Boot Actuator application.
|
||||
@@ -366,6 +364,12 @@ it can use the domain name from the server hostname as a proxy for the zone.
|
||||
If there is no other source of zone data, then a guess is made, based on the client configuration (as opposed to the instance configuration).
|
||||
We take `eureka.client.availabilityZones`, which is a map from region name to a list of zones, and pull out the first zone for the instance's own region (that is, the `eureka.client.region`, which defaults to "us-east-1", for compatibility with native Netflix).
|
||||
|
||||
=== AOT and Native Image Support
|
||||
|
||||
Spring Cloud Netflix Eureka Client integration supports Spring AOT transformations and native images, however, only with refresh mode disabled.
|
||||
|
||||
WARNING: If you want to run Eureka Client in AOT or native image modes, make sure to set `spring.cloud.refresh.enabled` to `false`
|
||||
|
||||
[[spring-cloud-eureka-server]]
|
||||
== Service Discovery: Eureka Server
|
||||
|
||||
@@ -509,7 +513,7 @@ the registrations amongst themselves.
|
||||
If the peers are physically separated (inside a data center or between multiple data centers), then the system can, in principle, survive "`split-brain`" type failures.
|
||||
You can add multiple peers to a system, and as long as they are all
|
||||
directly connected to each other, they will synchronize
|
||||
the registrations amongst themselves.
|
||||
the registrations amongst themselves.
|
||||
|
||||
.application.yml (Three Peer Aware Eureka Servers)
|
||||
----
|
||||
@@ -517,7 +521,7 @@ eureka:
|
||||
client:
|
||||
serviceUrl:
|
||||
defaultZone: https://peer1/eureka/,http://peer2/eureka/,http://peer3/eureka/
|
||||
|
||||
|
||||
---
|
||||
spring:
|
||||
profiles: peer1
|
||||
@@ -550,33 +554,32 @@ Set `eureka.instance.preferIpAddress` to `true` and, when the application regist
|
||||
====
|
||||
If the hostname cannot be determined by Java, then the IP address is sent to Eureka.
|
||||
Only explict way of setting the hostname is by setting `eureka.instance.hostname` property.
|
||||
You can set your hostname at the run-time by using an environment variable -- for example, `eureka.instance.hostname=${HOST_NAME}`.
|
||||
You can set your hostname at the run-time by using an environment variable -- for example, `eureka.instance.hostname=$\{HOST_NAME}`.
|
||||
====
|
||||
|
||||
=== Securing The Eureka Server
|
||||
|
||||
You can secure your Eureka server simply by adding Spring Security to your
|
||||
server's classpath via `spring-boot-starter-security`. By default when Spring Security is on the classpath it will require that
|
||||
server's classpath via `spring-boot-starter-security`. By default, when Spring Security is on the classpath it will require that
|
||||
a valid CSRF token be sent with every request to the app. Eureka clients will not generally possess a valid
|
||||
cross site request forgery (CSRF) token you will need to disable this requirement for the `/eureka/**` endpoints.
|
||||
For example:
|
||||
For example:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@EnableWebSecurity
|
||||
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.csrf().ignoringAntMatchers("/eureka/**");
|
||||
super.configure(http);
|
||||
}
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http.authorizeHttpRequests((authz) -> authz
|
||||
.anyRequest().authenticated())
|
||||
.httpBasic(withDefaults());
|
||||
http.csrf().ignoringRequestMatchers("/eureka/**");
|
||||
return http.build();
|
||||
}
|
||||
----
|
||||
|
||||
For more information on CSRF see the https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#csrf[Spring Security documentation].
|
||||
|
||||
A demo Eureka Server can be found in the Spring Cloud Samples https://github.com/spring-cloud-samples/eureka/tree/Eureka-With-Security[repo].
|
||||
A demo Eureka Server can be found in the Spring Cloud Samples https://github.com/spring-cloud-samples/eureka/tree/Eureka-With-Security-4.x[repo].
|
||||
|
||||
=== JDK 11 Support
|
||||
|
||||
@@ -591,6 +594,10 @@ when running a Eureka server you must include these dependencies in your POM or
|
||||
</dependency>
|
||||
----
|
||||
|
||||
=== AOT and Native Image Support
|
||||
|
||||
Spring Cloud Netflix Eureka Server does not support Spring AOT transformations or native images.
|
||||
|
||||
== Configuration properties
|
||||
|
||||
To see the list of all Spring Cloud Netflix related configuration properties please check link:appendix.html[the Appendix page].
|
||||
+23
-11
@@ -1,23 +1,26 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-netflix-docs</artifactId>
|
||||
<parent>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-netflix</artifactId>
|
||||
<version>4.0.0-SNAPSHOT</version>
|
||||
<version>4.1.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath>
|
||||
</parent>
|
||||
<artifactId>spring-cloud-netflix-docs</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<name>Spring Cloud Netflix Docs</name>
|
||||
<description>Spring Cloud Docs</description>
|
||||
<description>Spring Cloud Netflix Docs</description>
|
||||
<properties>
|
||||
<docs.main>spring-cloud-netflix</docs.main>
|
||||
<main.basedir>${basedir}/..</main.basedir>
|
||||
<configprops.inclusionPattern>
|
||||
.*.eureka.*
|
||||
</configprops.inclusionPattern>
|
||||
<upload-docs-zip.phase>deploy</upload-docs-zip.phase>
|
||||
<configprops.inclusionPattern>spring.cloud.*</configprops.inclusionPattern>
|
||||
<!-- Don't upload docs jar to central / repo.spring.io -->
|
||||
<maven-deploy-plugin-default.phase>none</maven-deploy-plugin-default.phase>
|
||||
</properties>
|
||||
@@ -38,26 +41,35 @@
|
||||
<profile>
|
||||
<id>docs</id>
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/antora/resources/antora-resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>pl.project13.maven</groupId>
|
||||
<artifactId>git-commit-id-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.asciidoctor</groupId>
|
||||
<artifactId>asciidoctor-maven-plugin</artifactId>
|
||||
<groupId>io.spring.maven.antora</groupId>
|
||||
<artifactId>antora-component-version-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>io.spring.maven.antora</groupId>
|
||||
<artifactId>antora-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
version: @antora-component.version@
|
||||
prerelease: @antora-component.prerelease@
|
||||
|
||||
asciidoc:
|
||||
attributes:
|
||||
attribute-missing: 'warn'
|
||||
chomp: 'all'
|
||||
project-root: @maven.multiModuleProjectDirectory@
|
||||
github-repo: @docs.main@
|
||||
github-raw: https://raw.githubusercontent.com/spring-cloud/@docs.main@/@github-tag@
|
||||
github-code: https://github.com/spring-cloud/@docs.main@/tree/@github-tag@
|
||||
github-issues: https://github.com/spring-cloud/@docs.main@/issues/
|
||||
github-wiki: https://github.com/spring-cloud/@docs.main@/wiki
|
||||
spring-cloud-version: @project.version@
|
||||
github-tag: @github-tag@
|
||||
version-type: @version-type@
|
||||
docs-url: https://docs.spring.io/@docs.main@/docs/@project.version@
|
||||
raw-docs-url: https://raw.githubusercontent.com/spring-cloud/@docs.main@/@github-tag@
|
||||
project-version: @project.version@
|
||||
project-name: @docs.main@
|
||||
@@ -1,28 +1,30 @@
|
||||
include::_attributes.adoc[]
|
||||
|
||||
image::https://circleci.com/gh/spring-cloud/spring-cloud-netflix/tree/main.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-netflix/tree/main"]
|
||||
image::https://codecov.io/gh/spring-cloud/spring-cloud-netflix/branch/main/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-netflix/branch/main"]
|
||||
|
||||
|
||||
include::intro.adoc[]
|
||||
|
||||
== Features
|
||||
[[features]]
|
||||
= Features
|
||||
|
||||
* Service Discovery: Eureka instances can be registered and clients can discover the instances using Spring-managed beans
|
||||
* Service Discovery: an embedded Eureka server can be created with declarative Java configuration
|
||||
|
||||
|
||||
== Building
|
||||
[[building]]
|
||||
= Building
|
||||
|
||||
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/docs/src/main/asciidoc/building-jdk8.adoc[]
|
||||
|
||||
NOTE: To build the module `spring-cloud-netflix-hystrix-contract` along with the entire Netflix project run the
|
||||
`build.sh` script in the `scripts` directory.
|
||||
|
||||
== Contributing
|
||||
[[contributing]]
|
||||
= Contributing
|
||||
|
||||
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/docs/src/main/asciidoc/contributing.adoc[]
|
||||
|
||||
== License
|
||||
[[license]]
|
||||
= License
|
||||
|
||||
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-netflix/main/LICENSE.txt[here].
|
||||
The project license file is available https://raw.githubusercontent.com/spring-cloud/spring-cloud-netflix/main/LICENSE.txt[here].
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
|===
|
||||
|Name | Default | Description
|
||||
|
||||
|eureka.client.eureka-connection-idle-timeout-seconds | `+++30+++` | Indicates how much time (in seconds) that the HTTP connections to eureka server can stay idle before it can be closed. In the AWS environment, it is recommended that the values is 30 seconds or less, since the firewall cleans up the connection information after a few mins leaving the connection hanging in limbo.
|
||||
|eureka.client.eureka-server-connect-timeout-seconds | `+++5+++` | Indicates how long to wait (in seconds) before a connection to eureka server needs to timeout. Note that the connections in the client are pooled by org.apache.http.client.HttpClient and this setting affects the actual connection creation and also the wait time to get the connection from the pool.
|
||||
|eureka.client.eureka-server-d-n-s-name | | Gets the DNS name to be queried to get the list of eureka servers.This information is not required if the contract returns the service urls by implementing serviceUrls. The DNS mechanism is used when useDnsForFetchingServiceUrls is set to true and the eureka client expects the DNS to configured a certain way so that it can fetch changing eureka servers dynamically. The changes are effective at runtime.
|
||||
|eureka.client.eureka-server-port | | Gets the port to be used to construct the service url to contact eureka server when the list of eureka servers come from the DNS.This information is not required if the contract returns the service urls eurekaServerServiceUrls(String). The DNS mechanism is used when useDnsForFetchingServiceUrls is set to true and the eureka client expects the DNS to configured a certain way so that it can fetch changing eureka servers dynamically. The changes are effective at runtime.
|
||||
|eureka.client.eureka-server-read-timeout-seconds | `+++8+++` | Indicates how long to wait (in seconds) before a read from eureka server needs to timeout.
|
||||
|eureka.client.eureka-server-total-connections | `+++200+++` | Gets the total number of connections that is allowed from eureka client to all eureka servers.
|
||||
|eureka.client.eureka-server-total-connections-per-host | `+++50+++` | Gets the total number of connections that is allowed from eureka client to a eureka server host.
|
||||
|eureka.client.eureka-server-u-r-l-context | | Gets the URL context to be used to construct the service url to contact eureka server when the list of eureka servers come from the DNS. This information is not required if the contract returns the service urls from eurekaServerServiceUrls. The DNS mechanism is used when useDnsForFetchingServiceUrls is set to true and the eureka client expects the DNS to configured a certain way so that it can fetch changing eureka servers dynamically. The changes are effective at runtime.
|
||||
|eureka.client.eureka-service-url-poll-interval-seconds | `+++0+++` | Indicates how often(in seconds) to poll for changes to eureka server information. Eureka servers could be added or removed and this setting controls how soon the eureka clients should know about it.
|
||||
|eureka.client.prefer-same-zone-eureka | `+++true+++` | Indicates whether or not this instance should try to use the eureka server in the same zone for latency and/or other reason. Ideally eureka clients are configured to talk to servers in the same zone The changes are effective at runtime at the next registry fetch cycle as specified by registryFetchIntervalSeconds
|
||||
|eureka.client.register-with-eureka | `+++true+++` | Indicates whether or not this instance should register its information with eureka server for discovery by others. In some cases, you do not want your instances to be discovered whereas you just want do discover other instances.
|
||||
|eureka.server.peer-eureka-nodes-update-interval-ms | `+++0+++` |
|
||||
|eureka.server.peer-eureka-status-refresh-time-interval-ms | `+++0+++` |
|
||||
|ribbon.eureka.enabled | `+++true+++` | Enables the use of Eureka with Ribbon.
|
||||
|spring.cloud.loadbalancer.eureka.approximate-zone-from-hostname | `+++false+++` | Used to determine whether we should try to get the `zone` value from host name.
|
||||
|
||||
|===
|
||||
@@ -8,7 +8,7 @@
|
||||
# "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
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
@@ -19,7 +19,7 @@
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven2 Start Up Batch script
|
||||
# Apache Maven Wrapper startup batch script, version 3.2.0
|
||||
#
|
||||
# Required ENV vars:
|
||||
# ------------------
|
||||
@@ -27,7 +27,6 @@
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# M2_HOME - location of maven2's installed home dir
|
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
# e.g. to debug Maven itself, use
|
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@@ -36,6 +35,10 @@
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
|
||||
if [ -f /usr/local/etc/mavenrc ] ; then
|
||||
. /usr/local/etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
@@ -50,7 +53,7 @@ fi
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
case "$(uname)" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
@@ -58,9 +61,9 @@ case "`uname`" in
|
||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
if [ -x "/usr/libexec/java_home" ]; then
|
||||
export JAVA_HOME="`/usr/libexec/java_home`"
|
||||
JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME
|
||||
else
|
||||
export JAVA_HOME="/Library/Java/Home"
|
||||
JAVA_HOME="/Library/Java/Home"; export JAVA_HOME
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
@@ -68,69 +71,38 @@ esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
JAVA_HOME=$(java-config --jre-home)
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG="`dirname "$PRG"`/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
saveddir=`pwd`
|
||||
|
||||
M2_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
||||
|
||||
cd "$saveddir"
|
||||
# echo Using m2 at $M2_HOME
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
||||
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
|
||||
fi
|
||||
|
||||
# For Mingw, ensure paths are in UNIX format before anything is touched
|
||||
if $mingw ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
||||
# TODO classpath?
|
||||
[ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)"
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
javaExecutable="`which javac`"
|
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
||||
javaExecutable="$(which javac)"
|
||||
if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then
|
||||
# readlink(1) is not available as standard on Solaris 10.
|
||||
readLink=`which readlink`
|
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
||||
readLink=$(which readlink)
|
||||
if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
javaHome="$(dirname "\"$javaExecutable\"")"
|
||||
javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
javaExecutable="$(readlink -f "\"$javaExecutable\"")"
|
||||
fi
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
||||
javaHome="$(dirname "\"$javaExecutable\"")"
|
||||
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
|
||||
JAVA_HOME="$javaHome"
|
||||
export JAVA_HOME
|
||||
fi
|
||||
@@ -146,7 +118,7 @@ if [ -z "$JAVACMD" ] ; then
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
else
|
||||
JAVACMD="`which java`"
|
||||
JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)"
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -160,12 +132,9 @@ if [ -z "$JAVA_HOME" ] ; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||
|
||||
# traverses directory structure from process work directory to filesystem root
|
||||
# first directory with .mvn subdirectory is considered project base directory
|
||||
find_maven_basedir() {
|
||||
|
||||
if [ -z "$1" ]
|
||||
then
|
||||
echo "Path not specified to find_maven_basedir"
|
||||
@@ -181,76 +150,99 @@ find_maven_basedir() {
|
||||
fi
|
||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
||||
if [ -d "${wdir}" ]; then
|
||||
wdir=`cd "$wdir/.."; pwd`
|
||||
wdir=$(cd "$wdir/.." || exit 1; pwd)
|
||||
fi
|
||||
# end of workaround
|
||||
done
|
||||
echo "${basedir}"
|
||||
printf '%s' "$(cd "$basedir" || exit 1; pwd)"
|
||||
}
|
||||
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
# Remove \r in case we run on Windows within Git Bash
|
||||
# and check out the repository with auto CRLF management
|
||||
# enabled. Otherwise, we may read lines that are delimited with
|
||||
# \r\n and produce $'-Xarg\r' rather than -Xarg due to word
|
||||
# splitting rules.
|
||||
tr -s '\r\n' ' ' < "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
BASE_DIR=`find_maven_basedir "$(pwd)"`
|
||||
log() {
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
printf '%s\n' "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
BASE_DIR=$(find_maven_basedir "$(dirname "$0")")
|
||||
if [ -z "$BASE_DIR" ]; then
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR
|
||||
log "$MAVEN_PROJECTBASEDIR"
|
||||
|
||||
##########################################################################################
|
||||
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
# This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
##########################################################################################
|
||||
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found .mvn/wrapper/maven-wrapper.jar"
|
||||
fi
|
||||
wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar"
|
||||
if [ -r "$wrapperJarPath" ]; then
|
||||
log "Found $wrapperJarPath"
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
|
||||
log "Couldn't find $wrapperJarPath, downloading it ..."
|
||||
|
||||
if [ -n "$MVNW_REPOURL" ]; then
|
||||
wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
|
||||
else
|
||||
wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
|
||||
fi
|
||||
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar"
|
||||
while IFS="=" read key value; do
|
||||
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
|
||||
while IFS="=" read -r key value; do
|
||||
# Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' )
|
||||
safeValue=$(echo "$value" | tr -d '\r')
|
||||
case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;;
|
||||
esac
|
||||
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Downloading from: $jarUrl"
|
||||
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
|
||||
log "Downloading from: $wrapperUrl"
|
||||
|
||||
if $cygwin; then
|
||||
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
|
||||
fi
|
||||
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
|
||||
|
||||
if command -v wget > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found wget ... using wget"
|
||||
log "Found wget ... using wget"
|
||||
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet"
|
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||
wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
|
||||
else
|
||||
wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
|
||||
fi
|
||||
wget "$jarUrl" -O "$wrapperJarPath"
|
||||
elif command -v curl > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found curl ... using curl"
|
||||
log "Found curl ... using curl"
|
||||
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent"
|
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||
curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
|
||||
else
|
||||
curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
|
||||
fi
|
||||
curl -o "$wrapperJarPath" "$jarUrl"
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Falling back to using Java to download"
|
||||
log "Falling back to using Java to download"
|
||||
javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java"
|
||||
javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class"
|
||||
# For Cygwin, switch paths to Windows format before running javac
|
||||
if $cygwin; then
|
||||
javaSource=$(cygpath --path --windows "$javaSource")
|
||||
javaClass=$(cygpath --path --windows "$javaClass")
|
||||
fi
|
||||
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
|
||||
if [ -e "$javaClass" ]; then
|
||||
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Compiling MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
# Compiling the Java class
|
||||
("$JAVA_HOME/bin/javac" "$javaClass")
|
||||
if [ -e "$javaSource" ]; then
|
||||
if [ ! -e "$javaClass" ]; then
|
||||
log " - Compiling MavenWrapperDownloader.java ..."
|
||||
("$JAVA_HOME/bin/javac" "$javaSource")
|
||||
fi
|
||||
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
# Running the downloader
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Running MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
|
||||
if [ -e "$javaClass" ]; then
|
||||
log " - Running MavenWrapperDownloader.java ..."
|
||||
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
@@ -259,48 +251,58 @@ fi
|
||||
# End of extension
|
||||
##########################################################################################
|
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo $MAVEN_PROJECTBASEDIR
|
||||
# If specified, validate the SHA-256 sum of the Maven wrapper jar file
|
||||
wrapperSha256Sum=""
|
||||
while IFS="=" read -r key value; do
|
||||
case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;;
|
||||
esac
|
||||
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
|
||||
if [ -n "$wrapperSha256Sum" ]; then
|
||||
wrapperSha256Result=false
|
||||
if command -v sha256sum > /dev/null; then
|
||||
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then
|
||||
wrapperSha256Result=true
|
||||
fi
|
||||
elif command -v shasum > /dev/null; then
|
||||
if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then
|
||||
wrapperSha256Result=true
|
||||
fi
|
||||
else
|
||||
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available."
|
||||
echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties."
|
||||
exit 1
|
||||
fi
|
||||
if [ $wrapperSha256Result = false ]; then
|
||||
echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2
|
||||
echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2
|
||||
echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
||||
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
||||
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
|
||||
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
|
||||
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
|
||||
MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
|
||||
fi
|
||||
|
||||
# Provide a "standardized" way to retrieve the CLI args that will
|
||||
# work with both Windows and non-Windows executions.
|
||||
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*"
|
||||
export MAVEN_CMD_LINE_ARGS
|
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
echo "Running version check"
|
||||
VERSION=$( sed '\!<parent!,\!</parent!d' `dirname $0`/pom.xml | grep '<version' | head -1 | sed -e 's/.*<version>//' -e 's!</version>.*$!!' )
|
||||
echo "The found version is [${VERSION}]"
|
||||
|
||||
if echo $VERSION | egrep -q 'M|RC'; then
|
||||
echo Activating \"milestone\" profile for version=\"$VERSION\"
|
||||
echo $MAVEN_CONFIG | grep -q milestone || MAVEN_CONFIG="$MAVEN_CONFIG -Pmilestone"
|
||||
else
|
||||
echo Deactivating \"milestone\" profile for version=\"$VERSION\"
|
||||
echo $MAVEN_CONFIG | grep -q milestone && MAVEN_CONFIG=$(echo $MAVEN_CONFIG | sed -e 's/-Pmilestone//')
|
||||
fi
|
||||
|
||||
if echo $VERSION | egrep -q 'RELEASE'; then
|
||||
echo Activating \"central\" profile for version=\"$VERSION\"
|
||||
echo $MAVEN_CONFIG | grep -q milestone || MAVEN_CONFIG="$MAVEN_CONFIG -Pcentral"
|
||||
else
|
||||
echo Deactivating \"central\" profile for version=\"$VERSION\"
|
||||
echo $MAVEN_CONFIG | grep -q central && MAVEN_CONFIG=$(echo $MAVEN_CONFIG | sed -e 's/-Pcentral//')
|
||||
fi
|
||||
|
||||
# shellcheck disable=SC2086 # safe args
|
||||
exec "$JAVACMD" \
|
||||
$MAVEN_OPTS \
|
||||
$MAVEN_DEBUG_OPTS \
|
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM https://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@@ -18,15 +18,14 @@
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Maven2 Start Up Batch script
|
||||
@REM Apache Maven Wrapper startup batch script, version 3.2.0
|
||||
@REM
|
||||
@REM Required ENV vars:
|
||||
@REM JAVA_HOME - location of a JDK home dir
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM M2_HOME - location of maven2's installed home dir
|
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
|
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
@REM e.g. to debug Maven itself, use
|
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@@ -37,7 +36,7 @@
|
||||
@echo off
|
||||
@REM set title of command window
|
||||
title %0
|
||||
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
|
||||
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
|
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||
|
||||
@REM set %HOME% to equivalent of $HOME
|
||||
@@ -46,8 +45,8 @@ if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||
@REM Execute a user defined script before this one
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
|
||||
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
|
||||
:skipRcPre
|
||||
|
||||
@setlocal
|
||||
@@ -120,24 +119,69 @@ SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar"
|
||||
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
|
||||
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
|
||||
set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
|
||||
|
||||
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
|
||||
IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B
|
||||
)
|
||||
|
||||
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
if exist %WRAPPER_JAR% (
|
||||
echo Found %WRAPPER_JAR%
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Found %WRAPPER_JAR%
|
||||
)
|
||||
) else (
|
||||
echo Couldn't find %WRAPPER_JAR%, downloading it ...
|
||||
echo Downloading from: %DOWNLOAD_URL%
|
||||
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
|
||||
echo Finished downloading %WRAPPER_JAR%
|
||||
if not "%MVNW_REPOURL%" == "" (
|
||||
SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
|
||||
)
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Couldn't find %WRAPPER_JAR%, downloading it ...
|
||||
echo Downloading from: %WRAPPER_URL%
|
||||
)
|
||||
|
||||
powershell -Command "&{"^
|
||||
"$webclient = new-object System.Net.WebClient;"^
|
||||
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
|
||||
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
|
||||
"}"^
|
||||
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
|
||||
"}"
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Finished downloading %WRAPPER_JAR%
|
||||
)
|
||||
)
|
||||
@REM End of extension
|
||||
|
||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
||||
@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file
|
||||
SET WRAPPER_SHA_256_SUM=""
|
||||
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
|
||||
IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B
|
||||
)
|
||||
IF NOT %WRAPPER_SHA_256_SUM%=="" (
|
||||
powershell -Command "&{"^
|
||||
"$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^
|
||||
"If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^
|
||||
" Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^
|
||||
" Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^
|
||||
" Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^
|
||||
" exit 1;"^
|
||||
"}"^
|
||||
"}"
|
||||
if ERRORLEVEL 1 goto error
|
||||
)
|
||||
|
||||
@REM Provide a "standardized" way to retrieve the CLI args that will
|
||||
@REM work with both Windows and non-Windows executions.
|
||||
set MAVEN_CMD_LINE_ARGS=%*
|
||||
|
||||
%MAVEN_JAVA_EXE% ^
|
||||
%JVM_CONFIG_MAVEN_PROPS% ^
|
||||
%MAVEN_OPTS% ^
|
||||
%MAVEN_DEBUG_OPTS% ^
|
||||
-classpath %WRAPPER_JAR% ^
|
||||
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
|
||||
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
||||
if ERRORLEVEL 1 goto error
|
||||
goto end
|
||||
|
||||
@@ -147,15 +191,15 @@ set ERROR_CODE=1
|
||||
:end
|
||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
|
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
|
||||
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
|
||||
:skipRcPost
|
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||
if "%MAVEN_BATCH_PAUSE%"=="on" pause
|
||||
|
||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
|
||||
|
||||
exit /B %ERROR_CODE%
|
||||
cmd /C exit /B %ERROR_CODE%
|
||||
|
||||
@@ -3,14 +3,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-netflix</artifactId>
|
||||
<version>4.0.0-SNAPSHOT</version>
|
||||
<version>4.1.0-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>Spring Cloud Netflix</name>
|
||||
<description>Spring Cloud Netflix</description>
|
||||
<parent>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-build</artifactId>
|
||||
<version>4.0.0-SNAPSHOT</version>
|
||||
<version>4.1.0-SNAPSHOT</version>
|
||||
<relativePath />
|
||||
</parent>
|
||||
<scm>
|
||||
@@ -21,8 +21,10 @@
|
||||
</scm>
|
||||
<properties>
|
||||
<bintray.package>netflix</bintray.package>
|
||||
<spring-cloud-commons.version>4.0.0-SNAPSHOT</spring-cloud-commons.version>
|
||||
<spring-cloud-config.version>4.0.0-SNAPSHOT</spring-cloud-config.version>
|
||||
<spring-cloud-commons.version>4.1.0-SNAPSHOT</spring-cloud-commons.version>
|
||||
<spring-cloud-config.version>4.1.0-SNAPSHOT</spring-cloud-config.version>
|
||||
<testcontainers.version>1.17.6</testcontainers.version>
|
||||
<mockserverclient.version>5.15.0</mockserverclient.version>
|
||||
|
||||
<!-- Sonar -->
|
||||
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
|
||||
@@ -115,6 +117,22 @@
|
||||
</dependency>
|
||||
<!-- Eureka core dep that is now optional -->
|
||||
<!-- end eureka deps -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>mockserver</artifactId>
|
||||
<version>${testcontainers.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${testcontainers.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mock-server</groupId>
|
||||
<artifactId>mockserver-client-java</artifactId>
|
||||
<version>${mockserverclient.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
<reporting>
|
||||
@@ -165,23 +183,6 @@
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<!-- FIXME: 4.0 -->
|
||||
<repository>
|
||||
<id>netflix-snapshots</id>
|
||||
<name>Netflix Snapshots</name>
|
||||
<url>https://artifactory-oss.prod.netflix.net/artifactory/maven-oss-snapshots</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>netflix-candidates</id>
|
||||
<name>Netflix Candidates</name>
|
||||
<url>https://artifactory-oss.prod.netflix.net/artifactory/maven-oss-candidates</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
|
||||
@@ -5,16 +5,16 @@
|
||||
<parent>
|
||||
<artifactId>spring-cloud-dependencies-parent</artifactId>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<version>4.0.0-SNAPSHOT</version>
|
||||
<version>4.1.0-SNAPSHOT</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
<artifactId>spring-cloud-netflix-dependencies</artifactId>
|
||||
<version>4.0.0-SNAPSHOT</version>
|
||||
<version>4.1.0-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>spring-cloud-netflix-dependencies</name>
|
||||
<description>Spring Cloud Netflix Dependencies</description>
|
||||
<properties>
|
||||
<eureka.version>2.0.0-rc.3</eureka.version>
|
||||
<eureka.version>2.0.1</eureka.version>
|
||||
</properties>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
@@ -67,6 +67,10 @@
|
||||
<groupId>com.google.code.findbugs</groupId>
|
||||
<artifactId>annotations</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.glassfish.jersey.core</groupId>
|
||||
<artifactId>jersey-client</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -120,7 +124,6 @@
|
||||
<dependency>
|
||||
<groupId>com.netflix.eureka</groupId>
|
||||
<artifactId>eureka-client-jersey3</artifactId>
|
||||
<!-- FIXME: 4.0 -->
|
||||
<version>${eureka.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-netflix</artifactId>
|
||||
<version>4.0.0-SNAPSHOT</version>
|
||||
<version>4.1.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<artifactId>spring-cloud-netflix-eureka-client-tls-tests</artifactId>
|
||||
@@ -120,6 +120,12 @@
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
||||
+2
-2
@@ -28,9 +28,9 @@ import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
public class AppRunner implements AutoCloseable {
|
||||
|
||||
private Class<?> appClass;
|
||||
private final Class<?> appClass;
|
||||
|
||||
private Map<String, String> props;
|
||||
private final Map<String, String> props;
|
||||
|
||||
private ConfigurableApplicationContext app;
|
||||
|
||||
|
||||
+5
-7
@@ -56,6 +56,7 @@ abstract class BaseCertTest {
|
||||
protected BaseCertTest() {
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
static EurekaServerRunner startEurekaServer(Class config) {
|
||||
EurekaServerRunner server = new EurekaServerRunner(config);
|
||||
server.enableTls();
|
||||
@@ -70,6 +71,7 @@ abstract class BaseCertTest {
|
||||
server.stop();
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
static EurekaClientRunner startService(EurekaServerRunner server, Class config) {
|
||||
EurekaClientRunner service = new EurekaClientRunner(config, server, "testservice");
|
||||
enableTlsClient(service);
|
||||
@@ -153,9 +155,7 @@ abstract class BaseCertTest {
|
||||
EurekaClientRunner client = createEurekaClient();
|
||||
enableTlsClient(client);
|
||||
client.setKeyStore(clientCert, WRONG_PASSWORD, WRONG_PASSWORD);
|
||||
Assertions.assertThrows(BeanCreationException.class, () -> {
|
||||
client.start();
|
||||
});
|
||||
Assertions.assertThrows(BeanCreationException.class, client::start);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -163,9 +163,7 @@ abstract class BaseCertTest {
|
||||
EurekaClientRunner client = createEurekaClient();
|
||||
enableTlsClient(client);
|
||||
client.setKeyStore(new File("nonExistFile"));
|
||||
Assertions.assertThrows(BeanCreationException.class, () -> {
|
||||
client.start();
|
||||
});
|
||||
Assertions.assertThrows(BeanCreationException.class, client::start);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -183,7 +181,7 @@ abstract class BaseCertTest {
|
||||
}
|
||||
|
||||
private static File saveCert(KeyAndCert keyCert) throws Exception {
|
||||
return saveKeyStore(keyCert.subject(), () -> keyCert.storeCert());
|
||||
return saveKeyStore(keyCert.subject(), keyCert::storeCert);
|
||||
}
|
||||
|
||||
private static File saveKeyStore(String prefix, KeyStoreSupplier func) throws Exception {
|
||||
|
||||
+4
-3
@@ -72,13 +72,13 @@ public class EurekaClientRunner extends AppRunner {
|
||||
}
|
||||
|
||||
public void waitServiceViaEureka(int seconds) {
|
||||
assertInSeconds(() -> foundServiceViaEureka(), seconds);
|
||||
assertInSeconds(this::foundServiceViaEureka, seconds);
|
||||
}
|
||||
|
||||
private void assertInSeconds(BooleanSupplier assertion, int seconds) {
|
||||
long start = System.currentTimeMillis();
|
||||
long limit = 1000L * seconds;
|
||||
long duration = 0;
|
||||
long duration;
|
||||
|
||||
do {
|
||||
if (assertion.getAsBoolean()) {
|
||||
@@ -98,8 +98,9 @@ public class EurekaClientRunner extends AppRunner {
|
||||
return !discovery.getServices().isEmpty();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public AbstractDiscoveryClientOptionalArgs<Void> discoveryClientOptionalArgs() {
|
||||
return this.getBean(AbstractDiscoveryClientOptionalArgs.class);
|
||||
return getBean(AbstractDiscoveryClientOptionalArgs.class);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+4
-4
@@ -22,8 +22,11 @@ import org.junit.jupiter.api.BeforeAll;
|
||||
|
||||
import org.springframework.boot.SpringBootConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClientOptionalArgs;
|
||||
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class EurekaClientTest extends BaseCertTest {
|
||||
|
||||
private static final Log log = LogFactory.getLog(EurekaClientTest.class);
|
||||
@@ -36,10 +39,7 @@ public class EurekaClientTest extends BaseCertTest {
|
||||
public static void setupAll() {
|
||||
server = startEurekaServer(EurekaClientTest.TestEurekaServer.class);
|
||||
service = startService(server, EurekaClientTest.TestApp.class);
|
||||
// Will use Jersey
|
||||
// FIXME: 4.0
|
||||
// assertThat(service.discoveryClientOptionalArgs())
|
||||
// .isInstanceOf(DiscoveryClient.DiscoveryClientOptionalArgs.class);
|
||||
assertThat(service.discoveryClientOptionalArgs()).isInstanceOf(RestTemplateDiscoveryClientOptionalArgs.class);
|
||||
log.info("Successfully asserted that Jersey will be used");
|
||||
waitForRegistration(() -> new EurekaClientTest().createEurekaClient());
|
||||
}
|
||||
|
||||
+3
-3
@@ -25,9 +25,9 @@ import java.security.cert.X509Certificate;
|
||||
|
||||
public class KeyAndCert {
|
||||
|
||||
private KeyPair keyPair;
|
||||
private final KeyPair keyPair;
|
||||
|
||||
private X509Certificate certificate;
|
||||
private final X509Certificate certificate;
|
||||
|
||||
public KeyAndCert(KeyPair keyPair, X509Certificate certificate) {
|
||||
this.keyPair = keyPair;
|
||||
@@ -51,7 +51,7 @@ public class KeyAndCert {
|
||||
}
|
||||
|
||||
public String subject() {
|
||||
String dn = certificate.getSubjectDN().getName();
|
||||
String dn = certificate.getSubjectX500Principal().getName();
|
||||
int index = dn.indexOf('=');
|
||||
return dn.substring(index + 1);
|
||||
}
|
||||
|
||||
+1
-3
@@ -56,9 +56,7 @@ public class KeyTool {
|
||||
|
||||
public KeyAndCert signCertificate(KeyPair keyPair, String subject, KeyAndCert signer) throws Exception {
|
||||
X509Certificate certificate = createCert(keyPair.getPublic(), signer.privateKey(), signer.subject(), subject);
|
||||
KeyAndCert result = new KeyAndCert(keyPair, certificate);
|
||||
|
||||
return result;
|
||||
return new KeyAndCert(keyPair, certificate);
|
||||
}
|
||||
|
||||
public KeyPair createKeyPair() throws Exception {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
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>
|
||||
<parent>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-netflix</artifactId>
|
||||
<version>4.0.0-SNAPSHOT</version>
|
||||
<version>4.1.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<artifactId>spring-cloud-netflix-eureka-client</artifactId>
|
||||
@@ -14,7 +15,7 @@
|
||||
<description>Spring Cloud Netflix Eureka Client</description>
|
||||
<properties>
|
||||
<!-- Why do I need this now? -->
|
||||
<maven.javadoc.failOnError>false</maven.javadoc.failOnError>
|
||||
<maven.javadoc.failOnError>false</maven.javadoc.failOnError>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
@@ -67,6 +68,10 @@
|
||||
<artifactId>spring-boot-autoconfigure-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents.client5</groupId>
|
||||
<artifactId>httpclient5</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
@@ -103,5 +108,20 @@
|
||||
<artifactId>reactor-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>mockserver</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mock-server</groupId>
|
||||
<artifactId>mockserver-client-java</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
||||
+10
-8
@@ -28,6 +28,7 @@ import com.netflix.discovery.DiscoveryClient;
|
||||
import com.netflix.discovery.EurekaClientConfig;
|
||||
import com.netflix.discovery.shared.transport.EurekaHttpClient;
|
||||
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
|
||||
import com.netflix.discovery.shared.transport.jersey.TransportClientFactories;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
@@ -48,22 +49,23 @@ public class CloudEurekaClient extends DiscoveryClient {
|
||||
|
||||
private final AtomicLong cacheRefreshedCount = new AtomicLong(0);
|
||||
|
||||
private ApplicationEventPublisher publisher;
|
||||
private final ApplicationEventPublisher publisher;
|
||||
|
||||
private Field eurekaTransportField;
|
||||
private final Field eurekaTransportField;
|
||||
|
||||
private ApplicationInfoManager applicationInfoManager;
|
||||
private final ApplicationInfoManager applicationInfoManager;
|
||||
|
||||
private AtomicReference<EurekaHttpClient> eurekaHttpClient = new AtomicReference<>();
|
||||
private final AtomicReference<EurekaHttpClient> eurekaHttpClient = new AtomicReference<>();
|
||||
|
||||
public CloudEurekaClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config,
|
||||
ApplicationEventPublisher publisher) {
|
||||
this(applicationInfoManager, config, null, publisher);
|
||||
TransportClientFactories transportClientFactories, ApplicationEventPublisher publisher) {
|
||||
this(applicationInfoManager, config, transportClientFactories, null, publisher);
|
||||
}
|
||||
|
||||
public CloudEurekaClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config,
|
||||
AbstractDiscoveryClientOptionalArgs<?> args, ApplicationEventPublisher publisher) {
|
||||
super(applicationInfoManager, config, args);
|
||||
TransportClientFactories transportClientFactories, AbstractDiscoveryClientOptionalArgs<?> args,
|
||||
ApplicationEventPublisher publisher) {
|
||||
super(applicationInfoManager, config, transportClientFactories, args);
|
||||
this.applicationInfoManager = applicationInfoManager;
|
||||
this.publisher = publisher;
|
||||
this.eurekaTransportField = ReflectionUtils.findField(DiscoveryClient.class, "eurekaTransport");
|
||||
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.cloud.netflix.eureka;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Convenience annotation for clients to enable Eureka discovery configuration
|
||||
* (specifically). Use this (optionally) in case you want discovery and know for sure that
|
||||
* it is Eureka you want. All it does is turn on discovery and let the autoconfiguration
|
||||
* find the eureka classes if they are available (i.e. you need Eureka on the classpath as
|
||||
* well).
|
||||
*
|
||||
* @author Dave Syer
|
||||
* @author Spencer Gibb
|
||||
*/
|
||||
@Target(ElementType.TYPE)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@Inherited
|
||||
public @interface EnableEurekaClient {
|
||||
|
||||
}
|
||||
+112
-6
@@ -24,14 +24,36 @@ import java.lang.annotation.Target;
|
||||
import java.util.Map;
|
||||
|
||||
import com.netflix.appinfo.ApplicationInfoManager;
|
||||
import com.netflix.appinfo.DataCenterInfo;
|
||||
import com.netflix.appinfo.EurekaInstanceConfig;
|
||||
import com.netflix.appinfo.HealthCheckHandler;
|
||||
import com.netflix.appinfo.InstanceInfo;
|
||||
import com.netflix.appinfo.LeaseInfo;
|
||||
import com.netflix.appinfo.MyDataCenterInfo;
|
||||
import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs;
|
||||
import com.netflix.discovery.DiscoveryClient;
|
||||
import com.netflix.discovery.EurekaClient;
|
||||
import com.netflix.discovery.EurekaClientConfig;
|
||||
import com.netflix.discovery.TimedSupervisorTask;
|
||||
import com.netflix.discovery.converters.jackson.DataCenterTypeInfoResolver;
|
||||
import com.netflix.discovery.converters.jackson.builder.ApplicationsJacksonBuilder;
|
||||
import com.netflix.discovery.converters.jackson.mixin.InstanceInfoJsonMixIn;
|
||||
import com.netflix.discovery.shared.Application;
|
||||
import com.netflix.discovery.shared.Applications;
|
||||
import com.netflix.discovery.shared.resolver.AsyncResolver;
|
||||
import com.netflix.discovery.shared.resolver.DefaultEndpoint;
|
||||
import com.netflix.discovery.shared.resolver.EurekaEndpoint;
|
||||
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
|
||||
import com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator;
|
||||
import com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient;
|
||||
import com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient;
|
||||
import com.netflix.discovery.shared.transport.jersey.TransportClientFactories;
|
||||
|
||||
import org.springframework.aop.support.AopUtils;
|
||||
import org.springframework.aot.hint.MemberCategory;
|
||||
import org.springframework.aot.hint.RuntimeHints;
|
||||
import org.springframework.aot.hint.RuntimeHintsRegistrar;
|
||||
import org.springframework.aot.hint.TypeReference;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
|
||||
@@ -67,6 +89,7 @@ import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.core.env.ConfigurableEnvironment;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import static org.springframework.cloud.commons.util.IdUtils.getDefaultInstanceId;
|
||||
@@ -93,7 +116,7 @@ import static org.springframework.cloud.commons.util.IdUtils.getDefaultInstanceI
|
||||
"org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration" })
|
||||
public class EurekaClientAutoConfiguration {
|
||||
|
||||
private ConfigurableEnvironment env;
|
||||
private final ConfigurableEnvironment env;
|
||||
|
||||
public EurekaClientAutoConfiguration(ConfigurableEnvironment env) {
|
||||
this.env = env;
|
||||
@@ -239,8 +262,9 @@ public class EurekaClientAutoConfiguration {
|
||||
|
||||
@Bean(destroyMethod = "shutdown")
|
||||
@ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT)
|
||||
public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config) {
|
||||
return new CloudEurekaClient(manager, config, this.optionalArgs, this.context);
|
||||
public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config,
|
||||
TransportClientFactories<?> transportClientFactories) {
|
||||
return new CloudEurekaClient(manager, config, transportClientFactories, this.optionalArgs, this.context);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -277,7 +301,8 @@ public class EurekaClientAutoConfiguration {
|
||||
@org.springframework.cloud.context.config.annotation.RefreshScope
|
||||
@Lazy
|
||||
public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config,
|
||||
EurekaInstanceConfig instance, @Autowired(required = false) HealthCheckHandler healthCheckHandler) {
|
||||
EurekaInstanceConfig instance, TransportClientFactories<?> transportClientFactories,
|
||||
@Autowired(required = false) HealthCheckHandler healthCheckHandler) {
|
||||
// If we use the proxy of the ApplicationInfoManager we could run into a
|
||||
// problem
|
||||
// when shutdown is called on the CloudEurekaClient where the
|
||||
@@ -292,8 +317,8 @@ public class EurekaClientAutoConfiguration {
|
||||
else {
|
||||
appManager = manager;
|
||||
}
|
||||
CloudEurekaClient cloudEurekaClient = new CloudEurekaClient(appManager, config, this.optionalArgs,
|
||||
this.context);
|
||||
CloudEurekaClient cloudEurekaClient = new CloudEurekaClient(appManager, config, transportClientFactories,
|
||||
this.optionalArgs, this.context);
|
||||
cloudEurekaClient.registerHealthCheck(healthCheckHandler);
|
||||
return cloudEurekaClient;
|
||||
}
|
||||
@@ -376,3 +401,84 @@ public class EurekaClientAutoConfiguration {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Remove after adding hints to GraalVM reachability metadata repo
|
||||
class EurekaClientHints implements RuntimeHintsRegistrar {
|
||||
|
||||
@Override
|
||||
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
|
||||
if (!ClassUtils.isPresent("com.netflix.discovery.DiscoveryClient", classLoader)) {
|
||||
return;
|
||||
}
|
||||
hints.reflection().registerType(TypeReference.of(DiscoveryClient.class),
|
||||
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INTROSPECT_DECLARED_METHODS))
|
||||
.registerType(TypeReference.of(EurekaEndpoint.class),
|
||||
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS))
|
||||
.registerType(TypeReference.of(DefaultEndpoint.class),
|
||||
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
|
||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
|
||||
.registerType(TypeReference.of(EurekaHttpClientDecorator.class),
|
||||
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS,
|
||||
MemberCategory.INTROSPECT_DECLARED_METHODS))
|
||||
.registerType(TypeReference.of(EurekaHttpResponse.class),
|
||||
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
|
||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
|
||||
.registerType(TypeReference.of(EurekaHttpClientDecorator.RequestExecutor.class),
|
||||
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS))
|
||||
.registerType(TypeReference.of(ApplicationInfoManager.class),
|
||||
hint -> hint.withMembers(MemberCategory.INTROSPECT_DECLARED_METHODS))
|
||||
.registerType(TypeReference.of(InstanceInfo.class),
|
||||
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS,
|
||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
|
||||
.registerType(TypeReference.of(InstanceInfo.ActionType.class),
|
||||
hint -> hint.withMembers(MemberCategory.INTROSPECT_DECLARED_METHODS,
|
||||
MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(InstanceInfo.PortWrapper.class),
|
||||
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS,
|
||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(LeaseInfo.class),
|
||||
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS,
|
||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(MyDataCenterInfo.class),
|
||||
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS,
|
||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(DataCenterInfo.class),
|
||||
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS,
|
||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(DataCenterInfo.Name.class),
|
||||
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS,
|
||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(EurekaClient.class),
|
||||
hint -> hint.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS))
|
||||
.registerType(TypeReference.of(TimedSupervisorTask.class),
|
||||
hint -> hint.withMembers(MemberCategory.INTROSPECT_DECLARED_METHODS,
|
||||
MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(DataCenterTypeInfoResolver.class),
|
||||
hint -> hint.withMembers(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS))
|
||||
.registerType(TypeReference.of(ApplicationsJacksonBuilder.class),
|
||||
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS,
|
||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(InstanceInfoJsonMixIn.class),
|
||||
hint -> hint.withMembers(MemberCategory.INTROSPECT_DECLARED_METHODS,
|
||||
MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(Application.class),
|
||||
hint -> hint.withMembers(MemberCategory.INTROSPECT_DECLARED_METHODS,
|
||||
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(Applications.class),
|
||||
hint -> hint.withMembers(MemberCategory.INTROSPECT_DECLARED_METHODS,
|
||||
MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(AsyncResolver.class),
|
||||
hint -> hint.withMembers(MemberCategory.INTROSPECT_DECLARED_METHODS,
|
||||
MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(RetryableEurekaHttpClient.class),
|
||||
hint -> hint.withMembers(MemberCategory.INTROSPECT_DECLARED_METHODS,
|
||||
MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(SessionedEurekaHttpClient.class),
|
||||
hint -> hint.withMembers(MemberCategory.INTROSPECT_DECLARED_METHODS,
|
||||
MemberCategory.DECLARED_FIELDS))
|
||||
.registerType(TypeReference.of(EurekaServiceInstance.class),
|
||||
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS,
|
||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+5
-4
@@ -25,6 +25,7 @@ import java.util.Objects;
|
||||
import com.netflix.appinfo.EurekaAccept;
|
||||
import com.netflix.discovery.EurekaClientConfig;
|
||||
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
|
||||
import org.apache.hc.client5.http.classic.HttpClient;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
@@ -126,14 +127,14 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered {
|
||||
/**
|
||||
* Indicates how long to wait (in seconds) before a connection to eureka server needs
|
||||
* to timeout. Note that the connections in the client are pooled by
|
||||
* org.apache.http.client.HttpClient and this setting affects the actual connection
|
||||
* creation and also the wait time to get the connection from the pool.
|
||||
* {@link HttpClient} and this setting affects the actual connection creation and also
|
||||
* the wait time to get the connection from the pool.
|
||||
*/
|
||||
private int eurekaServerConnectTimeoutSeconds = 5;
|
||||
|
||||
/**
|
||||
* Gets the name of the implementation which implements BackupRegistry to fetch the
|
||||
* registry information as a fall back option for only the first time when the eureka
|
||||
* registry information as a fallback option for only the first time when the eureka
|
||||
* client starts.
|
||||
*
|
||||
* This may be needed for applications which needs additional resiliency for registry
|
||||
@@ -472,7 +473,7 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered {
|
||||
if (serviceUrls == null || serviceUrls.isEmpty()) {
|
||||
serviceUrls = this.serviceUrl.get(DEFAULT_ZONE);
|
||||
}
|
||||
if (!StringUtils.isEmpty(serviceUrls)) {
|
||||
if (StringUtils.hasText(serviceUrls)) {
|
||||
final String[] serviceUrlsSplit = StringUtils.commaDelimitedListToStringArray(serviceUrls);
|
||||
List<String> eurekaServiceUrls = new ArrayList<>(serviceUrlsSplit.length);
|
||||
for (String eurekaServiceUrl : serviceUrlsSplit) {
|
||||
|
||||
+5
-6
@@ -67,7 +67,7 @@ import org.springframework.util.Assert;
|
||||
public class EurekaHealthCheckHandler
|
||||
implements HealthCheckHandler, ApplicationContextAware, InitializingBean, Ordered, Lifecycle {
|
||||
|
||||
private static final Map<Status, InstanceInfo.InstanceStatus> STATUS_MAPPING = new HashMap<Status, InstanceInfo.InstanceStatus>() {
|
||||
private static final Map<Status, InstanceInfo.InstanceStatus> STATUS_MAPPING = new HashMap<>() {
|
||||
{
|
||||
put(Status.UNKNOWN, InstanceStatus.UNKNOWN);
|
||||
put(Status.OUT_OF_SERVICE, InstanceStatus.DOWN);
|
||||
@@ -76,18 +76,18 @@ public class EurekaHealthCheckHandler
|
||||
}
|
||||
};
|
||||
|
||||
private StatusAggregator statusAggregator;
|
||||
private final StatusAggregator statusAggregator;
|
||||
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
private Map<String, HealthContributor> healthContributors = new HashMap<>();
|
||||
private final Map<String, HealthContributor> healthContributors = new HashMap<>();
|
||||
|
||||
/**
|
||||
* {@code true} until the context is stopped.
|
||||
*/
|
||||
private boolean running = true;
|
||||
|
||||
private Map<String, ReactiveHealthContributor> reactiveHealthContributors = new HashMap<>();
|
||||
private final Map<String, ReactiveHealthContributor> reactiveHealthContributors = new HashMap<>();
|
||||
|
||||
public EurekaHealthCheckHandler(StatusAggregator statusAggregator) {
|
||||
this.statusAggregator = statusAggregator;
|
||||
@@ -110,8 +110,7 @@ public class EurekaHealthCheckHandler
|
||||
for (Map.Entry<String, HealthContributor> entry : healthContributors.entrySet()) {
|
||||
// ignore EurekaHealthIndicator and flatten the rest of the composite
|
||||
// otherwise there is a never ending cycle of down. See gh-643
|
||||
if (entry.getValue() instanceof DiscoveryCompositeHealthContributor) {
|
||||
DiscoveryCompositeHealthContributor indicator = (DiscoveryCompositeHealthContributor) entry.getValue();
|
||||
if (entry.getValue() instanceof DiscoveryCompositeHealthContributor indicator) {
|
||||
indicator.getIndicators().forEach((name, discoveryHealthIndicator) -> {
|
||||
if (!(discoveryHealthIndicator instanceof EurekaHealthIndicator)) {
|
||||
this.healthContributors.put(name, (HealthIndicator) discoveryHealthIndicator::health);
|
||||
|
||||
+1
-1
@@ -92,7 +92,7 @@ public class EurekaHealthIndicator implements DiscoveryHealthIndicator {
|
||||
if (AopUtils.isAopProxy(eurekaClient)) {
|
||||
discoveryClient = ProxyUtils.getTargetObject(eurekaClient);
|
||||
}
|
||||
else if (DiscoveryClient.class.isInstance(eurekaClient)) {
|
||||
else if (eurekaClient instanceof DiscoveryClient) {
|
||||
discoveryClient = (DiscoveryClient) eurekaClient;
|
||||
}
|
||||
return discoveryClient;
|
||||
|
||||
+3
-1
@@ -25,6 +25,7 @@ import com.netflix.appinfo.DataCenterInfo;
|
||||
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
|
||||
import com.netflix.appinfo.MyDataCenterInfo;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.cloud.commons.util.InetUtils;
|
||||
import org.springframework.cloud.commons.util.InetUtils.HostInfo;
|
||||
@@ -285,6 +286,7 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi
|
||||
private EurekaInstanceConfigBean() {
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public EurekaInstanceConfigBean(InetUtils inetUtils) {
|
||||
this.inetUtils = inetUtils;
|
||||
this.hostInfo = this.inetUtils.findFirstNonLoopbackHostInfo();
|
||||
@@ -605,7 +607,7 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi
|
||||
leaseExpirationDurationInSeconds, virtualHostName, instanceId, secureVirtualHostName, aSGName,
|
||||
metadataMap, dataCenterInfo, ipAddress, statusPageUrlPath, statusPageUrl, homePageUrlPath, homePageUrl,
|
||||
healthCheckUrlPath, healthCheckUrl, secureHealthCheckUrl, namespace, hostname, preferIpAddress,
|
||||
initialStatus, defaultAddressResolutionOrder, environment);
|
||||
initialStatus, Arrays.hashCode(defaultAddressResolutionOrder), environment);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ import static com.netflix.appinfo.InstanceInfo.PortType.SECURE;
|
||||
*/
|
||||
public class EurekaServiceInstance implements ServiceInstance {
|
||||
|
||||
private InstanceInfo instance;
|
||||
private final InstanceInfo instance;
|
||||
|
||||
public EurekaServiceInstance(InstanceInfo instance) {
|
||||
Assert.notNull(instance, "Service instance required");
|
||||
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.cloud.netflix.eureka;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
*/
|
||||
// FIXME: 4.0
|
||||
public class MutableDiscoveryClientOptionalArgs {
|
||||
|
||||
} /*
|
||||
* extends DiscoveryClientOptionalArgs {
|
||||
*
|
||||
* private Collection<ClientFilter> additionalFilters;
|
||||
*
|
||||
* @Override public void setAdditionalFilters(Collection<ClientFilter>
|
||||
* additionalFilters) { additionalFilters = new LinkedHashSet<>(additionalFilters);
|
||||
* this.additionalFilters = additionalFilters;
|
||||
* super.setAdditionalFilters(additionalFilters); }
|
||||
*
|
||||
* public Collection<ClientFilter> getAdditionalFilters() { return
|
||||
* this.additionalFilters; }
|
||||
*
|
||||
* }
|
||||
*/
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.cloud.netflix.eureka;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.core5.http.io.SocketConfig;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.cloud.netflix.eureka.http.RestTemplateEurekaHttpClient;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
/**
|
||||
* Properties for configuring timeouts used in {@link RestTemplate} required by
|
||||
* {@link RestTemplateEurekaHttpClient}.
|
||||
*
|
||||
* @author Jiwon Jeon
|
||||
* @since 3.1.6
|
||||
*/
|
||||
@ConfigurationProperties("eureka.client.rest-template-timeout")
|
||||
public class RestTemplateTimeoutProperties {
|
||||
|
||||
/**
|
||||
* Default values are set to 180000, in keeping with {@link RequestConfig} and
|
||||
* {@link SocketConfig} defaults.
|
||||
*/
|
||||
private int connectTimeout = 3 * 60 * 1000;
|
||||
|
||||
private int connectRequestTimeout = 3 * 60 * 1000;
|
||||
|
||||
private int socketTimeout = 3 * 60 * 1000;
|
||||
|
||||
public int getConnectTimeout() {
|
||||
return connectTimeout;
|
||||
}
|
||||
|
||||
public int getConnectRequestTimeout() {
|
||||
return connectRequestTimeout;
|
||||
}
|
||||
|
||||
public int getSocketTimeout() {
|
||||
return socketTimeout;
|
||||
}
|
||||
|
||||
public void setConnectTimeout(int connectTimeout) {
|
||||
this.connectTimeout = connectTimeout;
|
||||
}
|
||||
|
||||
public void setConnectRequestTimeout(int connectRequestTimeout) {
|
||||
this.connectRequestTimeout = connectRequestTimeout;
|
||||
}
|
||||
|
||||
public void setSocketTimeout(int socketTimeout) {
|
||||
this.socketTimeout = socketTimeout;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
RestTemplateTimeoutProperties that = (RestTemplateTimeoutProperties) o;
|
||||
|
||||
return connectTimeout == that.connectTimeout && connectRequestTimeout == that.connectRequestTimeout
|
||||
&& socketTimeout == that.socketTimeout;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(connectTimeout, connectRequestTimeout, socketTimeout);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "RestTemplateTimeoutProperties{" + ", connectTimeout=" + connectTimeout + ", connectRequestTimeout="
|
||||
+ connectRequestTimeout + ", socketTimeout=" + socketTimeout + '}';
|
||||
}
|
||||
|
||||
}
|
||||
+44
-20
@@ -20,23 +20,29 @@ import java.io.IOException;
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs;
|
||||
import com.netflix.discovery.shared.transport.jersey.TransportClientFactories;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
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.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.configuration.SSLContextFactory;
|
||||
import org.springframework.cloud.configuration.TlsProperties;
|
||||
import org.springframework.cloud.netflix.eureka.RestTemplateTimeoutProperties;
|
||||
import org.springframework.cloud.netflix.eureka.http.DefaultEurekaClientHttpRequestFactorySupplier;
|
||||
import org.springframework.cloud.netflix.eureka.http.EurekaClientHttpRequestFactorySupplier;
|
||||
import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClientOptionalArgs;
|
||||
import org.springframework.cloud.netflix.eureka.http.RestTemplateTransportClientFactories;
|
||||
import org.springframework.cloud.netflix.eureka.http.WebClientDiscoveryClientOptionalArgs;
|
||||
import org.springframework.cloud.netflix.eureka.http.WebClientTransportClientFactories;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
@@ -45,6 +51,7 @@ import org.springframework.web.reactive.function.client.WebClient;
|
||||
* @author Daniel Lavoie
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableConfigurationProperties(RestTemplateTimeoutProperties.class)
|
||||
public class DiscoveryClientOptionalArgsConfiguration {
|
||||
|
||||
protected static final Log logger = LogFactory.getLog(DiscoveryClientOptionalArgsConfiguration.class);
|
||||
@@ -57,7 +64,7 @@ public class DiscoveryClientOptionalArgsConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnClass(name = "org.springframework.web.client.RestTemplate")
|
||||
@ConditionalOnMissingClass("com.sun.jersey.api.client.filter.ClientFilter")
|
||||
@ConditionalOnMissingClass("org.glassfish.jersey.client.JerseyClient")
|
||||
@ConditionalOnMissingBean(value = { AbstractDiscoveryClientOptionalArgs.class }, search = SearchStrategy.CURRENT)
|
||||
@ConditionalOnProperty(prefix = "eureka.client", name = "webclient.enabled", matchIfMissing = true,
|
||||
havingValue = "false")
|
||||
@@ -72,26 +79,23 @@ public class DiscoveryClientOptionalArgsConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnClass(name = "org.springframework.web.client.RestTemplate")
|
||||
EurekaClientHttpRequestFactorySupplier defaultEurekaClientHttpRequestFactorySupplier() {
|
||||
return new DefaultEurekaClientHttpRequestFactorySupplier();
|
||||
@ConditionalOnMissingClass("org.glassfish.jersey.client.JerseyClient")
|
||||
@ConditionalOnMissingBean(value = { TransportClientFactories.class }, search = SearchStrategy.CURRENT)
|
||||
@ConditionalOnProperty(prefix = "eureka.client", name = "webclient.enabled", matchIfMissing = true,
|
||||
havingValue = "false")
|
||||
public RestTemplateTransportClientFactories restTemplateTransportClientFactories(
|
||||
RestTemplateDiscoveryClientOptionalArgs optionalArgs) {
|
||||
return new RestTemplateTransportClientFactories(optionalArgs);
|
||||
}
|
||||
|
||||
// FIXME: 4.0
|
||||
/*
|
||||
* @Bean
|
||||
*
|
||||
* @ConditionalOnClass(name = "com.sun.jersey.api.client.filter.ClientFilter")
|
||||
*
|
||||
* @ConditionalOnMissingBean(value = AbstractDiscoveryClientOptionalArgs.class, search
|
||||
* = SearchStrategy.CURRENT) public MutableDiscoveryClientOptionalArgs
|
||||
* discoveryClientOptionalArgs(TlsProperties tlsProperties) throws
|
||||
* GeneralSecurityException, IOException {
|
||||
* logger.info("Eureka HTTP Client uses Jersey"); MutableDiscoveryClientOptionalArgs
|
||||
* result = new MutableDiscoveryClientOptionalArgs(); setupTLS(result, tlsProperties);
|
||||
* return result; }
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnClass(name = "org.springframework.web.client.RestTemplate")
|
||||
EurekaClientHttpRequestFactorySupplier defaultEurekaClientHttpRequestFactorySupplier(
|
||||
RestTemplateTimeoutProperties restTemplateTimeoutProperties) {
|
||||
return new DefaultEurekaClientHttpRequestFactorySupplier(restTemplateTimeoutProperties);
|
||||
}
|
||||
|
||||
private static void setupTLS(AbstractDiscoveryClientOptionalArgs<?> args, TlsProperties properties)
|
||||
throws GeneralSecurityException, IOException {
|
||||
@@ -101,7 +105,20 @@ public class DiscoveryClientOptionalArgsConfiguration {
|
||||
}
|
||||
}
|
||||
|
||||
@ConditionalOnMissingClass("com.sun.jersey.api.client.filter.ClientFilter")
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass(name = "org.glassfish.jersey.client.JerseyClient")
|
||||
@ConditionalOnBean(value = AbstractDiscoveryClientOptionalArgs.class, search = SearchStrategy.CURRENT)
|
||||
static class DiscoveryClientOptionalArgsTlsConfiguration {
|
||||
|
||||
DiscoveryClientOptionalArgsTlsConfiguration(TlsProperties tlsProperties,
|
||||
AbstractDiscoveryClientOptionalArgs optionalArgs) throws GeneralSecurityException, IOException {
|
||||
logger.info("Eureka HTTP Client uses Jersey");
|
||||
setupTLS(optionalArgs, tlsProperties);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ConditionalOnMissingClass("org.glassfish.jersey.client.JerseyClient")
|
||||
@ConditionalOnClass(name = "org.springframework.web.reactive.function.client.WebClient")
|
||||
@ConditionalOnProperty(prefix = "eureka.client", name = "webclient.enabled", havingValue = "true")
|
||||
protected static class WebClientConfiguration {
|
||||
@@ -122,10 +139,17 @@ public class DiscoveryClientOptionalArgsConfiguration {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(value = TransportClientFactories.class, search = SearchStrategy.CURRENT)
|
||||
public WebClientTransportClientFactories webClientTransportClientFactories(
|
||||
ObjectProvider<WebClient.Builder> builder) {
|
||||
return new WebClientTransportClientFactories(builder::getIfAvailable);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnMissingClass({ "com.sun.jersey.api.client.filter.ClientFilter",
|
||||
@ConditionalOnMissingClass({ "org.glassfish.jersey.client.JerseyClient",
|
||||
"org.springframework.web.reactive.function.client.WebClient" })
|
||||
@ConditionalOnProperty(prefix = "eureka.client", name = "webclient.enabled", havingValue = "true")
|
||||
protected static class WebClientNotFoundConfiguration {
|
||||
|
||||
+46
-23
@@ -17,12 +17,17 @@
|
||||
package org.springframework.cloud.netflix.eureka.config;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import com.netflix.discovery.shared.transport.EurekaHttpClient;
|
||||
import org.apache.commons.logging.Log;
|
||||
|
||||
import org.springframework.boot.BootstrapContext;
|
||||
import org.springframework.boot.BootstrapRegistry;
|
||||
import org.springframework.boot.BootstrapRegistryInitializer;
|
||||
import org.springframework.boot.context.properties.bind.BindHandler;
|
||||
import org.springframework.boot.context.properties.bind.Binder;
|
||||
import org.springframework.cloud.client.ServiceInstance;
|
||||
import org.springframework.cloud.config.client.ConfigClientProperties;
|
||||
import org.springframework.cloud.config.client.ConfigServerInstanceProvider;
|
||||
import org.springframework.cloud.configuration.TlsProperties;
|
||||
@@ -39,35 +44,53 @@ public class EurekaConfigServerBootstrapper implements BootstrapRegistryInitiali
|
||||
if (!ClassUtils.isPresent("org.springframework.cloud.config.client.ConfigServerInstanceProvider", null)) {
|
||||
return;
|
||||
}
|
||||
registry.registerIfAbsent(EurekaClientConfigBean.class, context -> {
|
||||
Binder binder = context.get(Binder.class);
|
||||
if (!getDiscoveryEnabled(binder)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return binder.bind(EurekaClientConfigBean.PREFIX, EurekaClientConfigBean.class)
|
||||
.orElseGet(EurekaClientConfigBean::new);
|
||||
});
|
||||
|
||||
registry.registerIfAbsent(ConfigServerInstanceProvider.Function.class, context -> {
|
||||
Binder binder = context.get(Binder.class);
|
||||
if (!getDiscoveryEnabled(binder)) {
|
||||
return (id) -> Collections.emptyList();
|
||||
}
|
||||
EurekaClientConfigBean config = context.get(EurekaClientConfigBean.class);
|
||||
EurekaHttpClient httpClient = new RestTemplateTransportClientFactory(
|
||||
context.getOrElse(TlsProperties.class, null),
|
||||
context.getOrElse(EurekaClientHttpRequestFactorySupplier.class,
|
||||
new DefaultEurekaClientHttpRequestFactorySupplier()))
|
||||
.newClient(HostnameBasedUrlRandomizer.randomEndpoint(config, binder));
|
||||
return new EurekaConfigServerInstanceProvider(httpClient, config)::getInstances;
|
||||
});
|
||||
// It is important that we pass a lambda for the Function or else we will get a
|
||||
// ClassNotFoundException when config is not on the classpath
|
||||
registry.registerIfAbsent(ConfigServerInstanceProvider.Function.class, EurekaFunction::create);
|
||||
}
|
||||
|
||||
private Boolean getDiscoveryEnabled(Binder binder) {
|
||||
private static Boolean getDiscoveryEnabled(Binder binder) {
|
||||
return binder.bind(ConfigClientProperties.CONFIG_DISCOVERY_ENABLED, Boolean.class).orElse(false)
|
||||
&& binder.bind("eureka.client.enabled", Boolean.class).orElse(true)
|
||||
&& binder.bind("spring.cloud.discovery.enabled", Boolean.class).orElse(true);
|
||||
}
|
||||
|
||||
final static class EurekaFunction implements ConfigServerInstanceProvider.Function {
|
||||
|
||||
private final BootstrapContext context;
|
||||
|
||||
static EurekaFunction create(BootstrapContext context) {
|
||||
return new EurekaFunction(context);
|
||||
}
|
||||
|
||||
private EurekaFunction(BootstrapContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ServiceInstance> apply(String serviceId, Binder binder, BindHandler bindHandler, Log log) {
|
||||
if (binder == null || !getDiscoveryEnabled(binder)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
EurekaClientConfigBean config = binder.bind(EurekaClientConfigBean.PREFIX, EurekaClientConfigBean.class)
|
||||
.orElseGet(EurekaClientConfigBean::new);
|
||||
EurekaHttpClient httpClient = new RestTemplateTransportClientFactory(
|
||||
context.getOrElse(TlsProperties.class, null),
|
||||
context.getOrElse(EurekaClientHttpRequestFactorySupplier.class,
|
||||
new DefaultEurekaClientHttpRequestFactorySupplier()))
|
||||
.newClient(HostnameBasedUrlRandomizer.randomEndpoint(config, binder));
|
||||
return new EurekaConfigServerInstanceProvider(httpClient, config).getInstances(serviceId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ServiceInstance> apply(String serviceId) {
|
||||
// This should never be called now but is here for backward
|
||||
// compatibility
|
||||
return apply(serviceId, null, null, null);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+65
-8
@@ -16,13 +16,22 @@
|
||||
|
||||
package org.springframework.cloud.netflix.eureka.http;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
|
||||
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
|
||||
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
|
||||
import org.apache.hc.core5.http.io.SocketConfig;
|
||||
import org.apache.hc.core5.util.Timeout;
|
||||
|
||||
import org.springframework.cloud.netflix.eureka.RestTemplateTimeoutProperties;
|
||||
import org.springframework.http.client.ClientHttpRequestFactory;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.lang.Nullable;
|
||||
@@ -32,23 +41,71 @@ import org.springframework.lang.Nullable;
|
||||
* {@link HttpClients}.
|
||||
*
|
||||
* @author Marcin Grzejszczak
|
||||
* @author Olga Maciaszek-Sharma
|
||||
* @author Jiwon Jeon
|
||||
* @since 3.0.0
|
||||
*/
|
||||
public class DefaultEurekaClientHttpRequestFactorySupplier implements EurekaClientHttpRequestFactorySupplier {
|
||||
|
||||
private final RestTemplateTimeoutProperties restTemplateTimeoutProperties;
|
||||
|
||||
/**
|
||||
* @deprecated in favour of
|
||||
* {@link DefaultEurekaClientHttpRequestFactorySupplier#DefaultEurekaClientHttpRequestFactorySupplier(RestTemplateTimeoutProperties)}
|
||||
*/
|
||||
@Deprecated
|
||||
public DefaultEurekaClientHttpRequestFactorySupplier() {
|
||||
this.restTemplateTimeoutProperties = new RestTemplateTimeoutProperties();
|
||||
}
|
||||
|
||||
public DefaultEurekaClientHttpRequestFactorySupplier(RestTemplateTimeoutProperties restTemplateTimeoutProperties) {
|
||||
this.restTemplateTimeoutProperties = restTemplateTimeoutProperties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClientHttpRequestFactory get(SSLContext sslContext, @Nullable HostnameVerifier hostnameVerifier) {
|
||||
HttpClientBuilder httpClientBuilder = HttpClients.custom();
|
||||
if (sslContext != null) {
|
||||
httpClientBuilder = httpClientBuilder.setSSLContext(sslContext);
|
||||
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
|
||||
if (sslContext != null || hostnameVerifier != null || restTemplateTimeoutProperties != null) {
|
||||
httpClientBuilder.setConnectionManager(
|
||||
buildConnectionManager(sslContext, hostnameVerifier, restTemplateTimeoutProperties));
|
||||
}
|
||||
if (hostnameVerifier != null) {
|
||||
httpClientBuilder = httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
|
||||
if (restTemplateTimeoutProperties != null) {
|
||||
httpClientBuilder.setDefaultRequestConfig(buildRequestConfig());
|
||||
}
|
||||
|
||||
CloseableHttpClient httpClient = httpClientBuilder.build();
|
||||
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||
requestFactory.setHttpClient(httpClient);
|
||||
return requestFactory;
|
||||
}
|
||||
|
||||
private HttpClientConnectionManager buildConnectionManager(SSLContext sslContext, HostnameVerifier hostnameVerifier,
|
||||
RestTemplateTimeoutProperties restTemplateTimeoutProperties) {
|
||||
PoolingHttpClientConnectionManagerBuilder connectionManagerBuilder = PoolingHttpClientConnectionManagerBuilder
|
||||
.create();
|
||||
SSLConnectionSocketFactoryBuilder sslConnectionSocketFactoryBuilder = SSLConnectionSocketFactoryBuilder
|
||||
.create();
|
||||
if (sslContext != null) {
|
||||
sslConnectionSocketFactoryBuilder.setSslContext(sslContext);
|
||||
}
|
||||
if (hostnameVerifier != null) {
|
||||
sslConnectionSocketFactoryBuilder.setHostnameVerifier(hostnameVerifier);
|
||||
}
|
||||
connectionManagerBuilder.setSSLSocketFactory(sslConnectionSocketFactoryBuilder.build());
|
||||
if (restTemplateTimeoutProperties != null) {
|
||||
connectionManagerBuilder.setDefaultSocketConfig(SocketConfig.custom()
|
||||
.setSoTimeout(Timeout.of(restTemplateTimeoutProperties.getSocketTimeout(), TimeUnit.MILLISECONDS))
|
||||
.build());
|
||||
}
|
||||
return connectionManagerBuilder.build();
|
||||
}
|
||||
|
||||
private RequestConfig buildRequestConfig() {
|
||||
return RequestConfig.custom()
|
||||
.setConnectTimeout(Timeout.of(restTemplateTimeoutProperties.getConnectTimeout(), TimeUnit.MILLISECONDS))
|
||||
.setConnectionRequestTimeout(
|
||||
Timeout.of(restTemplateTimeoutProperties.getConnectRequestTimeout(), TimeUnit.MILLISECONDS))
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-10
@@ -28,16 +28,6 @@ public class RestTemplateDiscoveryClientOptionalArgs extends AbstractDiscoveryCl
|
||||
public RestTemplateDiscoveryClientOptionalArgs(
|
||||
EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier) {
|
||||
this.eurekaClientHttpRequestFactorySupplier = eurekaClientHttpRequestFactorySupplier;
|
||||
setTransportClientFactories(new RestTemplateTransportClientFactories(this));
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated - use
|
||||
* {@link RestTemplateDiscoveryClientOptionalArgs#RestTemplateDiscoveryClientOptionalArgs(EurekaClientHttpRequestFactorySupplier)}
|
||||
*/
|
||||
@Deprecated
|
||||
public RestTemplateDiscoveryClientOptionalArgs() {
|
||||
this(new DefaultEurekaClientHttpRequestFactorySupplier());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+15
-11
@@ -50,7 +50,7 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient {
|
||||
|
||||
protected final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private RestTemplate restTemplate;
|
||||
private final RestTemplate restTemplate;
|
||||
|
||||
private String serviceUrl;
|
||||
|
||||
@@ -66,6 +66,10 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient {
|
||||
return this.serviceUrl;
|
||||
}
|
||||
|
||||
public RestTemplate getRestTemplate() {
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EurekaHttpResponse<Void> register(InstanceInfo info) {
|
||||
String urlPath = serviceUrl + "apps/" + info.getAppName();
|
||||
@@ -77,7 +81,7 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient {
|
||||
ResponseEntity<Void> response = restTemplate.exchange(urlPath, HttpMethod.POST, new HttpEntity<>(info, headers),
|
||||
Void.class);
|
||||
|
||||
return anEurekaHttpResponse(response.getStatusCodeValue()).headers(headersOf(response)).build();
|
||||
return anEurekaHttpResponse(response.getStatusCode().value()).headers(headersOf(response)).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -86,7 +90,7 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient {
|
||||
|
||||
ResponseEntity<Void> response = restTemplate.exchange(urlPath, HttpMethod.DELETE, null, Void.class);
|
||||
|
||||
return anEurekaHttpResponse(response.getStatusCodeValue()).headers(headersOf(response)).build();
|
||||
return anEurekaHttpResponse(response.getStatusCode().value()).headers(headersOf(response)).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -100,7 +104,7 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient {
|
||||
InstanceInfo.class);
|
||||
|
||||
EurekaHttpResponseBuilder<InstanceInfo> eurekaResponseBuilder = anEurekaHttpResponse(
|
||||
response.getStatusCodeValue(), InstanceInfo.class).headers(headersOf(response));
|
||||
response.getStatusCode().value(), InstanceInfo.class).headers(headersOf(response));
|
||||
|
||||
if (response.hasBody()) {
|
||||
eurekaResponseBuilder.entity(response.getBody());
|
||||
@@ -117,7 +121,7 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient {
|
||||
|
||||
ResponseEntity<Void> response = restTemplate.exchange(urlPath, HttpMethod.PUT, null, Void.class);
|
||||
|
||||
return anEurekaHttpResponse(response.getStatusCodeValue()).headers(headersOf(response)).build();
|
||||
return anEurekaHttpResponse(response.getStatusCode().value()).headers(headersOf(response)).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -127,7 +131,7 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient {
|
||||
|
||||
ResponseEntity<Void> response = restTemplate.exchange(urlPath, HttpMethod.DELETE, null, Void.class);
|
||||
|
||||
return anEurekaHttpResponse(response.getStatusCodeValue()).headers(headersOf(response)).build();
|
||||
return anEurekaHttpResponse(response.getStatusCode().value()).headers(headersOf(response)).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -145,7 +149,7 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient {
|
||||
ResponseEntity<EurekaApplications> response = restTemplate.exchange(url, HttpMethod.GET, null,
|
||||
EurekaApplications.class);
|
||||
|
||||
return anEurekaHttpResponse(response.getStatusCodeValue(),
|
||||
return anEurekaHttpResponse(response.getStatusCode().value(),
|
||||
response.getStatusCode().value() == HttpStatus.OK.value() && response.hasBody()
|
||||
? (Applications) response.getBody() : null).headers(headersOf(response)).build();
|
||||
}
|
||||
@@ -171,10 +175,10 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient {
|
||||
|
||||
ResponseEntity<Application> response = restTemplate.exchange(urlPath, HttpMethod.GET, null, Application.class);
|
||||
|
||||
Application application = response.getStatusCodeValue() == HttpStatus.OK.value() && response.hasBody()
|
||||
Application application = response.getStatusCode().value() == HttpStatus.OK.value() && response.hasBody()
|
||||
? response.getBody() : null;
|
||||
|
||||
return anEurekaHttpResponse(response.getStatusCodeValue(), application).headers(headersOf(response)).build();
|
||||
return anEurekaHttpResponse(response.getStatusCode().value(), application).headers(headersOf(response)).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -193,8 +197,8 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient {
|
||||
ResponseEntity<InstanceInfo> response = restTemplate.exchange(urlPath, HttpMethod.GET, null,
|
||||
InstanceInfo.class);
|
||||
|
||||
return anEurekaHttpResponse(response.getStatusCodeValue(),
|
||||
response.getStatusCodeValue() == HttpStatus.OK.value() && response.hasBody() ? response.getBody()
|
||||
return anEurekaHttpResponse(response.getStatusCode().value(),
|
||||
response.getStatusCode().value() == HttpStatus.OK.value() && response.hasBody() ? response.getBody()
|
||||
: null).headers(headersOf(response)).build();
|
||||
}
|
||||
|
||||
|
||||
+74
-34
@@ -16,6 +16,8 @@
|
||||
|
||||
package org.springframework.cloud.netflix.eureka.http;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.Optional;
|
||||
@@ -27,7 +29,7 @@ import com.fasterxml.jackson.databind.BeanDescription;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
|
||||
import com.fasterxml.jackson.databind.SerializationConfig;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
@@ -44,12 +46,16 @@ import com.netflix.discovery.shared.transport.TransportClientFactory;
|
||||
|
||||
import org.springframework.cloud.configuration.SSLContextFactory;
|
||||
import org.springframework.cloud.configuration.TlsProperties;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.HttpStatusCode;
|
||||
import org.springframework.http.client.ClientHttpRequestFactory;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.web.client.DefaultResponseErrorHandler;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
/**
|
||||
* Provides the custom {@link RestTemplate} required by the
|
||||
@@ -101,11 +107,20 @@ public class RestTemplateTransportClientFactory implements TransportClientFactor
|
||||
|
||||
@Override
|
||||
public EurekaHttpClient newClient(EurekaEndpoint serviceUrl) {
|
||||
return new RestTemplateEurekaHttpClient(restTemplate(serviceUrl.getServiceUrl()), serviceUrl.getServiceUrl());
|
||||
return new RestTemplateEurekaHttpClient(restTemplate(serviceUrl.getServiceUrl()),
|
||||
stripUserInfo(serviceUrl.getServiceUrl()));
|
||||
}
|
||||
|
||||
// apache http client 5.2 fails with non-null userinfo
|
||||
// basic auth added in restTemplate() below
|
||||
private String stripUserInfo(String serviceUrl) {
|
||||
return UriComponentsBuilder.fromUriString(serviceUrl).userInfo(null).toUriString();
|
||||
}
|
||||
|
||||
private RestTemplate restTemplate(String serviceUrl) {
|
||||
RestTemplate restTemplate = restTemplate();
|
||||
ClientHttpRequestFactory requestFactory = this.eurekaClientHttpRequestFactorySupplier
|
||||
.get(this.sslContext.orElse(null), this.hostnameVerifier.orElse(null));
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
|
||||
try {
|
||||
URI serviceURI = new URI(serviceUrl);
|
||||
@@ -124,13 +139,15 @@ public class RestTemplateTransportClientFactory implements TransportClientFactor
|
||||
restTemplate.getMessageConverters().add(0, mappingJacksonHttpMessageConverter());
|
||||
restTemplate.setErrorHandler(new ErrorHandler());
|
||||
|
||||
return restTemplate;
|
||||
}
|
||||
restTemplate.getInterceptors().add((request, body, execution) -> {
|
||||
ClientHttpResponse response = execution.execute(request, body);
|
||||
if (!response.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
|
||||
return response;
|
||||
}
|
||||
return new NotFoundHttpResponse(response);
|
||||
});
|
||||
|
||||
private RestTemplate restTemplate() {
|
||||
ClientHttpRequestFactory requestFactory = this.eurekaClientHttpRequestFactorySupplier
|
||||
.get(this.sslContext.orElse(null), this.hostnameVerifier.orElse(null));
|
||||
return new RestTemplate(requestFactory);
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -139,17 +156,16 @@ public class RestTemplateTransportClientFactory implements TransportClientFactor
|
||||
* serialized or deserialized. Achived with
|
||||
* {@link SerializationFeature#WRAP_ROOT_VALUE} and
|
||||
* {@link DeserializationFeature#UNWRAP_ROOT_VALUE}.
|
||||
* {@link PropertyNamingStrategy.SnakeCaseStrategy} is applied to the underlying
|
||||
* {@link PropertyNamingStrategies.SnakeCaseStrategy} is applied to the underlying
|
||||
* {@link ObjectMapper}.
|
||||
* @return a {@link MappingJackson2HttpMessageConverter} object
|
||||
*/
|
||||
public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
|
||||
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
|
||||
converter.setObjectMapper(new ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE));
|
||||
converter.setObjectMapper(new ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE));
|
||||
|
||||
SimpleModule jsonModule = new SimpleModule();
|
||||
jsonModule.setSerializerModifier(createJsonSerializerModifier()); // keyFormatter,
|
||||
// compact));
|
||||
jsonModule.setSerializerModifier(createJsonSerializerModifier());
|
||||
converter.getObjectMapper().registerModule(jsonModule);
|
||||
|
||||
converter.getObjectMapper().configure(SerializationFeature.WRAP_ROOT_VALUE, true);
|
||||
@@ -157,34 +173,14 @@ public class RestTemplateTransportClientFactory implements TransportClientFactor
|
||||
converter.getObjectMapper().addMixIn(Applications.class, ApplicationsJsonMixIn.class);
|
||||
converter.getObjectMapper().addMixIn(InstanceInfo.class, InstanceInfoJsonMixIn.class);
|
||||
|
||||
// converter.getObjectMapper().addMixIn(DataCenterInfo.class,
|
||||
// DataCenterInfoXmlMixIn.class);
|
||||
// converter.getObjectMapper().addMixIn(InstanceInfo.PortWrapper.class,
|
||||
// PortWrapperXmlMixIn.class);
|
||||
// converter.getObjectMapper().addMixIn(Application.class,
|
||||
// ApplicationXmlMixIn.class);
|
||||
// converter.getObjectMapper().addMixIn(Applications.class,
|
||||
// ApplicationsXmlMixIn.class);
|
||||
|
||||
return converter;
|
||||
}
|
||||
|
||||
public static BeanSerializerModifier createJsonSerializerModifier() { // final
|
||||
// KeyFormatter
|
||||
// keyFormatter,
|
||||
// final
|
||||
// boolean
|
||||
// compactMode)
|
||||
// {
|
||||
public static BeanSerializerModifier createJsonSerializerModifier() {
|
||||
return new BeanSerializerModifier() {
|
||||
@Override
|
||||
public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc,
|
||||
JsonSerializer<?> serializer) {
|
||||
/*
|
||||
* if (beanDesc.getBeanClass().isAssignableFrom(Applications.class)) {
|
||||
* return new ApplicationsJsonBeanSerializer((BeanSerializerBase)
|
||||
* serializer, keyFormatter); }
|
||||
*/
|
||||
if (beanDesc.getBeanClass().isAssignableFrom(InstanceInfo.class)) {
|
||||
return new InstanceInfoJsonBeanSerializer((BeanSerializerBase) serializer, false);
|
||||
}
|
||||
@@ -197,6 +193,50 @@ public class RestTemplateTransportClientFactory implements TransportClientFactor
|
||||
public void shutdown() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Response that ignores body, specifically for 404 errors.
|
||||
*/
|
||||
private static class NotFoundHttpResponse implements ClientHttpResponse {
|
||||
|
||||
private final ClientHttpResponse response;
|
||||
|
||||
NotFoundHttpResponse(ClientHttpResponse response) {
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpStatusCode getStatusCode() throws IOException {
|
||||
return response.getStatusCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRawStatusCode() throws IOException {
|
||||
return response.getRawStatusCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getStatusText() throws IOException {
|
||||
return response.getStatusText();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
response.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getBody() throws IOException {
|
||||
// ignore body on 404 for heartbeat, see gh-4145
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpHeaders getHeaders() {
|
||||
return response.getHeaders();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class ErrorHandler extends DefaultResponseErrorHandler {
|
||||
|
||||
@Override
|
||||
|
||||
-1
@@ -29,7 +29,6 @@ import org.springframework.web.reactive.function.client.WebClient;
|
||||
public class WebClientDiscoveryClientOptionalArgs extends AbstractDiscoveryClientOptionalArgs<Void> {
|
||||
|
||||
public WebClientDiscoveryClientOptionalArgs(Supplier<WebClient.Builder> builder) {
|
||||
setTransportClientFactories(new WebClientTransportClientFactories(builder));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+41
-45
@@ -16,8 +16,6 @@
|
||||
|
||||
package org.springframework.cloud.netflix.eureka.http;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.netflix.appinfo.InstanceInfo;
|
||||
@@ -28,12 +26,13 @@ import com.netflix.discovery.shared.transport.EurekaHttpClient;
|
||||
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
|
||||
import com.netflix.discovery.shared.transport.EurekaHttpResponse.EurekaHttpResponseBuilder;
|
||||
import com.netflix.discovery.util.StringUtil;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.HttpStatusCode;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.reactive.function.BodyInserters;
|
||||
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
@@ -46,8 +45,6 @@ import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEureka
|
||||
*/
|
||||
public class WebClientEurekaHttpClient implements EurekaHttpClient {
|
||||
|
||||
protected final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private WebClient webClient;
|
||||
|
||||
public WebClientEurekaHttpClient(WebClient webClient) {
|
||||
@@ -56,16 +53,18 @@ public class WebClientEurekaHttpClient implements EurekaHttpClient {
|
||||
|
||||
@Override
|
||||
public EurekaHttpResponse<Void> register(InstanceInfo info) {
|
||||
return webClient.post().uri("apps/" + info.getAppName(), Void.class).body(BodyInserters.fromValue(info))
|
||||
return webClient.post().uri("apps/" + info.getAppName()).body(BodyInserters.fromValue(info))
|
||||
.header(HttpHeaders.ACCEPT_ENCODING, "gzip")
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).exchange()
|
||||
.map(response -> eurekaHttpResponse(response)).block();
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).retrieve()
|
||||
.onStatus(HttpStatusCode::isError, this::ignoreError).toBodilessEntity().map(this::eurekaHttpResponse)
|
||||
.block();
|
||||
}
|
||||
|
||||
@Override
|
||||
public EurekaHttpResponse<Void> cancel(String appName, String id) {
|
||||
return webClient.delete().uri("apps/" + appName + '/' + id, Void.class).exchange()
|
||||
.map(response -> eurekaHttpResponse(response)).block();
|
||||
return webClient.delete().uri("apps/" + appName + '/' + id).retrieve()
|
||||
.onStatus(HttpStatusCode::isError, this::ignoreError).toBodilessEntity().map(this::eurekaHttpResponse)
|
||||
.block();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -75,14 +74,15 @@ public class WebClientEurekaHttpClient implements EurekaHttpClient {
|
||||
+ "&lastDirtyTimestamp=" + info.getLastDirtyTimestamp().toString()
|
||||
+ (overriddenStatus != null ? "&overriddenstatus=" + overriddenStatus.name() : "");
|
||||
|
||||
ClientResponse response = webClient.put().uri(urlPath, InstanceInfo.class)
|
||||
ResponseEntity<InstanceInfo> response = webClient.put().uri(urlPath)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).exchange().block();
|
||||
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).retrieve()
|
||||
.onStatus(HttpStatusCode::isError, this::ignoreError).toEntity(InstanceInfo.class).block();
|
||||
|
||||
EurekaHttpResponseBuilder<InstanceInfo> builder = anEurekaHttpResponse(statusCodeValueOf(response),
|
||||
InstanceInfo.class).headers(headersOf(response));
|
||||
|
||||
InstanceInfo entity = response.toEntity(InstanceInfo.class).block().getBody();
|
||||
InstanceInfo entity = response.getBody();
|
||||
|
||||
if (entity != null) {
|
||||
builder.entity(entity);
|
||||
@@ -98,9 +98,9 @@ public class WebClientEurekaHttpClient implements EurekaHttpClient {
|
||||
String urlPath = "apps/" + appName + '/' + id + "/status?value=" + newStatus.name() + "&lastDirtyTimestamp="
|
||||
+ info.getLastDirtyTimestamp().toString();
|
||||
|
||||
return webClient.put().uri(urlPath, Void.class)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).exchange()
|
||||
.map(response -> eurekaHttpResponse(response)).block();
|
||||
return webClient.put().uri(urlPath).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.retrieve().onStatus(HttpStatusCode::isError, this::ignoreError).toBodilessEntity()
|
||||
.map(this::eurekaHttpResponse).block();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -108,9 +108,9 @@ public class WebClientEurekaHttpClient implements EurekaHttpClient {
|
||||
String urlPath = "apps/" + appName + '/' + id + "/status?lastDirtyTimestamp="
|
||||
+ info.getLastDirtyTimestamp().toString();
|
||||
|
||||
return webClient.delete().uri(urlPath, Void.class)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).exchange()
|
||||
.map(response -> eurekaHttpResponse(response)).block();
|
||||
return webClient.delete().uri(urlPath).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.retrieve().onStatus(HttpStatusCode::isError, this::ignoreError).toBodilessEntity()
|
||||
.map(this::eurekaHttpResponse).block();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -125,13 +125,14 @@ public class WebClientEurekaHttpClient implements EurekaHttpClient {
|
||||
url = url + (urlPath.contains("?") ? "&" : "?") + "regions=" + StringUtil.join(regions);
|
||||
}
|
||||
|
||||
ClientResponse response = webClient.get().uri(url, Applications.class)
|
||||
ResponseEntity<Applications> response = webClient.get().uri(url)
|
||||
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).exchange().block();
|
||||
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).retrieve()
|
||||
.onStatus(HttpStatusCode::isError, this::ignoreError).toEntity(Applications.class).block();
|
||||
|
||||
int statusCode = statusCodeValueOf(response);
|
||||
|
||||
Applications body = response.toEntity(Applications.class).block().getBody();
|
||||
Applications body = response.getBody();
|
||||
|
||||
return anEurekaHttpResponse(statusCode, statusCode == HttpStatus.OK.value() && body != null ? body : null)
|
||||
.headers(headersOf(response)).build();
|
||||
@@ -155,11 +156,12 @@ public class WebClientEurekaHttpClient implements EurekaHttpClient {
|
||||
@Override
|
||||
public EurekaHttpResponse<Application> getApplication(String appName) {
|
||||
|
||||
ClientResponse response = webClient.get().uri("apps/" + appName, Application.class)
|
||||
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).exchange().block();
|
||||
ResponseEntity<Application> response = webClient.get().uri("apps/" + appName)
|
||||
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).retrieve()
|
||||
.onStatus(HttpStatusCode::isError, this::ignoreError).toEntity(Application.class).block();
|
||||
|
||||
int statusCode = statusCodeValueOf(response);
|
||||
Application body = response.toEntity(Application.class).block().getBody();
|
||||
Application body = response.getBody();
|
||||
|
||||
Application application = statusCode == HttpStatus.OK.value() && body != null ? body : null;
|
||||
|
||||
@@ -177,11 +179,12 @@ public class WebClientEurekaHttpClient implements EurekaHttpClient {
|
||||
}
|
||||
|
||||
private EurekaHttpResponse<InstanceInfo> getInstanceInternal(String urlPath) {
|
||||
ClientResponse response = webClient.get().uri(urlPath, InstanceInfo.class)
|
||||
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).exchange().block();
|
||||
ResponseEntity<InstanceInfo> response = webClient.get().uri(urlPath)
|
||||
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).retrieve()
|
||||
.onStatus(HttpStatusCode::isError, this::ignoreError).toEntity(InstanceInfo.class).block();
|
||||
|
||||
int statusCode = statusCodeValueOf(response);
|
||||
InstanceInfo body = response.toEntity(InstanceInfo.class).block().getBody();
|
||||
InstanceInfo body = response.getBody();
|
||||
|
||||
return anEurekaHttpResponse(statusCode, statusCode == HttpStatus.OK.value() && body != null ? body : null)
|
||||
.headers(headersOf(response)).build();
|
||||
@@ -196,26 +199,19 @@ public class WebClientEurekaHttpClient implements EurekaHttpClient {
|
||||
return this.webClient;
|
||||
}
|
||||
|
||||
private static Map<String, String> headersOf(ClientResponse response) {
|
||||
ClientResponse.Headers httpHeaders = response.headers();
|
||||
if (httpHeaders == null) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
HttpHeaders asHeaders = httpHeaders.asHttpHeaders();
|
||||
if (asHeaders == null) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
asHeaders.entrySet().stream()
|
||||
.forEach(entry -> entry.getValue().stream().forEach(v -> headers.put(entry.getKey(), v)));
|
||||
return headers;
|
||||
private Mono<? extends Throwable> ignoreError(ClientResponse response) {
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
private int statusCodeValueOf(ClientResponse response) {
|
||||
return response.statusCode().value();
|
||||
private static Map<String, String> headersOf(ResponseEntity<?> response) {
|
||||
return response.getHeaders().toSingleValueMap();
|
||||
}
|
||||
|
||||
private EurekaHttpResponse<Void> eurekaHttpResponse(ClientResponse response) {
|
||||
private int statusCodeValueOf(ResponseEntity<?> response) {
|
||||
return response.getStatusCode().value();
|
||||
}
|
||||
|
||||
private EurekaHttpResponse<Void> eurekaHttpResponse(ResponseEntity<?> response) {
|
||||
return anEurekaHttpResponse(statusCodeValueOf(response)).headers(headersOf(response)).build();
|
||||
}
|
||||
|
||||
|
||||
+11
-4
@@ -24,7 +24,7 @@ import com.fasterxml.jackson.databind.BeanDescription;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
|
||||
import com.fasterxml.jackson.databind.SerializationConfig;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
@@ -38,6 +38,7 @@ import com.netflix.discovery.shared.Applications;
|
||||
import com.netflix.discovery.shared.resolver.EurekaEndpoint;
|
||||
import com.netflix.discovery.shared.transport.EurekaHttpClient;
|
||||
import com.netflix.discovery.shared.transport.TransportClientFactory;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
@@ -122,13 +123,13 @@ public class WebClientTransportClientFactory implements TransportClientFactory {
|
||||
* serialized or deserialized. Achieved with
|
||||
* {@link SerializationFeature#WRAP_ROOT_VALUE} and
|
||||
* {@link DeserializationFeature#UNWRAP_ROOT_VALUE}.
|
||||
* {@link PropertyNamingStrategy.SnakeCaseStrategy} is applied to the underlying
|
||||
* {@link PropertyNamingStrategies.SnakeCaseStrategy} is applied to the underlying
|
||||
* {@link ObjectMapper}.
|
||||
* @return a {@link ObjectMapper} object
|
||||
*/
|
||||
private ObjectMapper objectMapper() {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
|
||||
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
|
||||
|
||||
SimpleModule jsonModule = new SimpleModule();
|
||||
jsonModule.setSerializerModifier(createJsonSerializerModifier());
|
||||
@@ -147,10 +148,16 @@ public class WebClientTransportClientFactory implements TransportClientFactory {
|
||||
return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
|
||||
// literally 400 pass the tests, not 4xxClientError
|
||||
if (clientResponse.statusCode().value() == 400) {
|
||||
ClientResponse newResponse = ClientResponse.from(clientResponse).statusCode(HttpStatus.OK).build();
|
||||
ClientResponse newResponse = clientResponse.mutate().statusCode(HttpStatus.OK).build();
|
||||
newResponse.body((clientHttpResponse, context) -> clientHttpResponse.getBody());
|
||||
return Mono.just(newResponse);
|
||||
}
|
||||
if (clientResponse.statusCode().equals(HttpStatus.NOT_FOUND)) {
|
||||
ClientResponse newResponse = clientResponse.mutate().statusCode(clientResponse.statusCode())
|
||||
// ignore body on 404 for heartbeat, see gh-4145
|
||||
.body(Flux.empty()).build();
|
||||
return Mono.just(newResponse);
|
||||
}
|
||||
return Mono.just(clientResponse);
|
||||
});
|
||||
}
|
||||
|
||||
+3
-3
@@ -65,11 +65,11 @@ public class EurekaLoadBalancerClientConfiguration {
|
||||
|
||||
@PostConstruct
|
||||
public void postprocess() {
|
||||
if (!StringUtils.isEmpty(zoneConfig.getZone())) {
|
||||
if (StringUtils.hasText(zoneConfig.getZone())) {
|
||||
return;
|
||||
}
|
||||
String zone = getZoneFromEureka();
|
||||
if (!StringUtils.isEmpty(zone)) {
|
||||
if (StringUtils.hasText(zone)) {
|
||||
if (LOG.isDebugEnabled()) {
|
||||
LOG.debug("Setting the value of '" + LOADBALANCER_ZONE + "' to " + zone);
|
||||
}
|
||||
@@ -85,7 +85,7 @@ public class EurekaLoadBalancerClientConfiguration {
|
||||
}
|
||||
else {
|
||||
zone = eurekaConfig == null ? null : eurekaConfig.getMetadataMap().get("zone");
|
||||
if (StringUtils.isEmpty(zone) && clientConfig != null) {
|
||||
if (!StringUtils.hasText(zone) && clientConfig != null) {
|
||||
String[] zones = clientConfig.getAvailabilityZones(clientConfig.getRegion());
|
||||
// Pick the first one from the regions we want to connect to
|
||||
zone = zones != null && zones.length > 0 ? zones[0] : null;
|
||||
|
||||
+6
-6
@@ -44,17 +44,17 @@ public class EurekaAutoServiceRegistration
|
||||
|
||||
private static final Log log = LogFactory.getLog(EurekaAutoServiceRegistration.class);
|
||||
|
||||
private AtomicBoolean running = new AtomicBoolean(false);
|
||||
private final AtomicBoolean running = new AtomicBoolean(false);
|
||||
|
||||
private int order = 0;
|
||||
private final int order = 0;
|
||||
|
||||
private AtomicInteger port = new AtomicInteger(0);
|
||||
private final AtomicInteger port = new AtomicInteger(0);
|
||||
|
||||
private ApplicationContext context;
|
||||
private final ApplicationContext context;
|
||||
|
||||
private EurekaServiceRegistry serviceRegistry;
|
||||
private final EurekaServiceRegistry serviceRegistry;
|
||||
|
||||
private EurekaRegistration registration;
|
||||
private final EurekaRegistration registration;
|
||||
|
||||
public EurekaAutoServiceRegistration(ApplicationContext context, EurekaServiceRegistry serviceRegistry,
|
||||
EurekaRegistration registration) {
|
||||
|
||||
+11
-1
@@ -25,6 +25,7 @@ import com.netflix.appinfo.HealthCheckHandler;
|
||||
import com.netflix.appinfo.InstanceInfo;
|
||||
import com.netflix.discovery.EurekaClient;
|
||||
import com.netflix.discovery.EurekaClientConfig;
|
||||
import com.netflix.discovery.shared.transport.jersey.TransportClientFactories;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
@@ -181,6 +182,8 @@ public class EurekaRegistration implements Registration {
|
||||
|
||||
private ApplicationEventPublisher publisher;
|
||||
|
||||
private TransportClientFactories<?> transportClientFactories;
|
||||
|
||||
Builder(CloudEurekaInstanceConfig instanceConfig) {
|
||||
this.instanceConfig = instanceConfig;
|
||||
}
|
||||
@@ -200,6 +203,11 @@ public class EurekaRegistration implements Registration {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder with(TransportClientFactories<?> transportClientFactories) {
|
||||
this.transportClientFactories = transportClientFactories;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder with(EurekaClientConfig clientConfig, ApplicationEventPublisher publisher) {
|
||||
this.clientConfig = clientConfig;
|
||||
this.publisher = publisher;
|
||||
@@ -216,9 +224,11 @@ public class EurekaRegistration implements Registration {
|
||||
if (this.eurekaClient == null) {
|
||||
Assert.notNull(this.clientConfig, "if eurekaClient is null, EurekaClientConfig may not be null");
|
||||
Assert.notNull(this.publisher, "if eurekaClient is null, ApplicationEventPublisher may not be null");
|
||||
Assert.notNull(this.transportClientFactories,
|
||||
"if eurekaClient is null, TransportClientFactories may not be null");
|
||||
|
||||
this.eurekaClient = new CloudEurekaClient(this.applicationInfoManager, this.clientConfig,
|
||||
this.publisher);
|
||||
this.transportClientFactories, this.publisher);
|
||||
}
|
||||
return new EurekaRegistration(instanceConfig, eurekaClient, applicationInfoManager, healthCheckHandler);
|
||||
}
|
||||
|
||||
+1
@@ -86,6 +86,7 @@ public class EurekaServiceRegistry implements ServiceRegistry<EurekaRegistration
|
||||
registration.getEurekaClient().setStatus(newStatus, info);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public Object getStatus(EurekaRegistration registration) {
|
||||
String appname = registration.getApplicationInfoManager().getInfo().getAppName();
|
||||
|
||||
+7
@@ -23,6 +23,13 @@
|
||||
"name": "eureka.client.webclient.enabled",
|
||||
"description": "Enables the use of WebClient for Eureka HTTP Client.",
|
||||
"type": "java.lang.Boolean"
|
||||
},
|
||||
{
|
||||
"defaultValue": 1,
|
||||
"name": "eureka.instance.metadata-map.weight",
|
||||
"description": "The weight of service instance for weighted load balancing.",
|
||||
"type": "java.lang.Integer",
|
||||
"sourceType": "org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
org.springframework.aot.hint.RuntimeHintsRegistrar=\
|
||||
org.springframework.cloud.netflix.eureka.EurekaClientHints
|
||||
+23
-45
@@ -26,6 +26,7 @@ import com.netflix.appinfo.HealthCheckHandler;
|
||||
import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs;
|
||||
import com.netflix.discovery.EurekaClient;
|
||||
import com.netflix.discovery.EurekaClientConfig;
|
||||
import com.netflix.discovery.shared.transport.jersey.TransportClientFactories;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
@@ -37,7 +38,6 @@ import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
|
||||
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
|
||||
import org.springframework.boot.context.event.ApplicationPreparedEvent;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
@@ -47,6 +47,7 @@ import org.springframework.cloud.client.discovery.DiscoveryClient;
|
||||
import org.springframework.cloud.client.discovery.health.DiscoveryClientHealthIndicator;
|
||||
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
|
||||
import org.springframework.cloud.commons.util.UtilAutoConfiguration;
|
||||
import org.springframework.cloud.context.config.ContextRefreshedWithApplicationEvent;
|
||||
import org.springframework.cloud.context.refresh.ContextRefresher;
|
||||
import org.springframework.cloud.context.scope.GenericScope;
|
||||
import org.springframework.cloud.netflix.eureka.config.DiscoveryClientOptionalArgsConfiguration;
|
||||
@@ -73,7 +74,7 @@ import static org.assertj.core.api.AssertionsForClassTypes.fail;
|
||||
*/
|
||||
class EurekaClientAutoConfigurationTests {
|
||||
|
||||
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
|
||||
@AfterEach
|
||||
void after() {
|
||||
@@ -94,7 +95,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSetManagementPortInMetadataMapIfEqualToServerPort() throws Exception {
|
||||
void shouldSetManagementPortInMetadataMapIfEqualToServerPort() {
|
||||
TestPropertyValues.of("server.port=8989").applyTo(this.context);
|
||||
setupContext(RefreshAutoConfiguration.class);
|
||||
|
||||
@@ -104,7 +105,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotSetManagementAndJmxPortsInMetadataMap() throws Exception {
|
||||
void shouldNotSetManagementAndJmxPortsInMetadataMap() {
|
||||
TestPropertyValues.of("server.port=8989", "management.server.port=0").applyTo(this.context);
|
||||
setupContext(RefreshAutoConfiguration.class);
|
||||
|
||||
@@ -115,7 +116,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldSetManagementAndJmxPortsInMetadataMap() throws Exception {
|
||||
void shouldSetManagementAndJmxPortsInMetadataMap() {
|
||||
TestPropertyValues.of("management.server.port=9999", "com.sun.management.jmxremote.port=6789")
|
||||
.applyTo(this.context);
|
||||
setupContext(RefreshAutoConfiguration.class);
|
||||
@@ -126,7 +127,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotResetManagementAndJmxPortsInMetadataMap() throws Exception {
|
||||
void shouldNotResetManagementAndJmxPortsInMetadataMap() {
|
||||
TestPropertyValues.of("management.server.port=9999", "eureka.instance.metadata-map.jmx.port=9898",
|
||||
"eureka.instance.metadata-map.management.port=7878").applyTo(this.context);
|
||||
setupContext(RefreshAutoConfiguration.class);
|
||||
@@ -201,7 +202,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusPageUrl_and_healthCheckUrl_do_not_contain_server_context_path() throws Exception {
|
||||
void statusPageUrl_and_healthCheckUrl_do_not_contain_server_context_path() {
|
||||
TestPropertyValues.of("server.port=8989", "management.server.port=9999", "server.contextPath=/service")
|
||||
.applyTo(this.context);
|
||||
|
||||
@@ -214,7 +215,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusPageUrl_and_healthCheckUrl_contain_management_context_path() throws Exception {
|
||||
void statusPageUrl_and_healthCheckUrl_contain_management_context_path() {
|
||||
TestPropertyValues.of("server.port=8989", "management.server.servlet.context-path=/management")
|
||||
.applyTo(this.context);
|
||||
|
||||
@@ -227,7 +228,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusPageUrl_and_healthCheckUrl_contain_management_context_path_random_port() throws Exception {
|
||||
void statusPageUrl_and_healthCheckUrl_contain_management_context_path_random_port() {
|
||||
TestPropertyValues.of("server.port=0", "management.server.servlet.context-path=/management")
|
||||
.applyTo(this.context);
|
||||
|
||||
@@ -286,7 +287,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusPageUrl_and_healthCheckUrl_contain_management_base_path() throws Exception {
|
||||
void statusPageUrl_and_healthCheckUrl_contain_management_base_path() {
|
||||
TestPropertyValues.of("server.port=8989", "management.server.base-path=/management").applyTo(this.context);
|
||||
|
||||
setupContext(RefreshAutoConfiguration.class);
|
||||
@@ -298,7 +299,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusPageUrl_and_healthCheckUrl_contain_management_base_path_random_port() throws Exception {
|
||||
void statusPageUrl_and_healthCheckUrl_contain_management_base_path_random_port() {
|
||||
TestPropertyValues.of("server.port=0", "management.server.base-path=/management").applyTo(this.context);
|
||||
|
||||
setupContext(RefreshAutoConfiguration.class);
|
||||
@@ -469,9 +470,9 @@ class EurekaClientAutoConfigurationTests {
|
||||
|
||||
ContextRefresher refresher = this.context.getBean(ContextRefresher.class);
|
||||
if (refresher instanceof ApplicationListener) {
|
||||
ApplicationListener<ApplicationPreparedEvent> listener = (ApplicationListener) refresher;
|
||||
listener.onApplicationEvent(
|
||||
new ApplicationPreparedEvent(Mockito.mock(SpringApplication.class), new String[0], this.context));
|
||||
ApplicationListener<ContextRefreshedWithApplicationEvent> listener = (ApplicationListener) refresher;
|
||||
listener.onApplicationEvent(new ContextRefreshedWithApplicationEvent(Mockito.mock(SpringApplication.class),
|
||||
new String[0], this.context));
|
||||
}
|
||||
refresher.refresh();
|
||||
|
||||
@@ -500,17 +501,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void basicAuth() {
|
||||
TestPropertyValues
|
||||
.of("server.port=8989", "eureka.client.serviceUrl.defaultZone=https://user:foo@example.com:80/eureka")
|
||||
.applyTo(this.context);
|
||||
setupContext(MockClientConfiguration.class);
|
||||
// ApacheHttpClient4 http = this.context.getBean(ApacheHttpClient4.class);
|
||||
// Mockito.verify(http).addFilter(Matchers.any(HTTPBasicAuthFilter.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDefaultAppName() throws Exception {
|
||||
void testDefaultAppName() {
|
||||
setupContext();
|
||||
assertThat(getInstanceConfig().getAppname()).isEqualTo("unknown");
|
||||
assertThat(getInstanceConfig().getVirtualHostName()).isEqualTo("unknown");
|
||||
@@ -518,7 +509,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAppName() throws Exception {
|
||||
void testAppName() {
|
||||
TestPropertyValues.of("spring.application.name=mytest").applyTo(this.context);
|
||||
setupContext();
|
||||
assertThat(getInstanceConfig().getAppname()).isEqualTo("mytest");
|
||||
@@ -527,7 +518,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAppNameUpper() throws Exception {
|
||||
void testAppNameUpper() {
|
||||
addSystemEnvironment(this.context.getEnvironment(), "SPRING_APPLICATION_NAME=mytestupper");
|
||||
setupContext();
|
||||
assertThat(getInstanceConfig().getAppname()).isEqualTo("mytestupper");
|
||||
@@ -569,7 +560,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInstanceNamePreferred() throws Exception {
|
||||
void testInstanceNamePreferred() {
|
||||
addSystemEnvironment(this.context.getEnvironment(), "SPRING_APPLICATION_NAME=mytestspringappname");
|
||||
TestPropertyValues.of("eureka.instance.appname=mytesteurekaappname").applyTo(this.context);
|
||||
setupContext();
|
||||
@@ -615,6 +606,7 @@ class EurekaClientAutoConfigurationTests {
|
||||
});
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
private void assertBeanNotPresent(Class beanClass) {
|
||||
try {
|
||||
context.getBean(beanClass);
|
||||
@@ -670,8 +662,9 @@ class EurekaClientAutoConfigurationTests {
|
||||
@Bean(destroyMethod = "shutdown")
|
||||
@ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT)
|
||||
public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config,
|
||||
ApplicationContext context, AbstractDiscoveryClientOptionalArgs optionalArgs) {
|
||||
return new CloudEurekaClient(manager, config, optionalArgs, context) {
|
||||
TransportClientFactories<?> transportClientFactories, ApplicationContext context,
|
||||
AbstractDiscoveryClientOptionalArgs optionalArgs) {
|
||||
return new CloudEurekaClient(manager, config, transportClientFactories, optionalArgs, context) {
|
||||
@Override
|
||||
public synchronized void shutdown() {
|
||||
CountDownLatch latch = countDownLatch();
|
||||
@@ -685,21 +678,6 @@ class EurekaClientAutoConfigurationTests {
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
protected static class MockClientConfiguration {
|
||||
|
||||
// FIXME: 4.0
|
||||
/*
|
||||
* @Bean public EurekaJerseyClient jerseyClient() { EurekaJerseyClient mock =
|
||||
* Mockito.mock(EurekaJerseyClient.class);
|
||||
* Mockito.when(mock.getClient()).thenReturn(apacheClient()); return mock; }
|
||||
*
|
||||
* @Bean public ApacheHttpClient4 apacheClient() { return
|
||||
* Mockito.mock(ApacheHttpClient4.class); }
|
||||
*/
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableConfigurationProperties(AutoServiceRegistrationProperties.class)
|
||||
public static class AutoServiceRegistrationConfiguration {
|
||||
|
||||
+2
-2
@@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
*/
|
||||
class EurekaClientConfigBeanTests {
|
||||
|
||||
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
|
||||
@AfterEach
|
||||
void init() {
|
||||
@@ -67,7 +67,7 @@ class EurekaClientConfigBeanTests {
|
||||
void serviceUrlWithCompositePropertySource() {
|
||||
CompositePropertySource source = new CompositePropertySource("composite");
|
||||
this.context.getEnvironment().getPropertySources().addFirst(source);
|
||||
source.addPropertySource(new MapPropertySource("config", Collections.<String, Object>singletonMap(
|
||||
source.addPropertySource(new MapPropertySource("config", Collections.singletonMap(
|
||||
"eureka.client.serviceUrl.defaultZone",
|
||||
"https://example.com,https://example2.com, https://www.hugedomains.com/domain_profile.cfm?d=example3&e=com")));
|
||||
this.context.register(PropertyPlaceholderAutoConfiguration.class, TestConfiguration.class);
|
||||
|
||||
+1
-1
@@ -321,7 +321,7 @@ class EurekaHealthCheckHandlerTests {
|
||||
@Override
|
||||
public Iterator<NamedContributor<HealthContributor>> iterator() {
|
||||
Iterator<Map.Entry<String, HealthContributor>> iterator = contributorMap.entrySet().iterator();
|
||||
return new Iterator<NamedContributor<HealthContributor>>() {
|
||||
return new Iterator<>() {
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
|
||||
+9
-18
@@ -18,11 +18,9 @@ package org.springframework.cloud.netflix.eureka;
|
||||
|
||||
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.beans.factory.BeanCreationException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
@@ -46,14 +44,14 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
*/
|
||||
class EurekaInstanceConfigBeanTests {
|
||||
|
||||
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
|
||||
private String hostName;
|
||||
|
||||
private String ipAddress;
|
||||
|
||||
@BeforeEach
|
||||
void init() throws Exception {
|
||||
void init() {
|
||||
try (InetUtils utils = new InetUtils(new InetUtilsProperties())) {
|
||||
InetUtils.HostInfo hostInfo = utils.findFirstNonLoopbackHostInfo();
|
||||
this.hostName = hostInfo.getHostname();
|
||||
@@ -158,13 +156,6 @@ class EurekaInstanceConfigBeanTests {
|
||||
assertThat(getInstanceConfig().getInitialStatus()).as("initialStatus wrong").isEqualTo(InstanceStatus.UP);
|
||||
}
|
||||
|
||||
void testBadInitialStatus() {
|
||||
TestPropertyValues.of("eureka.instance.initial-status:FOO").applyTo(this.context);
|
||||
Assertions.assertThrows(BeanCreationException.class, () -> {
|
||||
setupContext();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCustomInitialStatus() {
|
||||
TestPropertyValues.of("eureka.instance.initial-status:STARTING").applyTo(this.context);
|
||||
@@ -173,7 +164,7 @@ class EurekaInstanceConfigBeanTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPreferIpAddress() throws Exception {
|
||||
void testPreferIpAddress() {
|
||||
TestPropertyValues.of("eureka.instance.preferIpAddress:true").applyTo(this.context);
|
||||
setupContext();
|
||||
EurekaInstanceConfigBean instance = getInstanceConfig();
|
||||
@@ -183,7 +174,7 @@ class EurekaInstanceConfigBeanTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDefaultVirtualHostName() throws Exception {
|
||||
void testDefaultVirtualHostName() {
|
||||
TestPropertyValues.of("spring.application.name:myapp").applyTo(this.context);
|
||||
setupContext();
|
||||
assertThat(getInstanceConfig().getVirtualHostName()).as("virtualHostName wrong").isEqualTo("myapp");
|
||||
@@ -192,7 +183,7 @@ class EurekaInstanceConfigBeanTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCustomVirtualHostName() throws Exception {
|
||||
void testCustomVirtualHostName() {
|
||||
TestPropertyValues.of("spring.application.name:myapp", "eureka.instance.virtualHostName=myvirthost",
|
||||
"eureka.instance.secureVirtualHostName=mysecurevirthost").applyTo(this.context);
|
||||
setupContext();
|
||||
@@ -203,7 +194,7 @@ class EurekaInstanceConfigBeanTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDefaultAppName() throws Exception {
|
||||
void testDefaultAppName() {
|
||||
setupContext();
|
||||
assertThat(getInstanceConfig().getAppname()).as("default app name is wrong").isEqualTo("unknown");
|
||||
assertThat(getInstanceConfig().getVirtualHostName()).as("default virtual hostname is wrong")
|
||||
@@ -213,21 +204,21 @@ class EurekaInstanceConfigBeanTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCustomInstanceId() throws Exception {
|
||||
void testCustomInstanceId() {
|
||||
TestPropertyValues.of("eureka.instance.instanceId=myinstance").applyTo(this.context);
|
||||
setupContext();
|
||||
assertThat(getInstanceConfig().getInstanceId()).as("instance id is wrong").isEqualTo("myinstance");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCustomInstanceIdWithMetadata() throws Exception {
|
||||
void testCustomInstanceIdWithMetadata() {
|
||||
TestPropertyValues.of("eureka.instance.metadataMap.instanceId=myinstance").applyTo(this.context);
|
||||
setupContext();
|
||||
assertThat(getInstanceConfig().getInstanceId()).as("instance id is wrong").isEqualTo("myinstance");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDefaultInstanceId() throws Exception {
|
||||
void testDefaultInstanceId() {
|
||||
setupContext();
|
||||
assertThat(getInstanceConfig().getInstanceId()).as("default instance id is wrong").isEqualTo(null);
|
||||
}
|
||||
|
||||
+3
-5
@@ -16,8 +16,6 @@
|
||||
|
||||
package org.springframework.cloud.netflix.eureka;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.netflix.appinfo.InstanceInfo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -34,10 +32,10 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class InstanceInfoFactoryTests {
|
||||
|
||||
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
|
||||
@Test
|
||||
void instanceIdIsHostNameByDefault() throws IOException {
|
||||
void instanceIdIsHostNameByDefault() {
|
||||
InstanceInfo instanceInfo = setupInstance();
|
||||
try (InetUtils utils = new InetUtils(new InetUtilsProperties())) {
|
||||
assertThat(instanceInfo.getId()).isEqualTo(utils.findFirstNonLoopbackHostInfo().getHostname());
|
||||
@@ -45,7 +43,7 @@ class InstanceInfoFactoryTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void instanceIdIsIpWhenIpPreferred() throws Exception {
|
||||
void instanceIdIsIpWhenIpPreferred() {
|
||||
InstanceInfo instanceInfo = setupInstance("eureka.instance.preferIpAddress:true");
|
||||
assertThat(instanceInfo.getId().matches("(\\d+\\.){3}\\d+")).isTrue();
|
||||
}
|
||||
|
||||
+5
-5
@@ -21,6 +21,7 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
import org.springframework.cloud.commons.util.UtilAutoConfiguration;
|
||||
import org.springframework.cloud.config.server.config.ConfigServerProperties;
|
||||
import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
|
||||
|
||||
@@ -35,16 +36,15 @@ class EurekaClientConfigServerAutoConfigurationTests {
|
||||
@Test
|
||||
void offByDefault() {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaClientConfigServerAutoConfiguration.class)).run(c -> {
|
||||
assertThat(c.getBeanNamesForType(EurekaInstanceConfigBean.class).length).isEqualTo(0);
|
||||
});
|
||||
.withConfiguration(AutoConfigurations.of(EurekaClientConfigServerAutoConfiguration.class))
|
||||
.run(c -> assertThat(c.getBeanNamesForType(EurekaInstanceConfigBean.class).length).isEqualTo(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onWhenRequested() {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaClientConfigServerAutoConfiguration.class,
|
||||
ConfigServerProperties.class, EurekaInstanceConfigBean.class))
|
||||
UtilAutoConfiguration.class, ConfigServerProperties.class, EurekaInstanceConfigBean.class))
|
||||
.withPropertyValues("spring.cloud.config.server.prefix=/config").run(c -> {
|
||||
assertThat(c.getBeanNamesForType(EurekaInstanceConfig.class).length).isEqualTo(1);
|
||||
EurekaInstanceConfig instance = c.getBean(EurekaInstanceConfig.class);
|
||||
@@ -56,7 +56,7 @@ class EurekaClientConfigServerAutoConfigurationTests {
|
||||
void notOverridingMetamapSettings() {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaClientConfigServerAutoConfiguration.class,
|
||||
ConfigServerProperties.class, EurekaInstanceConfigBean.class))
|
||||
UtilAutoConfiguration.class, ConfigServerProperties.class, EurekaInstanceConfigBean.class))
|
||||
.withPropertyValues("spring.cloud.config.server.prefix=/config")
|
||||
.withPropertyValues("eureka.instance.metadataMap.configPath=/differentpath").run(c -> {
|
||||
assertThat(c.getBeanNamesForType(EurekaInstanceConfig.class).length).isEqualTo(1);
|
||||
|
||||
+14
-36
@@ -63,63 +63,50 @@ public class EurekaConfigServerBootstrapConfigurationTests {
|
||||
public void offByDefault() {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaConfigServerBootstrapConfiguration.class))
|
||||
.run(context -> {
|
||||
assertEurekaBeansNotPresent(context);
|
||||
});
|
||||
.run(this::assertEurekaBeansNotPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void properBeansCreatedWhenDiscoveryEnabled() {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaConfigServerBootstrapConfiguration.class))
|
||||
.withPropertyValues("spring.cloud.config.discovery.enabled=true").run(context -> {
|
||||
assertEurekaBeansPresent(context);
|
||||
});
|
||||
.withPropertyValues("spring.cloud.config.discovery.enabled=true").run(this::assertEurekaBeansPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void beansNotCreatedWhenDiscoveryNotEnabled() {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaConfigServerBootstrapConfiguration.class))
|
||||
.withPropertyValues("spring.cloud.config.discovery.enabled=false").run(context -> {
|
||||
assertEurekaBeansNotPresent(context);
|
||||
});
|
||||
.withPropertyValues("spring.cloud.config.discovery.enabled=false")
|
||||
.run(this::assertEurekaBeansNotPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void beansNotCreatedWhenDiscoveryDisabled() {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaConfigServerBootstrapConfiguration.class))
|
||||
.withPropertyValues("spring.cloud.config.discovery.disabled").run(context -> {
|
||||
assertEurekaBeansNotPresent(context);
|
||||
});
|
||||
.withPropertyValues("spring.cloud.config.discovery.disabled").run(this::assertEurekaBeansNotPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void beansNotCreatedWhenEurekaClientEnabled() {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaConfigServerBootstrapConfiguration.class))
|
||||
.withPropertyValues("eureka.client.enabled=true").run(context -> {
|
||||
assertEurekaBeansNotPresent(context);
|
||||
});
|
||||
.withPropertyValues("eureka.client.enabled=true").run(this::assertEurekaBeansNotPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void beansNotCreatedWhenEurekaClientNotEnabled() {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaConfigServerBootstrapConfiguration.class))
|
||||
.withPropertyValues("eureka.client.enabled=false").run(context -> {
|
||||
assertEurekaBeansNotPresent(context);
|
||||
});
|
||||
.withPropertyValues("eureka.client.enabled=false").run(this::assertEurekaBeansNotPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void beansNotCreatedWhenEurekaClientDisabled() {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaConfigServerBootstrapConfiguration.class))
|
||||
.withPropertyValues("eureka.client.disabled").run(context -> {
|
||||
assertEurekaBeansNotPresent(context);
|
||||
});
|
||||
.withPropertyValues("eureka.client.disabled").run(this::assertEurekaBeansNotPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -127,9 +114,7 @@ public class EurekaConfigServerBootstrapConfigurationTests {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaConfigServerBootstrapConfiguration.class))
|
||||
.withPropertyValues("spring.cloud.config.discovery.enabled=true", "eureka.client.enabled=true")
|
||||
.run(context -> {
|
||||
assertEurekaBeansPresent(context);
|
||||
});
|
||||
.run(this::assertEurekaBeansPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -137,9 +122,7 @@ public class EurekaConfigServerBootstrapConfigurationTests {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaConfigServerBootstrapConfiguration.class))
|
||||
.withPropertyValues("spring.cloud.config.discovery.enabled=true", "eureka.client.enabled=false")
|
||||
.run(context -> {
|
||||
assertEurekaBeansNotPresent(context);
|
||||
});
|
||||
.run(this::assertEurekaBeansNotPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -147,9 +130,7 @@ public class EurekaConfigServerBootstrapConfigurationTests {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaConfigServerBootstrapConfiguration.class))
|
||||
.withPropertyValues("spring.cloud.config.discovery.enabled=false", "eureka.client.enabled=true")
|
||||
.run(context -> {
|
||||
assertEurekaBeansNotPresent(context);
|
||||
});
|
||||
.run(this::assertEurekaBeansNotPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -157,9 +138,7 @@ public class EurekaConfigServerBootstrapConfigurationTests {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(EurekaConfigServerBootstrapConfiguration.class))
|
||||
.withPropertyValues("spring.cloud.config.discovery.enabled=false", "eureka.client.enabled=false")
|
||||
.run(context -> {
|
||||
assertEurekaBeansNotPresent(context);
|
||||
});
|
||||
.run(this::assertEurekaBeansNotPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -171,9 +150,8 @@ public class EurekaConfigServerBootstrapConfigurationTests {
|
||||
"eureka.client.use-dns-for-fetching-service-urls=true",
|
||||
"eureka.client.eureka-server-d-n-s-name=myeurekahost",
|
||||
"eureka.client.eureka-server-u-r-l-context=eureka", "eureka.client.eureka-server-port=30000")
|
||||
.run(context -> {
|
||||
assertThat(output).contains("Cannot get cnames bound to the region:txt.us-east-1.myeurekahost");
|
||||
});
|
||||
.run(context -> assertThat(output)
|
||||
.contains("Cannot get cnames bound to the region:txt.us-east-1.myeurekahost"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+8
-10
@@ -24,9 +24,10 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.cloud.netflix.eureka.http.WebClientEurekaHttpClient;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.reactive.function.client.ClientResponse;
|
||||
@@ -61,20 +62,17 @@ class EurekaConfigServerBootstrapConfigurationWebClientIntegrationTests {
|
||||
@SpringBootConfiguration
|
||||
@EnableAutoConfiguration
|
||||
@RestController
|
||||
static class WebClientController extends WebSecurityConfigurerAdapter {
|
||||
static class WebClientController {
|
||||
|
||||
@GetMapping("/")
|
||||
public String hello() {
|
||||
StringBuilder s = new StringBuilder();
|
||||
for (int i = 0; i < 300000; i++) {
|
||||
s.append(".");
|
||||
}
|
||||
return s.toString();
|
||||
return ".".repeat(300000);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests().anyRequest().permitAll().and().csrf().disable();
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http.authorizeHttpRequests().anyRequest().permitAll().and().csrf().disable();
|
||||
return http.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
/*
|
||||
* Copyright 2013-2023 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.netflix.eureka.config;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.BeanDescription;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationConfig;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
|
||||
import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase;
|
||||
import com.netflix.appinfo.InstanceInfo;
|
||||
import com.netflix.discovery.converters.jackson.serializer.InstanceInfoJsonBeanSerializer;
|
||||
import com.netflix.discovery.shared.Application;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockserver.client.MockServerClient;
|
||||
import org.testcontainers.containers.MockServerContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
|
||||
import org.springframework.boot.SpringBootConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.cloud.config.environment.Environment;
|
||||
import org.springframework.cloud.config.environment.PropertySource;
|
||||
import org.springframework.cloud.netflix.eureka.http.EurekaApplications;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockserver.model.HttpRequest.request;
|
||||
import static org.mockserver.model.HttpResponse.response;
|
||||
|
||||
/**
|
||||
* @author Ryan Baxter
|
||||
*/
|
||||
@Testcontainers
|
||||
public class EurekaConfigServerBootstrapperIT {
|
||||
|
||||
public static final DockerImageName MOCKSERVER_IMAGE = DockerImageName.parse("mockserver/mockserver")
|
||||
.withTag("mockserver-" + MockServerClient.class.getPackage().getImplementationVersion());
|
||||
|
||||
@Container
|
||||
static MockServerContainer mockServer = new MockServerContainer(MOCKSERVER_IMAGE);
|
||||
|
||||
private ConfigurableApplicationContext context;
|
||||
|
||||
@BeforeEach
|
||||
void before() {
|
||||
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void after() {
|
||||
this.context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws JsonProcessingException {
|
||||
Environment environment = new Environment("test", "default");
|
||||
Map<String, Object> properties = new HashMap<>();
|
||||
properties.put("hello", "world");
|
||||
PropertySource p = new PropertySource("p1", properties);
|
||||
environment.add(p);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
SimpleModule jsonModule = new SimpleModule();
|
||||
jsonModule.setSerializerModifier(createJsonSerializerModifier());
|
||||
objectMapper.registerModule(jsonModule);
|
||||
try (MockServerClient mockServerClient = new MockServerClient(mockServer.getHost(),
|
||||
mockServer.getMappedPort(MockServerContainer.PORT))) {
|
||||
mockServerClient.when(request().withPath("/application/default"))
|
||||
.respond(response().withBody(objectMapper.writeValueAsString(environment))
|
||||
.withHeader("content-type", "application/json"));
|
||||
InstanceInfo configServerInstanceInfo = InstanceInfo.Builder.newBuilder()
|
||||
.setVIPAddress("eureka-configserver").setInstanceId("eureka-configserver")
|
||||
.setAppName("eureka-configserver").setStatus(InstanceInfo.InstanceStatus.UP)
|
||||
.enablePort(InstanceInfo.PortType.UNSECURE, true).setHostName("localhost")
|
||||
.setPort(mockServer.getMappedPort(MockServerContainer.PORT)).build();
|
||||
Application configServer = new Application("eureka-configserver",
|
||||
Collections.singletonList(configServerInstanceInfo));
|
||||
EurekaApplications eurekaApplications = new EurekaApplications("hashcode", 0L,
|
||||
Collections.singletonList(configServer));
|
||||
mockServerClient.when(request().withPath("/apps/"))
|
||||
.respond(response()
|
||||
.withBody("{\"applications\":" + objectMapper.writeValueAsString(eurekaApplications) + "}")
|
||||
.withHeader("content-type", "application/json"));
|
||||
this.context = setup().run();
|
||||
assertThat(this.context.getEnvironment().getProperty("hello")).isEqualTo("world");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static BeanSerializerModifier createJsonSerializerModifier() {
|
||||
return new BeanSerializerModifier() {
|
||||
@Override
|
||||
public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc,
|
||||
JsonSerializer<?> serializer) {
|
||||
if (beanDesc.getBeanClass().isAssignableFrom(InstanceInfo.class)) {
|
||||
return new InstanceInfoJsonBeanSerializer((BeanSerializerBase) serializer, false);
|
||||
}
|
||||
return serializer;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
SpringApplicationBuilder setup(String... env) {
|
||||
SpringApplicationBuilder builder = new SpringApplicationBuilder(TestConfig.class)
|
||||
.properties(addDefaultEnv(env));
|
||||
return builder;
|
||||
}
|
||||
|
||||
private String[] addDefaultEnv(String[] env) {
|
||||
Set<String> set = new LinkedHashSet<>();
|
||||
if (env != null && env.length > 0) {
|
||||
set.addAll(Arrays.asList(env));
|
||||
}
|
||||
set.add("spring.config.import=classpath:bootstrapper.yaml");
|
||||
set.add("spring.cloud.config.enabled=true");
|
||||
set.add("spring.cloud.service-registry.auto-registration.enabled=false");
|
||||
set.add("eureka.client.serviceUrl.defaultZone=http://" + mockServer.getHost() + ":"
|
||||
+ mockServer.getMappedPort(MockServerContainer.PORT));
|
||||
return set.toArray(new String[0]);
|
||||
}
|
||||
|
||||
@SpringBootConfiguration
|
||||
@EnableAutoConfiguration
|
||||
static class TestConfig {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+19
-5
@@ -16,16 +16,21 @@
|
||||
|
||||
package org.springframework.cloud.netflix.eureka.config;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.boot.SpringBootConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.boot.context.properties.bind.BindHandler;
|
||||
import org.springframework.boot.context.properties.bind.Binder;
|
||||
import org.springframework.cloud.config.client.ConfigClientProperties;
|
||||
import org.springframework.cloud.config.client.ConfigServerInstanceProvider;
|
||||
import org.springframework.web.client.ResourceAccessException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
class EurekaConfigServerBootstrapperTests {
|
||||
|
||||
@@ -48,7 +53,10 @@ class EurekaConfigServerBootstrapperTests {
|
||||
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
|
||||
ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext()
|
||||
.get(ConfigServerInstanceProvider.Function.class);
|
||||
assertThat(providerFn.apply("id")).as("Should return empty list").isEmpty();
|
||||
Binder binder = event.getBootstrapContext().get(Binder.class);
|
||||
BindHandler bindHandler = event.getBootstrapContext().get(BindHandler.class);
|
||||
assertThat(providerFn.apply("id", binder, bindHandler, mock(Log.class)))
|
||||
.as("Should return empty list").isEmpty();
|
||||
})).run().close();
|
||||
}
|
||||
|
||||
@@ -60,19 +68,25 @@ class EurekaConfigServerBootstrapperTests {
|
||||
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
|
||||
ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext()
|
||||
.get(ConfigServerInstanceProvider.Function.class);
|
||||
assertThat(providerFn.apply("id")).as("Should return empty list").isEmpty();
|
||||
Binder binder = event.getBootstrapContext().get(Binder.class);
|
||||
BindHandler bindHandler = event.getBootstrapContext().get(BindHandler.class);
|
||||
assertThat(providerFn.apply("id", binder, bindHandler, mock(Log.class)))
|
||||
.as("Should return empty list").isEmpty();
|
||||
})).run().close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void enabledAddsInstanceProviderFn() {
|
||||
new SpringApplicationBuilder(TestConfig.class)
|
||||
.properties("spring.cloud.config.discovery.enabled=true",
|
||||
"spring.cloud.service-registry.auto-registration.enabled=false")
|
||||
.properties("spring.config.import: classpath:bootstrapper.yaml",
|
||||
ConfigClientProperties.PREFIX + ".enabled=true")
|
||||
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
|
||||
ConfigServerInstanceProvider.Function providerFn = event.getBootstrapContext()
|
||||
.get(ConfigServerInstanceProvider.Function.class);
|
||||
assertThatThrownBy(() -> providerFn.apply("id")).isInstanceOf(ResourceAccessException.class)
|
||||
Binder binder = event.getBootstrapContext().get(Binder.class);
|
||||
BindHandler bindHandler = event.getBootstrapContext().get(BindHandler.class);
|
||||
assertThatThrownBy(() -> providerFn.apply("id", binder, bindHandler, mock(Log.class)))
|
||||
.isInstanceOf(ResourceAccessException.class)
|
||||
.hasMessageContaining("I/O error on GET request for \"http://localhost:8761/eureka/apps/\"")
|
||||
.as("Should have tried to connect to Eureka to fetch instances.");
|
||||
})).run().close();
|
||||
|
||||
-1
@@ -40,7 +40,6 @@ import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
|
||||
public class EurekaHttpClientsOptionalArgsConfigurationNoWebfluxTest {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void contextFailsWithoutWebClient() {
|
||||
|
||||
ConfigurableApplicationContext ctx = null;
|
||||
|
||||
+7
-5
@@ -16,14 +16,17 @@
|
||||
|
||||
package org.springframework.cloud.netflix.eureka.config;
|
||||
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.cloud.netflix.eureka.sample.EurekaSampleApplication;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Daniel Lavoie
|
||||
*/
|
||||
@@ -31,13 +34,12 @@ import org.springframework.test.annotation.DirtiesContext;
|
||||
@SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
class JerseyOptionalArgsConfigurationTest {
|
||||
|
||||
// @Autowired
|
||||
// private DiscoveryClientOptionalArgs optionalArgs;
|
||||
@Autowired
|
||||
private AbstractDiscoveryClientOptionalArgs optionalArgs;
|
||||
|
||||
@Test
|
||||
@Disabled // FIXME: 4.0.0
|
||||
void contextLoads() {
|
||||
// assertThat(optionalArgs).isNotNull();
|
||||
assertThat(optionalArgs).isNotNull();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+11
-5
@@ -19,7 +19,7 @@ package org.springframework.cloud.netflix.eureka.http;
|
||||
import com.netflix.appinfo.InstanceInfo;
|
||||
import com.netflix.discovery.shared.Applications;
|
||||
import com.netflix.discovery.shared.transport.EurekaHttpClient;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
@@ -29,7 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
/**
|
||||
* @author Haytham Mohamed
|
||||
**/
|
||||
abstract class AbstractEurekaHttpClientTest {
|
||||
abstract class AbstractEurekaHttpClientTests {
|
||||
|
||||
protected EurekaHttpClient eurekaHttpClient;
|
||||
|
||||
@@ -49,8 +49,9 @@ abstract class AbstractEurekaHttpClientTest {
|
||||
|
||||
@Test
|
||||
void testSendHeartBeat() {
|
||||
assertThat(eurekaHttpClient.sendHeartBeat("test", "test", info, null).getStatusCode())
|
||||
.isEqualTo(HttpStatus.OK.value());
|
||||
EurekaHttpResponse<InstanceInfo> response = eurekaHttpClient.sendHeartBeat("test", "test", info, null);
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK.value());
|
||||
assertThat(response.getEntity()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -59,6 +60,12 @@ abstract class AbstractEurekaHttpClientTest {
|
||||
.isEqualTo(HttpStatus.NOT_FOUND.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendHeartBeatFourOFourWithBody() {
|
||||
assertThat(eurekaHttpClient.sendHeartBeat("fourOFourWithBody", "test", info, null).getStatusCode())
|
||||
.isEqualTo(HttpStatus.NOT_FOUND.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStatusUpdate() {
|
||||
assertThat(eurekaHttpClient.statusUpdate("test", "test", InstanceInfo.InstanceStatus.UP, info).getStatusCode())
|
||||
@@ -72,7 +79,6 @@ abstract class AbstractEurekaHttpClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled // FIXME: 4.0
|
||||
void testGetApplications() {
|
||||
Applications entity = eurekaHttpClient.getApplications().getEntity();
|
||||
assertThat(entity).isNotNull();
|
||||
+23
-16
@@ -35,16 +35,17 @@ import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
@@ -60,6 +61,7 @@ import static org.springframework.util.Assert.isTrue;
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@RestController
|
||||
@RequestMapping("/eureka")
|
||||
@SpringBootApplication
|
||||
public class EurekaServerMockApplication {
|
||||
|
||||
@@ -116,6 +118,11 @@ public class EurekaServerMockApplication {
|
||||
if ("fourOFour".equals(appName)) {
|
||||
return new ResponseEntity(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
if ("fourOFourWithBody".equals(appName)) {
|
||||
return new ResponseEntity(
|
||||
"{ \"error\": \"Not Found\", \"message\": null, \"path\": \"/1\", \"requestId\": \"9e5d3244-1\", \"status\": 404, \"timestamp\": \"2023-03-04T03:31:20.810+00:00\" }",
|
||||
HttpStatus.NOT_FOUND);
|
||||
}
|
||||
return new ResponseEntity<>(new InstanceInfo(null, null, null, null, null, null, null, null, null, null, null,
|
||||
null, null, 0, null, null, null, null, null, null, null, new HashMap<>(), 0L, 0L, null, null),
|
||||
HttpStatus.OK);
|
||||
@@ -135,7 +142,7 @@ public class EurekaServerMockApplication {
|
||||
|
||||
}
|
||||
|
||||
@GetMapping({ "/apps", "/apps/delta", "/vips/{address}", "/svips/{address}" })
|
||||
@GetMapping({ "/apps/", "/apps/delta", "/vips/{address}", "/svips/{address}" })
|
||||
public Applications getApplications(@PathVariable(required = false) String address,
|
||||
@RequestParam(required = false) String regions) {
|
||||
Applications applications = new Applications();
|
||||
@@ -155,23 +162,23 @@ public class EurekaServerMockApplication {
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
protected static class TestSecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
protected static class TestSecurityConfiguration {
|
||||
|
||||
TestSecurityConfiguration() {
|
||||
super(true);
|
||||
@Bean
|
||||
public InMemoryUserDetailsManager userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("test").password("test").roles("USER")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public UserDetailsService userDetailsService() {
|
||||
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
|
||||
manager.createUser(User.withUsername("test").password("{noop}test").roles("USER").build());
|
||||
return manager;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// super.configure(http);
|
||||
http.antMatcher("/apps/**").httpBasic();
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.securityMatcher("/v2/apps/**")
|
||||
.httpBasic();
|
||||
// @formatter:on
|
||||
return http.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+24
-3
@@ -16,9 +16,12 @@
|
||||
|
||||
package org.springframework.cloud.netflix.eureka.http;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider;
|
||||
import com.netflix.discovery.shared.resolver.DefaultEndpoint;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
@@ -26,20 +29,27 @@ import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.cloud.commons.util.InetUtils;
|
||||
import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
|
||||
import org.springframework.http.client.ClientHttpRequestInterceptor;
|
||||
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Daniel Lavoie
|
||||
*/
|
||||
@SpringBootTest(classes = EurekaServerMockApplication.class,
|
||||
properties = { "debug=true", "security.basic.enabled=true" }, webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
properties = { "debug=true", "security.basic.enabled=true", "eureka.client.fetch-registry=false",
|
||||
"eureka.client.register-with-eureka=false", "logging.level.org.springframework=INFO" },
|
||||
webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
@DirtiesContext
|
||||
class RestTemplateEurekaHttpClientTest extends AbstractEurekaHttpClientTest {
|
||||
class RestTemplateEurekaHttpClientTests extends AbstractEurekaHttpClientTests {
|
||||
|
||||
@Autowired
|
||||
private InetUtils inetUtils;
|
||||
|
||||
@Value("http://${security.user.name}:${security.user.password}@localhost:${local.server.port}")
|
||||
@Value("http://${security.user.name}:${security.user.password}@localhost:${local.server.port}/eureka")
|
||||
private String serviceUrl;
|
||||
|
||||
@BeforeEach
|
||||
@@ -61,4 +71,15 @@ class RestTemplateEurekaHttpClientTest extends AbstractEurekaHttpClientTest {
|
||||
info = new EurekaConfigBasedInstanceInfoProvider(config).get();
|
||||
}
|
||||
|
||||
@Test
|
||||
void basicAuth() {
|
||||
assertThat(eurekaHttpClient).isInstanceOf(RestTemplateEurekaHttpClient.class);
|
||||
RestTemplateEurekaHttpClient restTemplateEurekaHttpClient = (RestTemplateEurekaHttpClient) eurekaHttpClient;
|
||||
RestTemplate restTemplate = restTemplateEurekaHttpClient.getRestTemplate();
|
||||
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
|
||||
boolean hasBasicAuth = interceptors.stream()
|
||||
.anyMatch(interceptor -> interceptor instanceof BasicAuthenticationInterceptor);
|
||||
assertThat(hasBasicAuth).as("Basic Auth not configured").isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
+4
-3
@@ -33,15 +33,16 @@ import org.springframework.web.reactive.function.client.WebClient;
|
||||
* @author Daniel Lavoie
|
||||
*/
|
||||
@SpringBootTest(classes = EurekaServerMockApplication.class,
|
||||
properties = { "debug=true", "security.basic.enabled=true", "eureka.client.webclient.enabled=true" },
|
||||
properties = { "debug=true", "security.basic.enabled=true", "eureka.client.webclient.enabled=true",
|
||||
"eureka.client.fetch-registry=false", "eureka.client.register-with-eureka=false" },
|
||||
webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
@DirtiesContext
|
||||
class WebClientEurekaHttpClientTest extends AbstractEurekaHttpClientTest {
|
||||
class WebClientEurekaHttpClientTests extends AbstractEurekaHttpClientTests {
|
||||
|
||||
@Autowired
|
||||
private InetUtils inetUtils;
|
||||
|
||||
@Value("http://${security.user.name}:${security.user.password}@localhost:${local.server.port}")
|
||||
@Value("http://${security.user.name}:${security.user.password}@localhost:${local.server.port}/eureka/")
|
||||
private String serviceUrl;
|
||||
|
||||
@BeforeEach
|
||||
+5
-5
@@ -35,16 +35,16 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
*/
|
||||
class EurekaLoadBalancerClientConfigurationTests {
|
||||
|
||||
private EurekaClientConfigBean eurekaClientConfig = new EurekaClientConfigBean();
|
||||
private final EurekaClientConfigBean eurekaClientConfig = new EurekaClientConfigBean();
|
||||
|
||||
private EurekaInstanceConfigBean eurekaInstanceConfig = new EurekaInstanceConfigBean(
|
||||
private final EurekaInstanceConfigBean eurekaInstanceConfig = new EurekaInstanceConfigBean(
|
||||
new InetUtils(new InetUtilsProperties()));
|
||||
|
||||
private LoadBalancerZoneConfig zoneConfig = new LoadBalancerZoneConfig(null);
|
||||
private final LoadBalancerZoneConfig zoneConfig = new LoadBalancerZoneConfig(null);
|
||||
|
||||
private EurekaLoadBalancerProperties eurekaLoadBalancerProperties = new EurekaLoadBalancerProperties();
|
||||
private final EurekaLoadBalancerProperties eurekaLoadBalancerProperties = new EurekaLoadBalancerProperties();
|
||||
|
||||
private EurekaLoadBalancerClientConfiguration postprocessor = new EurekaLoadBalancerClientConfiguration(
|
||||
private final EurekaLoadBalancerClientConfiguration postprocessor = new EurekaLoadBalancerClientConfiguration(
|
||||
eurekaClientConfig, eurekaInstanceConfig, zoneConfig, eurekaLoadBalancerProperties);
|
||||
|
||||
@Test
|
||||
|
||||
+12
-12
@@ -33,7 +33,7 @@ class DefaultManagementMetadataProviderTest {
|
||||
private final ManagementMetadataProvider provider = new DefaultManagementMetadataProvider();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
void setUp() {
|
||||
when(INSTANCE.getHostname()).thenReturn("host");
|
||||
when(INSTANCE.getHealthCheckUrlPath()).thenReturn("health");
|
||||
when(INSTANCE.getStatusPageUrlPath()).thenReturn("info");
|
||||
@@ -41,7 +41,7 @@ class DefaultManagementMetadataProviderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverPortIsRandomAndManagementPortIsNull() throws Exception {
|
||||
void serverPortIsRandomAndManagementPortIsNull() {
|
||||
int serverPort = 0;
|
||||
String serverContextPath = "/";
|
||||
String managementContextPath = null;
|
||||
@@ -53,7 +53,7 @@ class DefaultManagementMetadataProviderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void managementPortIsRandom() throws Exception {
|
||||
void managementPortIsRandom() {
|
||||
int serverPort = 0;
|
||||
String serverContextPath = "/";
|
||||
String managementContextPath = null;
|
||||
@@ -65,7 +65,7 @@ class DefaultManagementMetadataProviderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverPort() throws Exception {
|
||||
void serverPort() {
|
||||
int serverPort = 7777;
|
||||
String serverContextPath = "/";
|
||||
String managementContextPath = null;
|
||||
@@ -80,7 +80,7 @@ class DefaultManagementMetadataProviderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverPortManagementPort() throws Exception {
|
||||
void serverPortManagementPort() {
|
||||
int serverPort = 7777;
|
||||
String serverContextPath = "/";
|
||||
String managementContextPath = null;
|
||||
@@ -95,7 +95,7 @@ class DefaultManagementMetadataProviderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverPortManagementPortServerContextPath() throws Exception {
|
||||
void serverPortManagementPortServerContextPath() {
|
||||
int serverPort = 7777;
|
||||
String serverContextPath = "/Server";
|
||||
String managementContextPath = null;
|
||||
@@ -110,7 +110,7 @@ class DefaultManagementMetadataProviderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverPortManagementPortServerContextPathManagementContextPath() throws Exception {
|
||||
void serverPortManagementPortServerContextPathManagementContextPath() {
|
||||
int serverPort = 7777;
|
||||
String serverContextPath = "/Server";
|
||||
String managementContextPath = "/Management";
|
||||
@@ -125,7 +125,7 @@ class DefaultManagementMetadataProviderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverPortServerContextPathManagementContextPath() throws Exception {
|
||||
void serverPortServerContextPathManagementContextPath() {
|
||||
int serverPort = 7777;
|
||||
String serverContextPath = "/Server";
|
||||
String managementContextPath = "/Management";
|
||||
@@ -140,7 +140,7 @@ class DefaultManagementMetadataProviderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverPortManagementContextPath() throws Exception {
|
||||
void serverPortManagementContextPath() {
|
||||
int serverPort = 7777;
|
||||
String serverContextPath = "/";
|
||||
String managementContextPath = "/Management";
|
||||
@@ -155,7 +155,7 @@ class DefaultManagementMetadataProviderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverPortServerContextPath() throws Exception {
|
||||
void serverPortServerContextPath() {
|
||||
int serverPort = 7777;
|
||||
String serverContextPath = "/Server";
|
||||
String managementContextPath = null;
|
||||
@@ -170,7 +170,7 @@ class DefaultManagementMetadataProviderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverPortManagementPortManagementContextPath() throws Exception {
|
||||
void serverPortManagementPortManagementContextPath() {
|
||||
int serverPort = 7777;
|
||||
String serverContextPath = "/";
|
||||
String managementContextPath = "/Management";
|
||||
@@ -186,7 +186,7 @@ class DefaultManagementMetadataProviderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void setSecureHealthCheckUrl() throws Exception {
|
||||
void setSecureHealthCheckUrl() {
|
||||
int serverPort = 7777;
|
||||
String serverContextPath = "/";
|
||||
String managementContextPath = "/Management";
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
*/
|
||||
class EurekaReactiveDiscoveryClientConfigurationTests {
|
||||
|
||||
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
|
||||
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class,
|
||||
ReactiveCommonsClientAutoConfiguration.class, EurekaClientAutoConfiguration.class,
|
||||
DiscoveryClientOptionalArgsConfiguration.class, EurekaReactiveDiscoveryClientConfiguration.class));
|
||||
|
||||
-4
@@ -18,7 +18,6 @@ package org.springframework.cloud.netflix.eureka.reactive;
|
||||
|
||||
import com.netflix.appinfo.InstanceInfo;
|
||||
import com.netflix.discovery.EurekaClient;
|
||||
import com.netflix.discovery.EurekaClientConfig;
|
||||
import com.netflix.discovery.shared.Application;
|
||||
import com.netflix.discovery.shared.Applications;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -47,9 +46,6 @@ class EurekaReactiveDiscoveryClientTests {
|
||||
@Mock
|
||||
private EurekaClient eurekaClient;
|
||||
|
||||
@Mock
|
||||
private EurekaClientConfig clientConfig;
|
||||
|
||||
@InjectMocks
|
||||
private EurekaReactiveDiscoveryClient client;
|
||||
|
||||
|
||||
+1
-2
@@ -17,7 +17,6 @@
|
||||
package org.springframework.cloud.netflix.eureka.sample;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
|
||||
import com.netflix.appinfo.HealthCheckHandler;
|
||||
import com.netflix.appinfo.InstanceInfo;
|
||||
@@ -103,7 +102,7 @@ public class EurekaSampleApplication implements ApplicationContextAware, Closeab
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
public void close() {
|
||||
deregister();
|
||||
}
|
||||
|
||||
|
||||
+2
@@ -62,6 +62,7 @@ class EurekaServiceRegistryTests {
|
||||
verifyNoInteractions(eurekaClient);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
void eurekaClientGetStatus() {
|
||||
EurekaServiceRegistry registry = new EurekaServiceRegistry();
|
||||
@@ -98,6 +99,7 @@ class EurekaServiceRegistryTests {
|
||||
OUT_OF_SERVICE.toString());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
void eurekaClientGetStatusNoInstance() {
|
||||
EurekaServiceRegistry registry = new EurekaServiceRegistry();
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
spring:
|
||||
config:
|
||||
import: "optional:configserver:"
|
||||
cloud:
|
||||
config:
|
||||
enabled: true
|
||||
discovery:
|
||||
service-id: eureka-configserver
|
||||
enabled: true
|
||||
service-registry:
|
||||
auto-registration:
|
||||
enabled: false
|
||||
@@ -5,7 +5,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-netflix</artifactId>
|
||||
<version>4.0.0-SNAPSHOT</version>
|
||||
<version>4.1.0-SNAPSHOT</version>
|
||||
<relativePath>..</relativePath> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<artifactId>spring-cloud-netflix-eureka-server</artifactId>
|
||||
|
||||
+1
-1
@@ -65,7 +65,7 @@ public class CloudJacksonJson extends LegacyJacksonJson {
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> String encode(T object) throws IOException {
|
||||
public <T> String encode(T object) {
|
||||
return this.codec.writeToString(object);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -56,7 +56,7 @@ public class EurekaController {
|
||||
@Value("${eureka.dashboard.path:/}")
|
||||
private String dashboardPath = "";
|
||||
|
||||
private ApplicationInfoManager applicationInfoManager;
|
||||
private final ApplicationInfoManager applicationInfoManager;
|
||||
|
||||
private final EurekaProperties eurekaProperties;
|
||||
|
||||
|
||||
+117
-24
@@ -17,28 +17,41 @@
|
||||
package org.springframework.cloud.netflix.eureka.server;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.netflix.appinfo.ApplicationInfoManager;
|
||||
import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs;
|
||||
import com.netflix.discovery.EurekaClient;
|
||||
import com.netflix.discovery.EurekaClientConfig;
|
||||
import com.netflix.discovery.Jersey3DiscoveryClientOptionalArgs;
|
||||
import com.netflix.discovery.converters.EurekaJacksonCodec;
|
||||
import com.netflix.discovery.converters.wrappers.CodecWrapper;
|
||||
import com.netflix.discovery.converters.wrappers.CodecWrappers;
|
||||
import com.netflix.discovery.shared.transport.EurekaHttpClient;
|
||||
import com.netflix.discovery.shared.transport.jersey.TransportClientFactories;
|
||||
import com.netflix.discovery.shared.transport.jersey3.EurekaIdentityHeaderFilter;
|
||||
import com.netflix.discovery.shared.transport.jersey3.EurekaJersey3Client;
|
||||
import com.netflix.discovery.shared.transport.jersey3.EurekaJersey3ClientImpl;
|
||||
import com.netflix.discovery.shared.transport.jersey3.Jersey3TransportClientFactories;
|
||||
import com.netflix.eureka.DefaultEurekaServerContext;
|
||||
import com.netflix.eureka.EurekaServerConfig;
|
||||
import com.netflix.eureka.EurekaServerContext;
|
||||
import com.netflix.eureka.EurekaServerIdentity;
|
||||
import com.netflix.eureka.cluster.PeerEurekaNode;
|
||||
import com.netflix.eureka.cluster.PeerEurekaNodes;
|
||||
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
|
||||
import com.netflix.eureka.resources.DefaultServerCodecs;
|
||||
import com.netflix.eureka.resources.ServerCodecs;
|
||||
import com.netflix.eureka.transport.EurekaServerHttpClientFactory;
|
||||
import com.netflix.eureka.transport.Jersey3DynamicGZIPContentEncodingFilter;
|
||||
import com.netflix.eureka.transport.Jersey3EurekaServerHttpClientFactory;
|
||||
import com.netflix.eureka.transport.Jersey3ReplicationClient;
|
||||
import jakarta.servlet.Filter;
|
||||
import jakarta.servlet.FilterChain;
|
||||
@@ -47,8 +60,12 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletRequestWrapper;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.client.Client;
|
||||
import jakarta.ws.rs.client.ClientRequestFilter;
|
||||
import jakarta.ws.rs.core.Application;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.glassfish.hk2.api.ServiceLocator;
|
||||
import org.glassfish.jersey.server.ResourceConfig;
|
||||
import org.glassfish.jersey.server.spi.Container;
|
||||
@@ -71,7 +88,6 @@ import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.cloud.client.actuator.HasFeatures;
|
||||
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
|
||||
import org.springframework.cloud.netflix.eureka.EurekaConstants;
|
||||
import org.springframework.cloud.netflix.eureka.config.HostnameBasedUrlRandomizer;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
|
||||
@@ -101,6 +117,8 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
@PropertySource("classpath:/eureka/server.properties")
|
||||
public class EurekaServerAutoConfiguration implements WebMvcConfigurer {
|
||||
|
||||
private static final Log log = LogFactory.getLog(EurekaServerAutoConfiguration.class);
|
||||
|
||||
/**
|
||||
* List of packages containing Jersey resources required by the Eureka server.
|
||||
*/
|
||||
@@ -162,7 +180,6 @@ public class EurekaServerAutoConfiguration implements WebMvcConfigurer {
|
||||
return codec == null ? CodecWrappers.getCodec(CodecWrappers.XStreamXml.class) : codec;
|
||||
}
|
||||
|
||||
// FIXME: 4.0
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public ReplicationClientAdditionalFilters replicationClientAdditionalFilters() {
|
||||
@@ -170,24 +187,31 @@ public class EurekaServerAutoConfiguration implements WebMvcConfigurer {
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(TransportClientFactories.class)
|
||||
public Jersey3TransportClientFactories jersey3TransportClientFactories() {
|
||||
return Jersey3TransportClientFactories.getInstance();
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
@Bean
|
||||
public EurekaHttpClient eurekaHttpClient(TransportClientFactories transportClientFactories, Environment env) {
|
||||
return transportClientFactories
|
||||
.newTransportClientFactory(this.eurekaClientConfig, Collections.emptyList(),
|
||||
this.applicationInfoManager.getInfo())
|
||||
.newClient(HostnameBasedUrlRandomizer.randomEndpoint(this.eurekaClientConfig, env));
|
||||
@ConditionalOnMissingBean(EurekaServerHttpClientFactory.class)
|
||||
public Jersey3EurekaServerHttpClientFactory jersey3EurekaServerHttpClientFactory() {
|
||||
return new Jersey3EurekaServerHttpClientFactory();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(AbstractDiscoveryClientOptionalArgs.class)
|
||||
public Jersey3DiscoveryClientOptionalArgs jersey3DiscoveryClientOptionalArgs() {
|
||||
return new Jersey3DiscoveryClientOptionalArgs();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PeerAwareInstanceRegistry peerAwareInstanceRegistry(ServerCodecs serverCodecs,
|
||||
EurekaHttpClient eurekaHttpClient) {
|
||||
EurekaServerHttpClientFactory eurekaServerHttpClientFactory) {
|
||||
this.eurekaClient.getApplications(); // force initialization
|
||||
return new InstanceRegistry(this.eurekaServerConfig, this.eurekaClientConfig, serverCodecs, this.eurekaClient,
|
||||
eurekaHttpClient, this.instanceRegistryProperties.getExpectedNumberOfClientsSendingRenews(),
|
||||
eurekaServerHttpClientFactory,
|
||||
this.instanceRegistryProperties.getExpectedNumberOfClientsSendingRenews(),
|
||||
this.instanceRegistryProperties.getDefaultOpenForTrafficCount());
|
||||
}
|
||||
|
||||
@@ -231,12 +255,15 @@ public class EurekaServerAutoConfiguration implements WebMvcConfigurer {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<?> eurekaVersionFilterRegistration(ServerProperties serverProperties) {
|
||||
String contextPath = serverProperties.getServlet().getContextPath();
|
||||
public FilterRegistrationBean<?> eurekaVersionFilterRegistration(ServerProperties serverProperties,
|
||||
Environment env) {
|
||||
final String contextPath = serverProperties.getServlet().getContextPath();
|
||||
String regex = EurekaConstants.DEFAULT_PREFIX + STATIC_CONTENT_PATTERN;
|
||||
if (StringUtils.hasText(contextPath)) {
|
||||
regex = contextPath + regex;
|
||||
}
|
||||
String debugResponseHeader = env.getProperty("eureka.server.version.filter.debug.response-header");
|
||||
boolean addDebugResponseHeader = StringUtils.hasText(debugResponseHeader);
|
||||
Pattern staticPattern = Pattern.compile(regex);
|
||||
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
|
||||
bean.setFilter(new OncePerRequestFilter() {
|
||||
@@ -249,18 +276,29 @@ public class EurekaServerAutoConfiguration implements WebMvcConfigurer {
|
||||
// don't forward static requests (images, js, etc...) to /v2
|
||||
&& !staticPattern.matcher(requestURI).matches()) {
|
||||
|
||||
String updatedPath = EurekaConstants.DEFAULT_PREFIX + "/v2"
|
||||
+ requestURI.substring(EurekaConstants.DEFAULT_PREFIX.length());
|
||||
|
||||
String prefix = EurekaConstants.DEFAULT_PREFIX;
|
||||
if (StringUtils.hasText(contextPath)) {
|
||||
prefix = contextPath + prefix;
|
||||
}
|
||||
String updatedPath = EurekaConstants.DEFAULT_PREFIX + "/v2" + requestURI.substring(prefix.length());
|
||||
if (StringUtils.hasText(contextPath)) {
|
||||
updatedPath = contextPath + updatedPath;
|
||||
}
|
||||
final String computedPath = updatedPath;
|
||||
// only used if a special debug property is set, so in prod this is
|
||||
// always skipped.
|
||||
if (addDebugResponseHeader) {
|
||||
response.addHeader(debugResponseHeader, computedPath);
|
||||
}
|
||||
HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
|
||||
@Override
|
||||
public String getRequestURI() {
|
||||
return updatedPath;
|
||||
return computedPath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getServletPath() {
|
||||
return updatedPath;
|
||||
return computedPath;
|
||||
}
|
||||
};
|
||||
req = wrapper;
|
||||
@@ -337,7 +375,7 @@ public class EurekaServerAutoConfiguration implements WebMvcConfigurer {
|
||||
@Bean
|
||||
@ConditionalOnBean(name = "httpTraceFilter")
|
||||
public FilterRegistrationBean<?> traceFilterRegistration(@Qualifier("httpTraceFilter") Filter filter) {
|
||||
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<Filter>();
|
||||
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
|
||||
bean.setFilter(filter);
|
||||
bean.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
|
||||
return bean;
|
||||
@@ -374,7 +412,7 @@ public class EurekaServerAutoConfiguration implements WebMvcConfigurer {
|
||||
static class RefreshablePeerEurekaNodes extends PeerEurekaNodes
|
||||
implements ApplicationListener<EnvironmentChangeEvent> {
|
||||
|
||||
private ReplicationClientAdditionalFilters replicationClientAdditionalFilters;
|
||||
/* for testing */ ReplicationClientAdditionalFilters replicationClientAdditionalFilters;
|
||||
|
||||
RefreshablePeerEurekaNodes(final PeerAwareInstanceRegistry registry, final EurekaServerConfig serverConfig,
|
||||
final EurekaClientConfig clientConfig, final ServerCodecs serverCodecs,
|
||||
@@ -386,11 +424,8 @@ public class EurekaServerAutoConfiguration implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
protected PeerEurekaNode createPeerEurekaNode(String peerEurekaNodeUrl) {
|
||||
Jersey3ReplicationClient replicationClient = Jersey3ReplicationClient.createReplicationClient(serverConfig,
|
||||
serverCodecs, peerEurekaNodeUrl);
|
||||
|
||||
// FIXME: 4.0
|
||||
// this.replicationClientAdditionalFilters.getFilters().forEach(replicationClient::addReplicationClientFilter);
|
||||
Jersey3ReplicationClient replicationClient = createReplicationClient(serverConfig, serverCodecs,
|
||||
peerEurekaNodeUrl, this.replicationClientAdditionalFilters.getFilters());
|
||||
|
||||
String targetHost = hostFromUrl(peerEurekaNodeUrl);
|
||||
if (targetHost == null) {
|
||||
@@ -399,6 +434,64 @@ public class EurekaServerAutoConfiguration implements WebMvcConfigurer {
|
||||
return new PeerEurekaNode(registry, targetHost, peerEurekaNodeUrl, replicationClient, serverConfig);
|
||||
}
|
||||
|
||||
// FIXME: 4.0 update Jersey3ReplicationClient.createReplicationClient to handle
|
||||
// additional filters
|
||||
private static Jersey3ReplicationClient createReplicationClient(EurekaServerConfig config,
|
||||
ServerCodecs serverCodecs, String serviceUrl, Collection<ClientRequestFilter> additionalFilters) {
|
||||
String name = Jersey3ReplicationClient.class.getSimpleName() + ": " + serviceUrl + "apps/: ";
|
||||
|
||||
EurekaJersey3Client jerseyClient;
|
||||
try {
|
||||
String hostname;
|
||||
try {
|
||||
hostname = new URL(serviceUrl).getHost();
|
||||
}
|
||||
catch (MalformedURLException e) {
|
||||
hostname = serviceUrl;
|
||||
}
|
||||
|
||||
String jerseyClientName = "Discovery-PeerNodeClient-" + hostname;
|
||||
EurekaJersey3ClientImpl.EurekaJersey3ClientBuilder clientBuilder = new EurekaJersey3ClientImpl.EurekaJersey3ClientBuilder()
|
||||
.withClientName(jerseyClientName).withUserAgent("Java-EurekaClient-Replication")
|
||||
.withEncoderWrapper(serverCodecs.getFullJsonCodec())
|
||||
.withDecoderWrapper(serverCodecs.getFullJsonCodec())
|
||||
.withConnectionTimeout(config.getPeerNodeConnectTimeoutMs())
|
||||
.withReadTimeout(config.getPeerNodeReadTimeoutMs())
|
||||
.withMaxConnectionsPerHost(config.getPeerNodeTotalConnectionsPerHost())
|
||||
.withMaxTotalConnections(config.getPeerNodeTotalConnections())
|
||||
.withConnectionIdleTimeout(config.getPeerNodeConnectionIdleTimeoutSeconds());
|
||||
|
||||
if (serviceUrl.startsWith("https://") && "true"
|
||||
.equals(System.getProperty("com.netflix.eureka.shouldSSLConnectionsUseSystemSocketFactory"))) {
|
||||
clientBuilder.withSystemSSLConfiguration();
|
||||
}
|
||||
jerseyClient = clientBuilder.build();
|
||||
}
|
||||
catch (Throwable e) {
|
||||
throw new RuntimeException("Cannot Create new Replica Node :" + name, e);
|
||||
}
|
||||
|
||||
String ip = null;
|
||||
try {
|
||||
ip = InetAddress.getLocalHost().getHostAddress();
|
||||
}
|
||||
catch (UnknownHostException e) {
|
||||
log.warn("Cannot find localhost ip", e);
|
||||
}
|
||||
|
||||
Client jerseyApacheClient = jerseyClient.getClient();
|
||||
jerseyApacheClient.register(new Jersey3DynamicGZIPContentEncodingFilter(config));
|
||||
|
||||
for (ClientRequestFilter filter : additionalFilters) {
|
||||
jerseyApacheClient.register(filter);
|
||||
}
|
||||
|
||||
EurekaServerIdentity identity = new EurekaServerIdentity(ip);
|
||||
jerseyApacheClient.register(new EurekaIdentityHeaderFilter(identity));
|
||||
|
||||
return new Jersey3ReplicationClient(jerseyClient, serviceUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(final EnvironmentChangeEvent event) {
|
||||
if (shouldUpdate(event.getKeys())) {
|
||||
|
||||
+5
-5
@@ -1049,11 +1049,11 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
|
||||
registrySyncRetryWaitMs, remoteRegionAppWhitelist, remoteRegionConnectTimeoutMs,
|
||||
remoteRegionConnectionIdleTimeoutSeconds, remoteRegionFetchThreadPoolSize, remoteRegionReadTimeoutMs,
|
||||
remoteRegionRegistryFetchInterval, remoteRegionTotalConnections, remoteRegionTotalConnectionsPerHost,
|
||||
remoteRegionTrustStore, remoteRegionTrustStorePassword, remoteRegionUrls, remoteRegionUrlsWithName,
|
||||
renewalPercentThreshold, renewalThresholdUpdateIntervalMs, responseCacheAutoExpirationInSeconds,
|
||||
responseCacheUpdateIntervalMs, retentionTimeInMSInDeltaQueue, route53BindRebindRetries,
|
||||
route53BindingRetryIntervalMs, route53DomainTTL, syncWhenTimestampDiffers, useReadOnlyResponseCache,
|
||||
waitTimeInMsWhenSyncEmpty, xmlCodecName, initialCapacityOfResponseCache,
|
||||
remoteRegionTrustStore, remoteRegionTrustStorePassword, Arrays.hashCode(remoteRegionUrls),
|
||||
remoteRegionUrlsWithName, renewalPercentThreshold, renewalThresholdUpdateIntervalMs,
|
||||
responseCacheAutoExpirationInSeconds, responseCacheUpdateIntervalMs, retentionTimeInMSInDeltaQueue,
|
||||
route53BindRebindRetries, route53BindingRetryIntervalMs, route53DomainTTL, syncWhenTimestampDiffers,
|
||||
useReadOnlyResponseCache, waitTimeInMsWhenSyncEmpty, xmlCodecName, initialCapacityOfResponseCache,
|
||||
expectedClientRenewalIntervalSeconds, useAwsAsgApi, myUrl);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ public class EurekaServerInitializerConfiguration implements ServletContextAware
|
||||
|
||||
private boolean running;
|
||||
|
||||
private int order = 1;
|
||||
private final int order = 1;
|
||||
|
||||
@Override
|
||||
public void setServletContext(ServletContext servletContext) {
|
||||
|
||||
+5
-5
@@ -21,11 +21,11 @@ import com.netflix.appinfo.InstanceInfo;
|
||||
import com.netflix.discovery.EurekaClient;
|
||||
import com.netflix.discovery.EurekaClientConfig;
|
||||
import com.netflix.discovery.shared.Application;
|
||||
import com.netflix.discovery.shared.transport.EurekaHttpClient;
|
||||
import com.netflix.eureka.EurekaServerConfig;
|
||||
import com.netflix.eureka.lease.Lease;
|
||||
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl;
|
||||
import com.netflix.eureka.resources.ServerCodecs;
|
||||
import com.netflix.eureka.transport.EurekaServerHttpClientFactory;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
@@ -46,12 +46,12 @@ public class InstanceRegistry extends PeerAwareInstanceRegistryImpl implements A
|
||||
|
||||
private ApplicationContext ctxt;
|
||||
|
||||
private int defaultOpenForTrafficCount;
|
||||
private final int defaultOpenForTrafficCount;
|
||||
|
||||
public InstanceRegistry(EurekaServerConfig serverConfig, EurekaClientConfig clientConfig, ServerCodecs serverCodecs,
|
||||
EurekaClient eurekaClient, EurekaHttpClient eurekaHttpClient, int expectedNumberOfClientsSendingRenews,
|
||||
int defaultOpenForTrafficCount) {
|
||||
super(serverConfig, clientConfig, serverCodecs, eurekaClient, eurekaHttpClient);
|
||||
EurekaClient eurekaClient, EurekaServerHttpClientFactory eurekaServerHttpClientFactory,
|
||||
int expectedNumberOfClientsSendingRenews, int defaultOpenForTrafficCount) {
|
||||
super(serverConfig, clientConfig, serverCodecs, eurekaClient, eurekaServerHttpClientFactory);
|
||||
|
||||
this.expectedNumberOfClientsSendingRenews = expectedNumberOfClientsSendingRenews;
|
||||
this.defaultOpenForTrafficCount = defaultOpenForTrafficCount;
|
||||
|
||||
+4
-5
@@ -19,21 +19,20 @@ package org.springframework.cloud.netflix.eureka.server;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashSet;
|
||||
|
||||
// FIXME: 4.0
|
||||
//import com.sun.jersey.api.client.filter.ClientFilter;
|
||||
import jakarta.ws.rs.client.ClientRequestFilter;
|
||||
|
||||
/**
|
||||
* @author Yuxin Bai
|
||||
*/
|
||||
public class ReplicationClientAdditionalFilters {
|
||||
|
||||
private Collection<?> filters;
|
||||
private final Collection<ClientRequestFilter> filters;
|
||||
|
||||
public ReplicationClientAdditionalFilters(Collection<?> filters) {
|
||||
public ReplicationClientAdditionalFilters(Collection<ClientRequestFilter> filters) {
|
||||
this.filters = new LinkedHashSet<>(filters);
|
||||
}
|
||||
|
||||
public Collection<?> getFilters() {
|
||||
public Collection<ClientRequestFilter> getFilters() {
|
||||
return this.filters;
|
||||
}
|
||||
|
||||
|
||||
+4
-1
@@ -40,7 +40,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
properties = { "spring.application.name=eureka", "server.servlet.context-path=/context",
|
||||
"management.security.enabled=false", "management.endpoints.web.exposure.include=*" })
|
||||
"management.security.enabled=false", "management.endpoints.web.exposure.include=*",
|
||||
"eureka.server.version.filter.debug.response-header=X-Version-Filter-Computed-Path" })
|
||||
class ApplicationContextTests {
|
||||
|
||||
private static final String BASE_PATH = new WebEndpointProperties().getBasePath();
|
||||
@@ -54,6 +55,8 @@ class ApplicationContextTests {
|
||||
ResponseEntity<Map> entity = new TestRestTemplate()
|
||||
.getForEntity("http://localhost:" + this.port + "/context/eureka/apps", Map.class);
|
||||
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
String computedPath = entity.getHeaders().getFirst("X-Version-Filter-Computed-Path");
|
||||
assertThat(computedPath).isEqualTo("/context/eureka/v2/apps");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+4
-4
@@ -52,7 +52,7 @@ class EurekaControllerReplicasTests {
|
||||
|
||||
String totalNoAutoList = combinationNoAuthList1 + "," + combinationNoAuthList2;
|
||||
|
||||
String empty = new String();
|
||||
String empty = "";
|
||||
|
||||
private ApplicationInfoManager original;
|
||||
|
||||
@@ -72,7 +72,7 @@ class EurekaControllerReplicasTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFilterReplicasNoAuth() throws Exception {
|
||||
void testFilterReplicasNoAuth() {
|
||||
Map<String, Object> model = new HashMap<>();
|
||||
StatusInfo statusInfo = StatusInfo.Builder.newBuilder().add("registered-replicas", empty)
|
||||
.add("available-replicas", noAuthList1).add("unavailable-replicas", noAuthList2)
|
||||
@@ -90,7 +90,7 @@ class EurekaControllerReplicasTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFilterReplicasAuth() throws Exception {
|
||||
void testFilterReplicasAuth() {
|
||||
Map<String, Object> model = new HashMap<>();
|
||||
StatusInfo statusInfo = StatusInfo.Builder.newBuilder().add("registered-replicas", authList2)
|
||||
.add("available-replicas", authList1).add("unavailable-replicas", empty).withInstanceInfo(instanceInfo)
|
||||
@@ -108,7 +108,7 @@ class EurekaControllerReplicasTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFilterReplicasAuthWithCombinationList() throws Exception {
|
||||
void testFilterReplicasAuthWithCombinationList() {
|
||||
Map<String, Object> model = new HashMap<>();
|
||||
StatusInfo statusInfo = StatusInfo.Builder.newBuilder().add("registered-replicas", totalAutoList)
|
||||
.add("available-replicas", combinationAuthList1).add("unavailable-replicas", combinationAuthList2)
|
||||
|
||||
+1
-1
@@ -93,7 +93,7 @@ class EurekaControllerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStatus() throws Exception {
|
||||
void testStatus() {
|
||||
Map<String, Object> model = new HashMap<>();
|
||||
|
||||
EurekaController controller = new EurekaController(infoManager, new EurekaProperties());
|
||||
|
||||
+4
-4
@@ -71,7 +71,7 @@ class InstanceRegistryTests {
|
||||
private TestEvents testEvents;
|
||||
|
||||
@Test
|
||||
void testRegister() throws Exception {
|
||||
void testRegister() {
|
||||
// creating instance info
|
||||
final LeaseInfo leaseInfo = getLeaseInfo();
|
||||
final InstanceInfo instanceInfo = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, leaseInfo);
|
||||
@@ -90,7 +90,7 @@ class InstanceRegistryTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDefaultLeaseDurationRegisterEvent() throws Exception {
|
||||
void testDefaultLeaseDurationRegisterEvent() {
|
||||
// creating instance info
|
||||
final InstanceInfo instanceInfo = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, null);
|
||||
// calling tested method
|
||||
@@ -102,7 +102,7 @@ class InstanceRegistryTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInternalCancel() throws Exception {
|
||||
void testInternalCancel() {
|
||||
// calling tested method
|
||||
instanceRegistry.internalCancel(APP_NAME, HOST_NAME, false);
|
||||
// event of proper type is registered
|
||||
@@ -118,7 +118,7 @@ class InstanceRegistryTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRenew() throws Exception {
|
||||
void testRenew() {
|
||||
// Creating two instances of the app
|
||||
final InstanceInfo instanceInfo1 = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, null);
|
||||
final InstanceInfo instanceInfo2 = getInstanceInfo(APP_NAME, HOST_NAME, "my-host-name:8009", 8009, null);
|
||||
|
||||
+24
-24
@@ -16,16 +16,20 @@
|
||||
|
||||
package org.springframework.cloud.netflix.eureka.server;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Collections;
|
||||
|
||||
import com.netflix.eureka.cluster.PeerEurekaNodes;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import jakarta.ws.rs.client.ClientRequestContext;
|
||||
import jakarta.ws.rs.client.ClientRequestFilter;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.cloud.netflix.eureka.server.EurekaServerAutoConfiguration.RefreshablePeerEurekaNodes;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
@@ -34,7 +38,6 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
/**
|
||||
* @author Yuxin Bai
|
||||
*/
|
||||
@Disabled // FIXME: 4.0
|
||||
@SpringBootTest(classes = RefreshablePeerEurekaNodesWithCustomFiltersTests.Application.class,
|
||||
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, value = { "spring.application.name=eureka",
|
||||
"server.contextPath=/context", "management.security.enabled=false" })
|
||||
@@ -47,16 +50,13 @@ class RefreshablePeerEurekaNodesWithCustomFiltersTests {
|
||||
void testCustomPeerNodesShouldTakePrecedenceOverDefault() {
|
||||
assertThat(peerEurekaNodes instanceof RefreshablePeerEurekaNodes)
|
||||
.as("PeerEurekaNodes should be an instance of RefreshablePeerEurekaNodes").isTrue();
|
||||
RefreshablePeerEurekaNodes refreshablePeerEurekaNodes = (RefreshablePeerEurekaNodes) peerEurekaNodes;
|
||||
|
||||
ReplicationClientAdditionalFilters filters = getField(RefreshablePeerEurekaNodes.class,
|
||||
(RefreshablePeerEurekaNodes) peerEurekaNodes, "replicationClientAdditionalFilters");
|
||||
// assertThat(filters.getFilters())
|
||||
// .as("PeerEurekaNodes'should have only one filter set on
|
||||
// replicationClientAdditionalFilters").hasSize(1);
|
||||
// assertThat(filters.getFilters().iterator().next() instanceof
|
||||
// Application.CustomClientFilter)
|
||||
// .as("The type of the filter should be CustomClientFilter as user declared
|
||||
// so").isTrue();
|
||||
ReplicationClientAdditionalFilters filters = refreshablePeerEurekaNodes.replicationClientAdditionalFilters;
|
||||
assertThat(filters.getFilters())
|
||||
.as("PeerEurekaNodes'should have only one filter set on replicationClientAdditionalFilters").hasSize(1);
|
||||
assertThat(filters.getFilters().iterator().next() instanceof Application.CustomClientFilter)
|
||||
.as("The type of the filter should be CustomClientFilter as user declared so").isTrue();
|
||||
}
|
||||
|
||||
private static <T, R> R getField(Class<T> clazz, T target, String fieldName) {
|
||||
@@ -72,19 +72,19 @@ class RefreshablePeerEurekaNodesWithCustomFiltersTests {
|
||||
@EnableEurekaServer
|
||||
protected static class Application {
|
||||
|
||||
// FIXME: 4.0
|
||||
/*
|
||||
* @Bean public ReplicationClientAdditionalFilters customFilters() { return new
|
||||
* ReplicationClientAdditionalFilters(Collections.singletonList(new
|
||||
* CustomClientFilter())); }
|
||||
*
|
||||
* protected class CustomClientFilter extends ClientFilter {
|
||||
*
|
||||
* @Override public ClientResponse handle(ClientRequest cr) throws
|
||||
* ClientHandlerException { return getNext().handle(cr); }
|
||||
*
|
||||
* }
|
||||
*/
|
||||
@Bean
|
||||
public ReplicationClientAdditionalFilters customFilters() {
|
||||
return new ReplicationClientAdditionalFilters(Collections.singletonList(new CustomClientFilter()));
|
||||
}
|
||||
|
||||
protected class CustomClientFilter implements ClientRequestFilter {
|
||||
|
||||
@Override
|
||||
public void filter(ClientRequestContext requestContext) throws IOException {
|
||||
// noop
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-netflix</artifactId>
|
||||
<version>4.0.0-SNAPSHOT</version>
|
||||
<version>4.1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
|
||||
<name>Spring Cloud Starter Netflix Eureka Client</name>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-netflix</artifactId>
|
||||
<version>4.0.0-SNAPSHOT</version>
|
||||
<version>4.1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
|
||||
<name>Spring Cloud Starter Netflix Eureka Server</name>
|
||||
|
||||
Reference in New Issue
Block a user