Initial commit

This commit is contained in:
spencergibb
2023-09-13 16:12:34 -04:00
parent d5913b08ff
commit d345e92bc3
254 changed files with 504 additions and 24497 deletions

View File

@@ -1,18 +0,0 @@
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
[*]
indent_style = tab
indent_size = 4
end_of_line = lf
insert_final_newline = true
[*.yml]
indent_style = space
indent_size = 2
[*.yaml]
indent_style = space
indent_size = 2

View File

@@ -1,45 +0,0 @@
# Contributing
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
[Contributor License Agreement](https://cla.pivotal.io/sign/spring).
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 [code of
conduct](https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report
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
[Spring Cloud Build](https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml) project. If using IntelliJ, you can use the
[Eclipse Code Formatter Plugin](https://plugins.jetbrains.com/plugin/6546) to import the same file.
* Make sure all new `.java` files to have a simple Javadoc class comment with at least an
`@author` tag identifying you, and preferably at least a paragraph on what the class is
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 [these conventions](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html),
if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit
message (where XXXX is the issue number).

View File

@@ -1,20 +0,0 @@
<!--
Thanks for raising a Spring Cloud issue. What sort of issue are you raising?
Question
Please ask questions about how to use something, or to understand why something isn't
working as you expect it to, on Stack Overflow using the spring-cloud tag.
Bug report
Please provide details of the problem, including the version of Spring Cloud that you
are using. If possible, please provide a test case or sample application that reproduces
the problem. This makes it much easier for us to diagnose the problem and to verify that
we have fixed it.
Enhancement
Please start by describing the problem that you are trying to solve. There may already
be a solution, or there may be a way to solve it that you hadn't considered.
-->

View File

@@ -1,17 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
Please provide details of the problem, including the version of Spring Cloud that you
are using.
**Sample**
If possible, please provide a test case or sample application that reproduces
the problem. This makes it much easier for us to diagnose the problem and to verify that
we have fixed it.

View File

@@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

53
.github/workflows/deploy-docs.yml vendored Normal file
View File

@@ -0,0 +1,53 @@
name: Deploy Docs
run-name: ${{ format('{0} ({1})', github.workflow, github.event.inputs.build-refname || 'all') }}
on:
workflow_dispatch:
inputs:
build-refname:
description: Enter git refname to build (e.g., 5.7.x).
required: false
push:
branches: docs-build
env:
GRADLE_ENTERPRISE_SECRET_ACCESS_KEY: ${{ secrets.GRADLE_ENTERPRISE_SECRET_ACCESS_KEY }}
permissions:
contents: write
jobs:
build:
if: github.repository_owner == 'spring-cloud'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 5
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
- name: Set up refname build
if: github.event.inputs.build-refname
run: |
git fetch --depth 1 https://github.com/$GITHUB_REPOSITORY ${{ github.event.inputs.build-refname }}
export BUILD_REFNAME=${{ github.event.inputs.build-refname }}
echo "BUILD_REFNAME=$BUILD_REFNAME" >> $GITHUB_ENV
export BUILD_VERSION=$(git cat-file --textconv FETCH_HEAD:pom.xml | python3 -c "import xml.etree.ElementTree as xml; from sys import stdin; print(xml.parse(stdin).getroot().find('{http://maven.apache.org/POM/4.0.0}version').text)")
echo BUILD_VERSION=$BUILD_VERSION >> $GITHUB_ENV
- name: Run Antora
run: |
./mvnw --no-transfer-progress -B antora
- name: Publish Docs
uses: spring-io/spring-doc-actions/rsync-antora-reference@v0.0.11
with:
docs-username: ${{ secrets.DOCS_USERNAME }}
docs-host: ${{ secrets.DOCS_HOST }}
docs-ssh-key: ${{ secrets.DOCS_SSH_KEY }}
docs-ssh-host-key: ${{ secrets.DOCS_SSH_HOST_KEY }}
site-path: target/antora/site
- name: Bust Cloudflare Cache
uses: spring-io/spring-doc-actions/bust-cloudflare-antora-cache@v0.0.11
with:
context-root: spring-cloud-consul
cloudflare-zone-id: ${{ secrets.CLOUDFLARE_ZONE_ID }}
cloudflare-cache-token: ${{ secrets.CLOUDFLARE_CACHE_TOKEN }}

View File

@@ -1,37 +0,0 @@
# This workflow will build a Java project with Maven
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Build
on:
push:
branches: [ main, 3.1.x ]
pull_request:
branches: [ main, 3.1.x ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK
uses: actions/setup-java@v2
with:
distribution: 'temurin'
java-version: '17'
- name: Cache local Maven repository
uses: actions/cache@v2
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Build with Maven
run: ./mvnw clean install -B -U -Pspring -Dmaven.test.redirectTestOutputToFile=true
- name: Publish Test Report
uses: mikepenz/action-junit-report@v2
if: always() # always run even if the previous step fails
with:
report_paths: '**/surefire-reports/TEST-*.xml'

36
.gitignore vendored
View File

@@ -1,20 +1,22 @@
*~
#*
*#
.#*
.classpath
.project
.settings/
.springBeans
target/
_site/
.idea
.settings/
.project
.classpath
*.orig
.springBeans
.factorypath
.sts4-cache
.ant-targets-build.xml
src/ant/.ant-targets-upload-dist.xml
*.sonar4clipse*
.DS_Store
*.iml
*.ipr
.factorypath
*.swp
/consul
consul_*.zip
consul_*.zip.*
.vscode/
.flattened-pom.xml
*.iws
/.idea/
*.graphml
node
node_modules
build
package.json
package-lock.json

View File

@@ -1 +0,0 @@
-DaltSnapshotDeploymentRepository=repo.spring.io::default::https://repo.spring.io/libs-snapshot-local -P spring

206
.mvn/wrapper/MavenWrapperDownloader.java vendored Executable file → Normal file
View File

@@ -1,117 +1,117 @@
/*
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.
*/
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
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.2/maven-wrapper-0.4.2.jar";
private static final String WRAPPER_VERSION = "0.5.6";
/**
* 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/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".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 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";
/**
* 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";
/**
* 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());
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);
// 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);
}
}
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + 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();
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
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
.mvn/wrapper/maven-wrapper.jar vendored Executable file → Normal file

Binary file not shown.

3
.mvn/wrapper/maven-wrapper.properties vendored Executable file → Normal file
View File

@@ -1 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

View File

@@ -1,3 +0,0 @@
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=17.0.1-tem

View File

@@ -1,62 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<settings>
<servers>
<server>
<id>repo.spring.io</id>
<username>${env.CI_DEPLOY_USERNAME}</username>
<password>${env.CI_DEPLOY_PASSWORD}</password>
</server>
</servers>
<profiles>
<profile>
<id>spring</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-snapshot-local</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/release</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-snapshot-local</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
</settings>

View File

View File

@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@@ -1,596 +1,23 @@
////
DO NOT EDIT THIS FILE. IT WAS GENERATED.
Manual changes to this file will be lost when it is generated again.
Edit the files in the src/main/asciidoc/ directory instead.
////
= Spring Cloud Consul Docs Build
You're currently viewing the Antora playbook branch.
The playbook branch hosts the docs build that is used to build and publish the production docs site.
image::https://circleci.com/gh/spring-cloud/spring-cloud-consul/tree/master.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-consul/tree/master"]
image::https://codecov.io/gh/spring-cloud/spring-cloud-consul/branch/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-consul/branch/master"]
The Spring Cloud Consul reference docs are built using https://antora.org[Antora].
This README covers how to build the docs in a software branch as well as how to build the production docs site locally.
This project provides Consul 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 Consul based components. The
patterns provided include Service Discovery, Control Bus and Configuration.
Intelligent Routing and Client Side Load Balancing, Circuit Breaker
are provided by integration with other Spring Cloud projects.
== Building the Site
You can build the entire site by invoking the following on the docs-build branch and then viewing the site at `target/site/index.html`
== Quick Start
This quick start walks through using Spring Cloud Consul for Service Discovery and Distributed Configuration.
First, run Consul Agent on your machine. Then you can access it and use it as a Service Registry and Configuration source with Spring Cloud Consul.
=== Discovery Client Usage
To use these features in an application, you can build it as a Spring Boot application that depends on `spring-cloud-consul-core`.
The most convenient way to add the dependency is with a Spring Boot starter: `org.springframework.cloud:spring-cloud-starter-consul-discovery`.
We recommend using dependency management and `spring-boot-starter-parent`.
The following example shows a typical Maven configuration:
[source,xml,indent=0]
.pom.xml
[source,bash]
----
<project>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>{spring-boot-version}</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
./mvnw antora
----
The following example shows a typical Gradle setup:
== Building a Specific Branch
[source,groovy,indent=0]
.build.gradle
[source,bash]
----
plugins {
id 'org.springframework.boot' version ${spring-boot-version}
id 'io.spring.dependency-management' version ${spring-dependency-management-version}
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-consul-discovery'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
./mvnw antora
----
Now you can create a standard Spring Boot application, such as the following HTTP server:
----
@SpringBootApplication
@RestController
public class Application {
@GetMapping("/")
public String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
----
When this HTTP server runs, it connects to Consul Agent running at the default local 8500 port.
To modify the startup behavior, you can change the location of Consul Agent by using `application.properties`, as shown in the following example:
----
spring:
cloud:
consul:
host: localhost
port: 8500
----
You can now use `DiscoveryClient`, `@LoadBalanced RestTemplate`, or `@LoadBalanced WebClient.Builder` to retrieve services and instances data from Consul, as shown in the following example:
[source,java,indent=0]
----
@Autowired
private DiscoveryClient discoveryClient;
public String serviceUrl() {
List<ServiceInstance> list = discoveryClient.getInstances("STORES");
if (list != null && list.size() > 0 ) {
return list.get(0).getUri().toString();
}
return null;
}
----
=== Distributed Configuration Usage
To use these features in an application, you can build it as a Spring Boot application that depends on `spring-cloud-consul-core` and `spring-cloud-consul-config`.
The most convenient way to add the dependency is with a Spring Boot starter: `org.springframework.cloud:spring-cloud-starter-consul-config`.
We recommend using dependency management and `spring-boot-starter-parent`.
The following example shows a typical Maven configuration:
[source,xml,indent=0]
.pom.xml
----
<project>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>{spring-boot-version}</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
----
The following example shows a typical Gradle setup:
[source,groovy,indent=0]
.build.gradle
----
plugins {
id 'org.springframework.boot' version ${spring-boot-version}
id 'io.spring.dependency-management' version ${spring-dependency-management-version}
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-consul-config'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
----
Now you can create a standard Spring Boot application, such as the following HTTP server:
----
@SpringBootApplication
@RestController
public class Application {
@GetMapping("/")
public String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
----
The application retrieves configuration data from Consul.
WARNING: If you use Spring Cloud Consul Config, you need to set the `spring.config.import` property in order to bind to Consul.
You can read more about it in the <<config-data-import,Spring Boot Config Data Import section>>.
== Consul overview
Features of Consul
* Distributed configuration
* Service registration and discovery
* Distributed events
* Distributed locking and sessions
* Supports multiple data centers
* Built in, user-friendly user interface
See the https://consul.io/intro/index.html[intro] for more information.
== Spring Cloud Consul Features
* Spring Cloud `DiscoveryClient` implementation
** supports Spring Cloud Gateway
** supports Spring Cloud LoadBalancer
* Consul based `PropertySource` loaded during the 'bootstrap' phase.
* Spring Cloud Bus implementation based on Consul https://www.consul.io/docs/agent/http/event.html[events]
== Running the sample
1. Run `docker-compose up`
2. Verify consul is running by visiting http://localhost:8500
3. Run `mvn package` this will bring in the required spring cloud maven repositories and build
4. Run `java -jar spring-cloud-consul-sample/target/spring-cloud-consul-sample-${VERSION}.jar`
5. visit http://localhost:8080, verify that `{"serviceId":"<yourhost>:8080","host":"<yourhost>","port":8080}` results
6. run `java -jar spring-cloud-consul-sample/target/spring-cloud-consul-sample-${VERSION}.jar --server.port=8081`
7. visit http://localhost:8080 again, verify that `{"serviceId":"<yourhost>:8081","host":"<yourhost>","port":8081}` eventually shows up in the results in a round robbin fashion (may take a minute or so).
== 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.
== Contributing
:spring-cloud-build-branch: master
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>
----

View File

@@ -1,5 +0,0 @@
# Security Policy
## Reporting a Vulnerability
To report security vulnerabilities, please go to https://pivotal.io/security.

View File

@@ -6,38 +6,39 @@ antora:
- '@antora/collector-extension'
- '@antora/atlas-extension'
- require: '@springio/antora-extensions/root-component-extension'
root_component_name: 'PROJECT_WITHOUT_SPRING'
# FIXME: Run antora once using this extension to migrate to the Asciidoc Tabs syntax
# and then remove this extension
- require: '@springio/antora-extensions/tabs-migration-extension'
unwrap_example_block: always
save_result: true
root_component_name: 'cloud-consul'
site:
title: PROJECT_FULL_NAME
url: https://docs.spring.io/PROJECT_NAME/reference/
title: Spring Cloud Consul
url: https://docs.spring.io/spring-cloud-consul/reference
robots: allow
git:
ensure_git_suffix: false
content:
sources:
- url: ./..
branches: HEAD
- url: https://github.com/spring-cloud/spring-cloud-consul
# Refname matching:
# https://docs.antora.org/antora/latest/playbook/content-refname-matching/
branches: [ main ]
tags: [ '({4..9}).+({1..9}).+({0..9})?(-{RC,M}+({0..9}))', '!4.1.0-M1' ]
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_strategy: redirect:to
latest_version_segment: ''
redirect_facility: httpd
ui:
bundle:
url: https://github.com/spring-io/antora-ui-spring/releases/download/v0.3.5/ui-bundle.zip
snapshot: true
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

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +0,0 @@
releaser:
maven:
buildCommand: ./scripts/build.sh {{systemProps}}

View File

@@ -1,8 +0,0 @@
# Work in Progress
consul:
image: library/consul
ports:
- "8300:8300"
- "8400:8400"
- "8500:8500"
- "8600:8600"

View File

@@ -1,32 +0,0 @@
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)

View File

@@ -1,12 +0,0 @@
name: PROJECT_WITHOUT_SPRING
version: true
title: PROJECT_NAME
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/

View File

@@ -1,20 +0,0 @@
* xref:index.adoc[]
* xref:spring-cloud-consul.adoc[]
** xref:spring-cloud-consul/quick-start.adoc[]
** xref:spring-cloud-consul/install.adoc[]
** xref:spring-cloud-consul/agent.adoc[]
** xref:spring-cloud-consul/discovery.adoc[]
** xref:spring-cloud-consul/config.adoc[]
** xref:spring-cloud-consul/retry.adoc[]
** xref:spring-cloud-consul/bus.adoc[]
** xref:spring-cloud-consul/hystrix.adoc[]
** xref:spring-cloud-consul/turbine.adoc[]
** xref:spring-cloud-consul/configuration-properties.adoc[]
* xref:_attributes.adoc[]
* xref:intro.adoc[]
* xref:quickstart.adoc[]
* xref:README.adoc[]
* xref:_configprops.adoc[]
* xref:appendix.adoc[]
* xref:sagan-boot.adoc[]
* xref:sagan-index.adoc[]

View File

@@ -1,51 +0,0 @@
image::https://circleci.com/gh/spring-cloud/spring-cloud-consul/tree/master.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-consul/tree/master"]
image::https://codecov.io/gh/spring-cloud/spring-cloud-consul/branch/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-consul/branch/master"]
[[quick-start]]
= Quick Start
[[consul-overview]]
= Consul overview
Features of Consul
* Distributed configuration
* Service registration and discovery
* Distributed events
* Distributed locking and sessions
* Supports multiple data centers
* Built in, user-friendly user interface
See the https://consul.io/intro/index.html[intro] for more information.
[[spring-cloud-consul-features]]
= Spring Cloud Consul Features
* Spring Cloud `DiscoveryClient` implementation
** supports Spring Cloud Gateway
** supports Spring Cloud LoadBalancer
* Consul based `PropertySource` loaded during the 'bootstrap' phase.
* Spring Cloud Bus implementation based on Consul https://www.consul.io/docs/agent/http/event.html[events]
[[running-the-sample]]
= Running the sample
1. Run `docker-compose up`
2. Verify consul is running by visiting http://localhost:8500
3. Run `mvn package` this will bring in the required spring cloud maven repositories and build
4. Run `java -jar spring-cloud-consul-sample/target/spring-cloud-consul-sample-${VERSION}.jar`
5. visit http://localhost:8080, verify that `{"serviceId":"<yourhost>:8080","host":"<yourhost>","port":8080}` results
6. run `java -jar spring-cloud-consul-sample/target/spring-cloud-consul-sample-${VERSION}.jar --server.port=8081`
7. visit http://localhost:8080 again, verify that `{"serviceId":"<yourhost>:8081","host":"<yourhost>","port":8081}` eventually shows up in the results in a round robbin fashion (may take a minute or so).
[[building]]
= Building
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/building-jdk8.adoc[]
[[contributing]]
= Contributing
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[]

View File

@@ -1,14 +0,0 @@
:doctype: book
:idprefix:
:idseparator: -
:tabsize: 4
:numbered:
:sectanchors:
:sectnums:
:icons: font
:hide-uri-scheme:
:docinfo: shared,private
:sc-ext: java
:project-full-name: Spring Cloud Consul
:all: {asterisk}{asterisk}

View File

@@ -1,84 +0,0 @@
|===
|Name | Default | Description
|spring.cloud.consul.config.acl-token | |
|spring.cloud.consul.config.data-key | `+++data+++` | If format is Format.PROPERTIES or Format.YAML then the following field is used as key to look up consul for configuration.
|spring.cloud.consul.config.default-context | `+++application+++` |
|spring.cloud.consul.config.enabled | `+++true+++` |
|spring.cloud.consul.config.fail-fast | `+++true+++` | Throw exceptions during config lookup if true, otherwise, log warnings.
|spring.cloud.consul.config.format | |
|spring.cloud.consul.config.name | | Alternative to spring.application.name to use in looking up values in consul KV.
|spring.cloud.consul.config.prefix | |
|spring.cloud.consul.config.prefixes | |
|spring.cloud.consul.config.profile-separator | `+++,+++` |
|spring.cloud.consul.config.watch.delay | `+++1000+++` | The value of the fixed delay for the watch in millis. Defaults to 1000.
|spring.cloud.consul.config.watch.enabled | `+++true+++` | If the watch is enabled. Defaults to true.
|spring.cloud.consul.config.watch.wait-time | `+++55+++` | The number of seconds to wait (or block) for watch query, defaults to 55. Needs to be less than default ConsulClient (defaults to 60). To increase ConsulClient timeout create a ConsulClient bean with a custom ConsulRawClient with a custom HttpClient.
|spring.cloud.consul.discovery.acl-token | |
|spring.cloud.consul.discovery.catalog-services-watch-delay | `+++1000+++` | The delay between calls to watch consul catalog in millis, default is 1000.
|spring.cloud.consul.discovery.catalog-services-watch-timeout | `+++2+++` | The number of seconds to block while watching consul catalog, default is 2.
|spring.cloud.consul.discovery.consistency-mode | | Consistency mode for health service request.
|spring.cloud.consul.discovery.datacenters | | Map of serviceId's -> datacenter to query for in server list. This allows looking up services in another datacenters.
|spring.cloud.consul.discovery.default-query-tag | | Tag to query for in service list if one is not listed in serverListQueryTags. Multiple tags can be specified with a comma separated value.
|spring.cloud.consul.discovery.default-zone-metadata-name | `+++zone+++` | Service instance zone comes from metadata. This allows changing the metadata tag name.
|spring.cloud.consul.discovery.deregister | `+++true+++` | Disable automatic de-registration of service in consul.
|spring.cloud.consul.discovery.enable-tag-override | | Enable tag override for the registered service.
|spring.cloud.consul.discovery.enabled | `+++true+++` | Is service discovery enabled?
|spring.cloud.consul.discovery.fail-fast | `+++true+++` | Throw exceptions during service registration if true, otherwise, log warnings (defaults to true).
|spring.cloud.consul.discovery.health-check-critical-timeout | | Timeout to deregister services critical for longer than timeout (e.g. 30m). Requires consul version 7.x or higher.
|spring.cloud.consul.discovery.health-check-headers | | Headers to be applied to the Health Check calls.
|spring.cloud.consul.discovery.health-check-interval | `+++10s+++` | How often to perform the health check (e.g. 10s), defaults to 10s.
|spring.cloud.consul.discovery.health-check-path | `+++/actuator/health+++` | Alternate server path to invoke for health checking.
|spring.cloud.consul.discovery.health-check-timeout | | Timeout for health check (e.g. 10s).
|spring.cloud.consul.discovery.health-check-tls-skip-verify | | Skips certificate verification during service checks if true, otherwise runs certificate verification.
|spring.cloud.consul.discovery.health-check-url | | Custom health check url to override default.
|spring.cloud.consul.discovery.heartbeat.actuator-health-group | | The actuator health group to use (null for the root group) when determining system health via Actuator.
|spring.cloud.consul.discovery.heartbeat.enabled | `+++false+++` |
|spring.cloud.consul.discovery.heartbeat.interval-ratio | |
|spring.cloud.consul.discovery.heartbeat.reregister-service-on-failure | `+++false+++` |
|spring.cloud.consul.discovery.heartbeat.ttl | `+++30s+++` |
|spring.cloud.consul.discovery.heartbeat.use-actuator-health | `+++true+++` | Whether or not to take the current system health (as reported via the Actuator Health endpoint) into account when reporting the application status to the Consul TTL check. Actuator Health endpoint also has to be available to the application.
|spring.cloud.consul.discovery.hostname | | Hostname to use when accessing server.
|spring.cloud.consul.discovery.include-hostname-in-instance-id | `+++false+++` | Whether hostname is included into the default instance id when registering service.
|spring.cloud.consul.discovery.instance-group | | Service instance group.
|spring.cloud.consul.discovery.instance-id | | Unique service instance id.
|spring.cloud.consul.discovery.instance-zone | | Service instance zone.
|spring.cloud.consul.discovery.ip-address | | IP address to use when accessing service (must also set preferIpAddress to use).
|spring.cloud.consul.discovery.lifecycle.enabled | `+++true+++` |
|spring.cloud.consul.discovery.management-enable-tag-override | | Enable tag override for the registered management service.
|spring.cloud.consul.discovery.management-metadata | | Metadata to use when registering management service.
|spring.cloud.consul.discovery.management-port | | Port to register the management service under (defaults to management port).
|spring.cloud.consul.discovery.management-suffix | `+++management+++` | Suffix to use when registering management service.
|spring.cloud.consul.discovery.management-tags | | Tags to use when registering management service.
|spring.cloud.consul.discovery.metadata | | Metadata to use when registering service.
|spring.cloud.consul.discovery.order | `+++0+++` | Order of the discovery client used by `CompositeDiscoveryClient` for sorting available clients.
|spring.cloud.consul.discovery.port | | Port to register the service under (defaults to listening port).
|spring.cloud.consul.discovery.prefer-agent-address | `+++false+++` | Source of how we will determine the address to use.
|spring.cloud.consul.discovery.prefer-ip-address | `+++false+++` | Use ip address rather than hostname during registration.
|spring.cloud.consul.discovery.query-passing | `+++false+++` | Add the 'passing` parameter to /v1/health/service/serviceName. This pushes health check passing to the server.
|spring.cloud.consul.discovery.register | `+++true+++` | Register as a service in consul.
|spring.cloud.consul.discovery.register-health-check | `+++true+++` | Register health check in consul. Useful during development of a service.
|spring.cloud.consul.discovery.scheme | `+++http+++` | Whether to register an http or https service.
|spring.cloud.consul.discovery.server-list-query-tags | | Map of serviceId's -> tag to query for in server list. This allows filtering services by one more tags. Multiple tags can be specified with a comma separated value.
|spring.cloud.consul.discovery.service-name | | Service name.
|spring.cloud.consul.discovery.tags | | Tags to use when registering service.
|spring.cloud.consul.enabled | `+++true+++` | Is spring cloud consul enabled.
|spring.cloud.consul.host | `+++localhost+++` | Consul agent hostname. Defaults to 'localhost'.
|spring.cloud.consul.path | | Custom path if consul is under non-root.
|spring.cloud.consul.port | `+++8500+++` | Consul agent port. Defaults to '8500'.
|spring.cloud.consul.retry.enabled | `+++true+++` | If consul retry is enabled.
|spring.cloud.consul.retry.initial-interval | `+++1000+++` | Initial retry interval in milliseconds.
|spring.cloud.consul.retry.max-attempts | `+++6+++` | Maximum number of attempts.
|spring.cloud.consul.retry.max-interval | `+++2000+++` | Maximum interval for backoff.
|spring.cloud.consul.retry.multiplier | `+++1.1+++` | Multiplier for next interval.
|spring.cloud.consul.ribbon.enabled | `+++true+++` | Enables Consul and Ribbon integration.
|spring.cloud.consul.scheme | | Consul agent scheme (HTTP/HTTPS). If there is no scheme in address - client will use HTTP.
|spring.cloud.consul.service-registry.auto-registration.enabled | `+++true+++` | Enables Consul Service Registry Auto-registration.
|spring.cloud.consul.service-registry.enabled | `+++true+++` | Enables Consul Service Registry functionality.
|spring.cloud.consul.tls.certificate-password | | Password to open the certificate.
|spring.cloud.consul.tls.certificate-path | | File path to the certificate.
|spring.cloud.consul.tls.key-store-instance-type | | Type of key framework to use.
|spring.cloud.consul.tls.key-store-password | | Password to an external keystore.
|spring.cloud.consul.tls.key-store-path | | Path to an external keystore.
|===

View File

@@ -1,13 +0,0 @@
:numbered!:
[appendix]
[[common-application-properties]]
= Common application properties
:page-section-summary-toc: 1
Various properties can be specified inside your `application.properties` file, inside your `application.yml` file, or as command line switches.
This appendix provides a list of common {project-full-name} properties and references to the underlying classes that consume them.
NOTE: Property contributions can come from additional jar files on your classpath, so you should not consider this an exhaustive list.
Also, you can define your own properties.

View File

@@ -1,8 +0,0 @@
This project provides Consul 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 Consul based components. The
patterns provided include Service Discovery, Control Bus and Configuration.
Intelligent Routing and Client Side Load Balancing, Circuit Breaker
are provided by integration with other Spring Cloud projects.

View File

@@ -1,229 +0,0 @@
This quick start walks through using Spring Cloud Consul for Service Discovery and Distributed Configuration.
First, run Consul Agent on your machine. Then you can access it and use it as a Service Registry and Configuration source with Spring Cloud Consul.
[[discovery-client-usage]]
= Discovery Client Usage
To use these features in an application, you can build it as a Spring Boot application that depends on `spring-cloud-consul-core`.
The most convenient way to add the dependency is with a Spring Boot starter: `org.springframework.cloud:spring-cloud-starter-consul-discovery`.
We recommend using dependency management and `spring-boot-starter-parent`.
The following example shows a typical Maven configuration:
[source,xml,indent=0]
.pom.xml
----
<project>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>{spring-boot-version}</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
----
The following example shows a typical Gradle setup:
[source,groovy,indent=0]
.build.gradle
----
plugins {
id 'org.springframework.boot' version ${spring-boot-version}
id 'io.spring.dependency-management' version ${spring-dependency-management-version}
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-consul-discovery'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
----
Now you can create a standard Spring Boot application, such as the following HTTP server:
----
@SpringBootApplication
@RestController
public class Application {
@GetMapping("/")
public String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
----
When this HTTP server runs, it connects to Consul Agent running at the default local 8500 port.
To modify the startup behavior, you can change the location of Consul Agent by using `application.properties`, as shown in the following example:
----
spring:
cloud:
consul:
host: localhost
port: 8500
----
You can now use `DiscoveryClient`, `@LoadBalanced RestTemplate`, or `@LoadBalanced WebClient.Builder` to retrieve services and instances data from Consul, as shown in the following example:
[source,java,indent=0]
----
@Autowired
private DiscoveryClient discoveryClient;
public String serviceUrl() {
List<ServiceInstance> list = discoveryClient.getInstances("STORES");
if (list != null && list.size() > 0 ) {
return list.get(0).getUri().toString();
}
return null;
}
----
[[distributed-configuration-usage]]
= Distributed Configuration Usage
To use these features in an application, you can build it as a Spring Boot application that depends on `spring-cloud-consul-core` and `spring-cloud-consul-config`.
The most convenient way to add the dependency is with a Spring Boot starter: `org.springframework.cloud:spring-cloud-starter-consul-config`.
We recommend using dependency management and `spring-boot-starter-parent`.
The following example shows a typical Maven configuration:
[source,xml,indent=0]
.pom.xml
----
<project>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>{spring-boot-version}</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
----
The following example shows a typical Gradle setup:
[source,groovy,indent=0]
.build.gradle
----
plugins {
id 'org.springframework.boot' version ${spring-boot-version}
id 'io.spring.dependency-management' version ${spring-dependency-management-version}
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-consul-config'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
----
Now you can create a standard Spring Boot application, such as the following HTTP server:
----
@SpringBootApplication
@RestController
public class Application {
@GetMapping("/")
public String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
----
The application retrieves configuration data from Consul.
WARNING: If you use Spring Cloud Consul Config, you need to set the `spring.config.import` property in order to bind to Consul.
You can read more about it in the xref:spring-cloud-consul/config.adoc#config-data-import[Spring Boot Config Data Import section].

View File

@@ -1,39 +0,0 @@
Spring Cloud Consul provides http://consul.io[Consul] 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 Hashicorp's Consul. The patterns provided include Service Discovery, Distributed Configuration and Control Bus.
## Features
Spring Cloud Consul features:
* Service Discovery: instances can be registered with the Consul agent and clients can discover the instances using Spring-managed beans
* Supports Spring Cloud LoadBalancer - a client side load-balancer provided by the Spring Cloud project
* Supports Spring Cloud Gateway, a dynamic router and filter
* Distributed Configuration: using the Consul Key/Value store
* Control Bus: Distributed control events using Consul Events
## Quick Start
As long as Spring Cloud Consul and the Consul API are on the
classpath any Spring Boot application with `@EnableDiscoveryClient` will try to contact a Consul
agent on `localhost:8500` (the default values of
`spring.cloud.consul.host` and `spring.cloud.consul.port` respectively):
```java
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
@RestController
public class Application {
@RequestMapping("/")
public String home() {
return "Hello World";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
A local Consul agent must be running. See the https://consul.io/docs/agent/basics.html[Consul agent documentation] on how to run an agent.

View File

@@ -1,7 +0,0 @@
[[spring-cloud-consul]]
= Spring Cloud Consul
:page-section-summary-toc: 1
*{spring-cloud-version}*

View File

@@ -1,12 +0,0 @@
[[spring-cloud-consul-agent]]
= Consul Agent
:page-section-summary-toc: 1
A Consul Agent client must be available to all Spring Cloud Consul applications. By default, the Agent client is expected to be at `localhost:8500`. See the https://consul.io/docs/agent/basics.html[Agent documentation] for specifics on how to start an Agent client and how to connect to a cluster of Consul Agent Servers. For development, after you have installed consul, you may start a Consul Agent using the following command:
----
./src/main/bash/local_run_consul.sh
----
This will start an agent in server mode on port 8500, with the ui available at http://localhost:8500

View File

@@ -1,11 +0,0 @@
[[spring-cloud-consul-bus]]
= Spring Cloud Bus with Consul
:page-section-summary-toc: 1
[[how-to-activate]]
== How to activate
To get started with the Consul Bus use the starter with group `org.springframework.cloud` and artifact id `spring-cloud-starter-consul-bus`. See the https://projects.spring.io/spring-cloud/[Spring Cloud Project page] for details on setting up your build system with the current Spring Cloud Release Train.
See the https://cloud.spring.io/spring-cloud-bus/[Spring Cloud Bus] documentation for the available actuator endpoints and howto send custom messages.

View File

@@ -1,156 +0,0 @@
[[spring-cloud-consul-config]]
= Distributed Configuration with Consul
Consul provides a https://consul.io/docs/agent/http/kv.html[Key/Value Store] for storing configuration and other metadata. Spring Cloud Consul Config is an alternative to the https://github.com/spring-cloud/spring-cloud-config[Config Server and Client]. Configuration is loaded into the Spring Environment during the special "bootstrap" phase. Configuration is stored in the `/config` folder by default. Multiple `PropertySource` instances are created based on the application's name and the active profiles that mimics the Spring Cloud Config order of resolving properties. For example, an application with the name "testApp" and with the "dev" profile will have the following property sources created:
----
config/testApp,dev/
config/testApp/
config/application,dev/
config/application/
----
The most specific property source is at the top, with the least specific at the bottom. Properties in the `config/application` folder are applicable to all applications using consul for configuration. Properties in the `config/testApp` folder are only available to the instances of the service named "testApp".
Configuration is currently read on startup of the application. Sending a HTTP POST to `/refresh` will cause the configuration to be reloaded. xref:spring-cloud-consul/config.adoc#spring-cloud-consul-config-watch[Config Watch] will also automatically detect changes and reload the application context.
[[how-to-activate]]
== How to activate
To get started with Consul Configuration use the starter with group `org.springframework.cloud` and artifact id `spring-cloud-starter-consul-config`. See the https://projects.spring.io/spring-cloud/[Spring Cloud Project page] for details on setting up your build system with the current Spring Cloud Release Train.
[[config-data-import]]
== Spring Boot Config Data Import
Spring Boot 2.4 introduced a new way to import configuration data via the `spring.config.import` property. This is now the default way to get configuration from Consul.
To optionally connect to Consul set the following in application.properties:
.application.properties
[source,properties]
----
spring.config.import=optional:consul:
----
This will connect to the Consul Agent at the default location of "http://localhost:8500". Removing the `optional:` prefix will cause Consul Config to fail if it is unable to connect to Consul. To change the connection properties of Consul Config either set `spring.cloud.consul.host` and `spring.cloud.consul.port` or add the host/port pair to the `spring.config.import` statement such as, `spring.config.import=optional:consul:myhost:8500`. The location in the import property has precedence over the host and port propertie.
Consul Config will try to load values from four automatic contexts based on `spring.cloud.consul.config.name` (which defaults to the value of the `spring.application.name` property) and `spring.cloud.consul.config.default-context` (which defaults to `application`). If you want to specify the contexts rather than using the computed ones, you can add that information to the `spring.config.import` statement.
.application.properties
[source,properties]
----
spring.config.import=optional:consul:myhost:8500/contextone;/context/two
----
This will optionally load configuration only from `/contextone` and `/context/two`.
NOTE: A `bootstrap` file (properties or yaml) is *not* needed for the Spring Boot Config Data method of import via `spring.config.import`.
[[customizing]]
== Customizing
Consul Config may be customized using the following properties:
[source,yaml]
----
spring:
cloud:
consul:
config:
enabled: true
prefix: configuration
defaultContext: apps
profileSeparator: '::'
----
CAUTION: If you have set `spring.cloud.bootstrap.enabled=true` or `spring.config.use-legacy-processing=true`, or included `spring-cloud-starter-bootstrap`, then the above values will need to be placed in `bootstrap.yml` instead of `application.yml`.
* `enabled` setting this value to "false" disables Consul Config
* `prefix` sets the base folder for configuration values
* `defaultContext` sets the folder name used by all applications
* `profileSeparator` sets the value of the separator used to separate the profile name in property sources with profiles
[[spring-cloud-consul-config-watch]]
== Config Watch
The Consul Config Watch takes advantage of the ability of consul to https://www.consul.io/docs/agent/watches.html#keyprefix[watch a key prefix]. The Config Watch makes a blocking Consul HTTP API call to determine if any relevant configuration data has changed for the current application. If there is new configuration data a Refresh Event is published. This is equivalent to calling the `/refresh` actuator endpoint.
To change the frequency of when the Config Watch is called change `spring.cloud.consul.config.watch.delay`. The default value is 1000, which is in milliseconds. The delay is the amount of time after the end of the previous invocation and the start of the next.
To disable the Config Watch set `spring.cloud.consul.config.watch.enabled=false`.
The watch uses a Spring `TaskScheduler` to schedule the call to consul. By default it is a `ThreadPoolTaskScheduler` with a `poolSize` of 1. To change the `TaskScheduler`, create a bean of type `TaskScheduler` named with the `ConsulConfigAutoConfiguration.CONFIG_WATCH_TASK_SCHEDULER_NAME` constant.
[[spring-cloud-consul-config-format]]
== YAML or Properties with Config
It may be more convenient to store a blob of properties in YAML or Properties format as opposed to individual key/value pairs. Set the `spring.cloud.consul.config.format` property to `YAML` or `PROPERTIES`. For example to use YAML:
[source,yaml]
----
spring:
cloud:
consul:
config:
format: YAML
----
CAUTION: If you have set `spring.cloud.bootstrap.enabled=true` or `spring.config.use-legacy-processing=true`, or included `spring-cloud-starter-bootstrap`, then the above values will need to be placed in `bootstrap.yml` instead of `application.yml`.
YAML must be set in the appropriate `data` key in consul. Using the defaults above the keys would look like:
----
config/testApp,dev/data
config/testApp/data
config/application,dev/data
config/application/data
----
You could store a YAML document in any of the keys listed above.
You can change the data key using `spring.cloud.consul.config.data-key`.
[[spring-cloud-consul-config-git2consul]]
== git2consul with Config
git2consul is a Consul community project that loads files from a git repository to individual keys into Consul. By default the names of the keys are names of the files. YAML and Properties files are supported with file extensions of `.yml` and `.properties` respectively. Set the `spring.cloud.consul.config.format` property to `FILES`. For example:
.bootstrap.yml
----
spring:
cloud:
consul:
config:
format: FILES
----
Given the following keys in `/config`, the `development` profile and an application name of `foo`:
----
.gitignore
application.yml
bar.properties
foo-development.properties
foo-production.yml
foo.properties
master.ref
----
the following property sources would be created:
----
config/foo-development.properties
config/foo.properties
config/application.yml
----
The value of each key needs to be a properly formatted YAML or Properties file.
[[spring-cloud-consul-failfast]]
== Fail Fast
It may be convenient in certain circumstances (like local development or certain test scenarios) to not fail if consul isn't available for configuration. Setting `spring.cloud.consul.config.fail-fast=false` will cause the configuration module to log a warning rather than throw an exception. This will allow the application to continue startup normally.
CAUTION: If you have set `spring.cloud.bootstrap.enabled=true` or `spring.config.use-legacy-processing=true`, or included `spring-cloud-starter-bootstrap`, then the above values will need to be placed in `bootstrap.yml` instead of `application.yml`.

View File

@@ -1,5 +0,0 @@
[[configuration-properties]]
= Configuration Properties
:page-section-summary-toc: 1
To see the list of all Consul related configuration properties please check link:appendix.html[the Appendix page].

View File

@@ -1,402 +0,0 @@
[[spring-cloud-consul-discovery]]
= Service Discovery with Consul
Service Discovery is one of the key tenets of a microservice based architecture. Trying to hand configure each client or some form of convention can be very difficult to do and can be very brittle. Consul provides Service Discovery services via an https://www.consul.io/docs/agent/http.html[HTTP API] and https://www.consul.io/docs/agent/dns.html[DNS]. Spring Cloud Consul leverages the HTTP API for service registration and discovery. This does not prevent non-Spring Cloud applications from leveraging the DNS interface. Consul Agents servers are run in a https://www.consul.io/docs/internals/architecture.html[cluster] that communicates via a https://www.consul.io/docs/internals/gossip.html[gossip protocol] and uses the https://www.consul.io/docs/internals/consensus.html[Raft consensus protocol].
[[how-to-activate]]
== How to activate
To activate Consul Service Discovery use the starter with group `org.springframework.cloud` and artifact id `spring-cloud-starter-consul-discovery`. See the https://projects.spring.io/spring-cloud/[Spring Cloud Project page] for details on setting up your build system with the current Spring Cloud Release Train.
[[registering-with-consul]]
== Registering with Consul
When a client registers with Consul, it provides meta-data about itself such as host and port, id, name and tags. An https://www.consul.io/docs/discovery/checks#http-interval[HTTP Check] is created by default that Consul hits the `/actuator/health` endpoint every 10 seconds. If the health check fails, the service instance is marked as critical.
Example Consul client:
[source,java,indent=0]
----
@SpringBootApplication
@RestController
public class Application {
@RequestMapping("/")
public String home() {
return "Hello world";
}
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
----
(i.e. utterly normal Spring Boot app). If the Consul client is located somewhere other than `localhost:8500`, the configuration is required to locate the client. Example:
.application.yml
----
spring:
cloud:
consul:
host: localhost
port: 8500
----
CAUTION: If you use xref:spring-cloud-consul/config.adoc[Spring Cloud Consul Config], and you have set `spring.cloud.bootstrap.enabled=true` or `spring.config.use-legacy-processing=true` or use `spring-cloud-starter-bootstrap`, then the above values will need to be placed in `bootstrap.yml` instead of `application.yml`.
The default service name, instance id and port, taken from the `Environment`, are `${spring.application.name}`, the Spring Context ID and `${server.port}` respectively.
To disable the Consul Discovery Client you can set `spring.cloud.consul.discovery.enabled` to `false`. Consul Discovery Client will also be disabled when `spring.cloud.discovery.enabled` is set to `false`.
To disable the service registration you can set `spring.cloud.consul.discovery.register` to `false`.
[[registering-management-as-a-separate-service]]
=== Registering Management as a Separate Service
When management server port is set to something different than the application port, by setting `management.server.port` property, management service will be registered as a separate service than the application service. For example:
.application.yml
----
spring:
application:
name: myApp
management:
server:
port: 4452
----
Above configuration will register following 2 services:
* Application Service:
----
ID: myApp
Name: myApp
----
* Management Service:
----
ID: myApp-management
Name: myApp-management
----
Management service will inherit its `instanceId` and `serviceName` from the application service. For example:
.application.yml
----
spring:
application:
name: myApp
management:
server:
port: 4452
spring:
cloud:
consul:
discovery:
instance-id: custom-service-id
serviceName: myprefix-${spring.application.name}
----
Above configuration will register following 2 services:
* Application Service:
----
ID: custom-service-id
Name: myprefix-myApp
----
* Management Service:
----
ID: custom-service-id-management
Name: myprefix-myApp-management
----
Further customization is possible via following properties:
----
/** Port to register the management service under (defaults to management port) */
spring.cloud.consul.discovery.management-port
/** Suffix to use when registering management service (defaults to "management") */
spring.cloud.consul.discovery.management-suffix
/** Tags to use when registering management service (defaults to "management") */
spring.cloud.consul.discovery.management-tags
----
[[http-health-check]]
=== HTTP Health Check
The health check for a Consul instance defaults to "/actuator/health", which is the default location of the health endpoint in a Spring Boot Actuator application. You need to change this, even for an Actuator application, if you use a non-default context path or servlet path (e.g. `server.servletPath=/foo`) or management endpoint path (e.g. `management.server.servlet.context-path=/admin`).
The interval that Consul uses to check the health endpoint may also be configured. "10s" and "1m" represent 10 seconds and 1 minute respectively.
This example illustrates the above (see the `spring.cloud.consul.discovery.health-check-*` properties in link:appendix.html[the appendix page] for more options).
.application.yml
----
spring:
cloud:
consul:
discovery:
healthCheckPath: ${management.server.servlet.context-path}/actuator/health
healthCheckInterval: 15s
----
You can disable the HTTP health check entirely by setting `spring.cloud.consul.discovery.register-health-check=false`.
[[applying-headers]]
==== Applying Headers
Headers can be applied to health check requests. For example, if you're trying to register a https://cloud.spring.io/spring-cloud-config/[Spring Cloud Config] server that uses https://github.com/spring-cloud/spring-cloud-config/blob/master/docs/src/main/asciidoc/spring-cloud-config.adoc#vault-backend[Vault Backend]:
.application.yml
----
spring:
cloud:
consul:
discovery:
health-check-headers:
X-Config-Token: 6442e58b-d1ea-182e-cfa5-cf9cddef0722
----
According to the HTTP standard, each header can have more than one values, in which case, an array can be supplied:
.application.yml
----
spring:
cloud:
consul:
discovery:
health-check-headers:
X-Config-Token:
- "6442e58b-d1ea-182e-cfa5-cf9cddef0722"
- "Some other value"
----
[[ttl-health-check]]
=== TTL Health Check
A Consul https://www.consul.io/docs/discovery/checks#ttl[TTL Check] can be used instead of the default configured HTTP check.
The main difference is that the application sends a heartbeat signal to the Consul agent rather than the Consul agent sending a request to the application.
The interval the application uses to send the ping may also be configured. "10s" and "1m" represent 10 seconds and 1 minute respectively.
The default is 30 seconds.
This example illustrates the above (see the `spring.cloud.consul.discovery.heartbeat.*` properties in link:appendix.html[the appendix page] for more options).
.application.yml
----
spring:
cloud:
consul:
discovery:
heartbeat:
enabled: true
ttl: 10s
----
[[ttl-application-status]]
==== TTL Application Status
For a Spring Boot Actuator application the status is determined from its available health endpoint.
When the health endpoint is not available (either disabled or not a Spring Boot Actuator application) it assumes the application is in good health.
When querying the health endpoint, the root https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready-health-groups[health group] is used by default.
A different health group can be used by setting the following property:
.application.yml
----
spring:
cloud:
consul:
discovery:
heartbeat:
actuator-health-group: <your-custom-group-goes-here>
----
You can disable the use of the health endpoint entirely by setting the following property:
.application.yml
----
spring:
cloud:
consul:
discovery:
heartbeat:
use-actuator-health: false
----
[[custom-ttl-application-status]]
===== Custom TTL Application Status
If you want to configure your own application status mechanism, simply implement the `ApplicationStatusProvider` interface
.MyCustomApplicationStatusProvider.java
----
@Bean
public class MyCustomApplicationStatusProvider implements ApplicationStatusProvider {
public CheckStatus currentStatus() {
return yourMethodToDetermineAppStatusGoesHere();
}
}
----
and make it available to the application context:
----
@Bean
public CustomApplicationStatusProvider customAppStatusProvider() {
return new MyCustomApplicationStatusProvider();
}
----
[[actuator-health-indicators]]
=== Actuator Health Indicator(s)
If the service instance is a Spring Boot Actuator application, it may be provided the following Actuator health indicators.
[[discoveryclienthealthindicator]]
==== DiscoveryClientHealthIndicator
When Consul Service Discovery is active, a https://cloud.spring.io/spring-cloud-commons/2.2.x/reference/html/#health-indicator[DiscoverClientHealthIndicator] is configured and made available to the Actuator health endpoint.
See https://cloud.spring.io/spring-cloud-commons/2.2.x/reference/html/#health-indicator[here] for configuration options.
[[consulhealthindicator]]
==== ConsulHealthIndicator
An indicator is configured that verifies the health of the `ConsulClient`.
By default, it retrieves the Consul leader node status and all registered services.
In deployments that have many registered services it may be costly to retrieve all services on every health check.
To skip the service retrieval and only check the leader node status set `spring.cloud.consul.health-indicator.include-services-query=false`.
To disable the indicator set `management.health.consul.enabled=false`.
WARNING: When the application runs in https://cloud.spring.io/spring-cloud-commons/2.2.x/reference/html/#the-bootstrap-application-context[bootstrap context mode] (the default),
this indicator is loaded into the bootstrap context and is not made available to the Actuator health endpoint.
[[metadata]]
=== Metadata
Consul supports metadata on services. Spring Cloud's `ServiceInstance` has a `Map<String, String> metadata` field which is populated from a services `meta` field. To populate the `meta` field set values on `spring.cloud.consul.discovery.metadata` or `spring.cloud.consul.discovery.management-metadata` properties.
.application.yml
----
spring:
cloud:
consul:
discovery:
metadata:
myfield: myvalue
anotherfield: anothervalue
----
The above configuration will result in a service who's meta field contains `myfield->myvalue` and `anotherfield->anothervalue`.
[[generated-metadata]]
==== Generated Metadata
The Consul Auto Registration will generate a few entries automatically.
.Auto Generated Metadata
|===
| Key | Value
| 'group'
| Property `spring.cloud.consul.discovery.instance-group`. This values is only generated if `instance-group` is not empty.'
| 'secure'
| True if property `spring.cloud.consul.discovery.scheme` equals 'https', otherwise false.
| Property `spring.cloud.consul.discovery.default-zone-metadata-name`, defaults to 'zone'
| Property `spring.cloud.consul.discovery.instance-zone`. This values is only generated if `instance-zone` is not empty.'
|===
WARNING: Older versions of Spring Cloud Consul populated the `ServiceInstance.getMetadata()` method from Spring Cloud Commons by parsing the `spring.cloud.consul.discovery.tags` property. This is no longer supported, please migrate to using the `spring.cloud.consul.discovery.metadata` map.
[[making-the-consul-instance-id-unique]]
=== Making the Consul Instance ID Unique
By default a consul instance is registered with an ID that is equal to its Spring Application Context ID. By default, the Spring Application Context ID is `${spring.application.name}:comma,separated,profiles:${server.port}`. For most cases, this will allow multiple instances of one service to run on one machine. If further uniqueness is required, Using Spring Cloud you can override this by providing a unique identifier in `spring.cloud.consul.discovery.instanceId`. For example:
.application.yml
----
spring:
cloud:
consul:
discovery:
instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}
----
With this metadata, and multiple service instances deployed on localhost, the random value will kick in there to make the instance unique. In Cloudfoundry the `vcap.application.instance_id` will be populated automatically in a Spring Boot application, so the random value will not be needed.
[[looking-up-services]]
== Looking up services
[[using-load-balancer]]
=== Using Load-balancer
Spring Cloud has support for https://github.com/spring-cloud/spring-cloud-netflix/blob/master/docs/src/main/asciidoc/spring-cloud-netflix.adoc#spring-cloud-feign[Feign] (a REST client builder) and also https://docs.spring.io/spring-cloud-commons/docs/current/reference/html/#rest-template-loadbalancer-client[Spring `RestTemplate`]
for looking up services using the logical service names/ids instead of physical URLs. Both Feign and the discovery-aware RestTemplate utilize https://docs.spring.io/spring-cloud-commons/docs/current/reference/html/#spring-cloud-loadbalancer[Spring Cloud LoadBalancer] for client-side load balancing.
If you want to access service STORES using the RestTemplate simply declare:
----
@LoadBalanced
@Bean
public RestTemplate loadbalancedRestTemplate() {
return new RestTemplate();
}
----
and use it like this (notice how we use the STORES service name/id from Consul instead of a fully qualified domainname):
----
@Autowired
RestTemplate restTemplate;
public String getFirstProduct() {
return this.restTemplate.getForObject("https://STORES/products/1", String.class);
}
----
If you have Consul clusters in multiple datacenters and you want to access a service in another datacenter a service name/id alone is not enough. In that case
you use property `spring.cloud.consul.discovery.datacenters.STORES=dc-west` where `STORES` is the service name/id and `dc-west` is the datacenter
where the STORES service lives.
TIP: Spring Cloud now also offers support for
https://cloud.spring.io/spring-cloud-commons/reference/html/#_spring_resttemplate_as_a_load_balancer_client[Spring Cloud LoadBalancer].
[[using-the-discoveryclient]]
=== Using the DiscoveryClient
You can also use the `org.springframework.cloud.client.discovery.DiscoveryClient` which provides a simple API for discovery clients that is not specific to Netflix, e.g.
----
@Autowired
private DiscoveryClient discoveryClient;
public String serviceUrl() {
List<ServiceInstance> list = discoveryClient.getInstances("STORES");
if (list != null && list.size() > 0 ) {
return list.get(0).getUri();
}
return null;
}
----
[[consul-catalog-watch]]
== Consul Catalog Watch
The Consul Catalog Watch takes advantage of the ability of consul to https://www.consul.io/docs/agent/watches.html#services[watch services]. The Catalog Watch makes a blocking Consul HTTP API call to determine if any services have changed. If there is new service data a Heartbeat Event is published.
To change the frequency of when the Config Watch is called change `spring.cloud.consul.config.discovery.catalog-services-watch-delay`. The default value is 1000, which is in milliseconds. The delay is the amount of time after the end of the previous invocation and the start of the next.
To disable the Catalog Watch set `spring.cloud.consul.discovery.catalogServicesWatch.enabled=false`.
The watch uses a Spring `TaskScheduler` to schedule the call to consul. By default it is a `ThreadPoolTaskScheduler` with a `poolSize` of 1. To change the `TaskScheduler`, create a bean of type `TaskScheduler` named with the `ConsulDiscoveryClientConfiguration.CATALOG_WATCH_TASK_SCHEDULER_NAME` constant.

View File

@@ -1,7 +0,0 @@
[[spring-cloud-consul-hystrix]]
= Circuit Breaker with Hystrix
:page-section-summary-toc: 1
Applications can use the Hystrix Circuit Breaker provided by the Spring Cloud Netflix project by including this starter in the projects pom.xml: `spring-cloud-starter-hystrix`. Hystrix doesn't depend on the Netflix Discovery Client. The `@EnableHystrix` annotation should be placed on a configuration class (usually the main class). Then methods can be annotated with `@HystrixCommand` to be protected by a circuit breaker. See https://projects.spring.io/spring-cloud/spring-cloud.html#_circuit_breaker_hystrix_clients[the documentation] for more details.

View File

@@ -1,6 +0,0 @@
[[spring-cloud-consul-install]]
= Install Consul
:page-section-summary-toc: 1
Please see the https://www.consul.io/intro/getting-started/install.html[installation documentation] for instructions on how to install Consul.

View File

@@ -1,6 +0,0 @@
[[quick-start]]
= Quick Start
:page-section-summary-toc: 1
include:../:quickstart.adoc[]

View File

@@ -1,16 +0,0 @@
[[spring-cloud-consul-retry]]
= Consul Retry
:page-section-summary-toc: 1
If you expect that the consul agent may occasionally be unavailable when
your app starts, you can ask it to keep trying after a failure. You need to add
`spring-retry` and `spring-boot-starter-aop` to your classpath. The default
behaviour is to retry 6 times with an initial backoff interval of 1000ms and an
exponential multiplier of 1.1 for subsequent backoffs. You can configure these
properties (and others) using `spring.cloud.consul.retry.*` configuration properties.
This works with both Spring Cloud Consul Config and Discovery registration.
TIP: To take full control of the retry add a `@Bean` of type
`RetryOperationsInterceptor` with id "consulRetryInterceptor". Spring
Retry has a `RetryInterceptorBuilder` that makes it easy to create one.

View File

@@ -1,42 +0,0 @@
[[spring-cloud-consul-turbine]]
= Hystrix metrics aggregation with Turbine and Consul
Turbine (provided by the Spring Cloud Netflix project), aggregates multiple instances Hystrix metrics streams, so the dashboard can display an aggregate view. Turbine uses the `DiscoveryClient` interface to lookup relevant instances. To use Turbine with Spring Cloud Consul, configure the Turbine application in a manner similar to the following examples:
.pom.xml
----
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-turbine</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
----
Notice that the Turbine dependency is not a starter. The turbine starter includes support for Netflix Eureka.
.application.yml
----
spring.application.name: turbine
applications: consulhystrixclient
turbine:
aggregator:
clusterConfig: ${applications}
appConfig: ${applications}
----
The `clusterConfig` and `appConfig` sections must match, so it's useful to put the comma-separated list of service ID's into a separate configuration property.
.Turbine.java
----
@EnableTurbine
@SpringBootApplication
public class Turbine {
public static void main(String[] args) {
SpringApplication.run(DemoturbinecommonsApplication.class, args);
}
}
----

View File

@@ -1,72 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-consul</artifactId>
<version>4.1.0-SNAPSHOT</version>
</parent>
<artifactId>spring-cloud-consul-docs</artifactId>
<packaging>jar</packaging>
<name>Spring Cloud Consul Docs</name>
<description>Spring Cloud Docs</description>
<properties>
<docs.main>spring-cloud-consul</docs.main>
<main.basedir>${basedir}/..</main.basedir>
<configprops.inclusionPattern>spring.cloud.consul.*</configprops.inclusionPattern>
<upload-docs-zip.phase>deploy</upload-docs-zip.phase>
<!-- Don't upload docs jar to central / repo.spring.io -->
<maven-deploy-plugin-default.phase>none</maven-deploy-plugin-default.phase>
</properties>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>spring-cloud-starter-consul</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>spring-cloud-starter-consul-all</artifactId>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/asciidoc</sourceDirectory>
</build>
<profiles>
<profile>
<id>docs</id>
<build>
<plugins>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@@ -1,330 +0,0 @@
#!/bin/bash -x
set -e
# Set default props like MAVEN_PATH, ROOT_FOLDER etc.
function set_default_props() {
# The script should be run from the root folder
ROOT_FOLDER=`pwd`
echo "Current folder is ${ROOT_FOLDER}"
if [[ ! -e "${ROOT_FOLDER}/.git" ]]; then
echo "You're not in the root folder of the project!"
exit 1
fi
# Prop that will let commit the changes
COMMIT_CHANGES="no"
MAVEN_PATH=${MAVEN_PATH:-}
echo "Path to Maven is [${MAVEN_PATH}]"
REPO_NAME=${PWD##*/}
echo "Repo name is [${REPO_NAME}]"
SPRING_CLOUD_STATIC_REPO=${SPRING_CLOUD_STATIC_REPO:-git@github.com:spring-cloud/spring-cloud-static.git}
echo "Spring Cloud Static repo is [${SPRING_CLOUD_STATIC_REPO}"
}
# Check if gh-pages exists and docs have been built
function check_if_anything_to_sync() {
git remote set-url --push origin `git config remote.origin.url | sed -e 's/^git:/https:/'`
if ! (git remote set-branches --add origin gh-pages && git fetch -q); then
echo "No gh-pages, so not syncing"
exit 0
fi
if ! [ -d docs/target/generated-docs ] && ! [ "${BUILD}" == "yes" ]; then
echo "No gh-pages sources in docs/target/generated-docs, so not syncing"
exit 0
fi
}
function retrieve_current_branch() {
# Code getting the name of the current branch. For master we want to publish as we did until now
# https://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch
# If there is a branch already passed will reuse it - otherwise will try to find it
CURRENT_BRANCH=${BRANCH}
if [[ -z "${CURRENT_BRANCH}" ]] ; then
CURRENT_BRANCH=$(git symbolic-ref -q HEAD)
CURRENT_BRANCH=${CURRENT_BRANCH##refs/heads/}
CURRENT_BRANCH=${CURRENT_BRANCH:-HEAD}
fi
echo "Current branch is [${CURRENT_BRANCH}]"
git checkout ${CURRENT_BRANCH} || echo "Failed to check the branch... continuing with the script"
}
# Switches to the provided value of the release version. We always prefix it with `v`
function switch_to_tag() {
git checkout v${VERSION}
}
# Build the docs if switch is on
function build_docs_if_applicable() {
if [[ "${BUILD}" == "yes" ]] ; then
./mvnw clean install -P docs -pl docs -DskipTests
fi
}
# Get the name of the `docs.main` property
# Get allowed branches - assumes that a `docs` module is available under `docs` profile
function retrieve_doc_properties() {
MAIN_ADOC_VALUE=$("${MAVEN_PATH}"mvn -q \
-Dexec.executable="echo" \
-Dexec.args='${docs.main}' \
--non-recursive \
org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
echo "Extracted 'main.adoc' from Maven build [${MAIN_ADOC_VALUE}]"
ALLOW_PROPERTY=${ALLOW_PROPERTY:-"docs.allowed.branches"}
ALLOWED_BRANCHES_VALUE=$("${MAVEN_PATH}"mvn -q \
-Dexec.executable="echo" \
-Dexec.args="\${${ALLOW_PROPERTY}}" \
org.codehaus.mojo:exec-maven-plugin:1.3.1:exec \
-P docs \
-pl docs)
echo "Extracted '${ALLOW_PROPERTY}' from Maven build [${ALLOWED_BRANCHES_VALUE}]"
}
# Stash any outstanding changes
function stash_changes() {
git diff-index --quiet HEAD && dirty=$? || (echo "Failed to check if the current repo is dirty. Assuming that it is." && dirty="1")
if [ "$dirty" != "0" ]; then git stash; fi
}
# Switch to gh-pages branch to sync it with current branch
function add_docs_from_target() {
local DESTINATION_REPO_FOLDER
if [[ -z "${DESTINATION}" && -z "${CLONE}" ]] ; then
DESTINATION_REPO_FOLDER=${ROOT_FOLDER}
elif [[ "${CLONE}" == "yes" ]]; then
mkdir -p ${ROOT_FOLDER}/target
local clonedStatic=${ROOT_FOLDER}/target/spring-cloud-static
if [[ ! -e "${clonedStatic}/.git" ]]; then
echo "Cloning Spring Cloud Static to target"
git clone ${SPRING_CLOUD_STATIC_REPO} ${clonedStatic} && git checkout gh-pages
else
echo "Spring Cloud Static already cloned - will pull changes"
cd ${clonedStatic} && git checkout gh-pages && git pull origin gh-pages
fi
DESTINATION_REPO_FOLDER=${clonedStatic}/${REPO_NAME}
mkdir -p ${DESTINATION_REPO_FOLDER}
else
if [[ ! -e "${DESTINATION}/.git" ]]; then
echo "[${DESTINATION}] is not a git repository"
exit 1
fi
DESTINATION_REPO_FOLDER=${DESTINATION}/${REPO_NAME}
mkdir -p ${DESTINATION_REPO_FOLDER}
echo "Destination was provided [${DESTINATION}]"
fi
cd ${DESTINATION_REPO_FOLDER}
git checkout gh-pages
git pull origin gh-pages
# Add git branches
###################################################################
if [[ -z "${VERSION}" ]] ; then
copy_docs_for_current_version
else
copy_docs_for_provided_version
fi
commit_changes_if_applicable
}
# Copies the docs by using the retrieved properties from Maven build
function copy_docs_for_current_version() {
if [[ "${CURRENT_BRANCH}" == "master" ]] ; then
echo -e "Current branch is master - will copy the current docs only to the root folder"
for f in docs/target/generated-docs/*; do
file=${f#docs/target/generated-docs/*}
if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then
# Not ignored...
cp -rf $f ${ROOT_FOLDER}/
git add -A ${ROOT_FOLDER}/$file
fi
done
COMMIT_CHANGES="yes"
else
echo -e "Current branch is [${CURRENT_BRANCH}]"
# https://stackoverflow.com/questions/29300806/a-bash-script-to-check-if-a-string-is-present-in-a-comma-separated-list-of-strin
if [[ ",${ALLOWED_BRANCHES_VALUE}," = *",${CURRENT_BRANCH},"* ]] ; then
mkdir -p ${ROOT_FOLDER}/${CURRENT_BRANCH}
echo -e "Branch [${CURRENT_BRANCH}] is allowed! Will copy the current docs to the [${CURRENT_BRANCH}] folder"
for f in docs/target/generated-docs/*; do
file=${f#docs/target/generated-docs/*}
if ! git ls-files -i -o --exclude-standard --directory | grep -q ^$file$; then
# Not ignored...
# We want users to access 1.0.0.RELEASE/ instead of 1.0.0.RELEASE/spring-cloud.sleuth.html
if [[ "${file}" == "${MAIN_ADOC_VALUE}.html" ]] ; then
# We don't want to copy the spring-cloud-sleuth.html
# we want it to be converted to index.html
cp -rf $f ${ROOT_FOLDER}/${CURRENT_BRANCH}/index.html
git add -A ${ROOT_FOLDER}/${CURRENT_BRANCH}/index.html
else
cp -rf $f ${ROOT_FOLDER}/${CURRENT_BRANCH}
git add -A ${ROOT_FOLDER}/${CURRENT_BRANCH}/$file
fi
fi
done
COMMIT_CHANGES="yes"
else
echo -e "Branch [${CURRENT_BRANCH}] is not on the allow list! Check out the Maven [${ALLOW_PROPERTY}] property in
[docs] module available under [docs] profile. Won't commit any changes to gh-pages for this branch."
fi
fi
}
# Copies the docs by using the explicitly provided version
function copy_docs_for_provided_version() {
local FOLDER=${DESTINATION_REPO_FOLDER}/${VERSION}
mkdir -p ${FOLDER}
echo -e "Current tag is [v${VERSION}] Will copy the current docs to the [${FOLDER}] folder"
for f in ${ROOT_FOLDER}/docs/target/generated-docs/*; do
file=${f#${ROOT_FOLDER}/docs/target/generated-docs/*}
copy_docs_for_branch ${file} ${FOLDER}
done
COMMIT_CHANGES="yes"
CURRENT_BRANCH="v${VERSION}"
}
# Copies the docs from target to the provided destination
# Params:
# $1 - file from target
# $2 - destination to which copy the files
function copy_docs_for_branch() {
local file=$1
local destination=$2
if ! git ls-files -i -o --exclude-standard --directory | grep -q ^${file}$; then
# Not ignored...
# We want users to access 1.0.0.RELEASE/ instead of 1.0.0.RELEASE/spring-cloud.sleuth.html
if [[ ("${file}" == "${MAIN_ADOC_VALUE}.html") || ("${file}" == "${REPO_NAME}.html") ]] ; then
# We don't want to copy the spring-cloud-sleuth.html
# we want it to be converted to index.html
cp -rf $f ${destination}/index.html
git add -A ${destination}/index.html
else
cp -rf $f ${destination}
git add -A ${destination}/$file
fi
fi
}
function commit_changes_if_applicable() {
if [[ "${COMMIT_CHANGES}" == "yes" ]] ; then
COMMIT_SUCCESSFUL="no"
git commit -a -m "Sync docs from ${CURRENT_BRANCH} to gh-pages" && COMMIT_SUCCESSFUL="yes" || echo "Failed to commit changes"
# Uncomment the following push if you want to auto push to
# the gh-pages branch whenever you commit to master locally.
# This is a little extreme. Use with care!
###################################################################
if [[ "${COMMIT_SUCCESSFUL}" == "yes" ]] ; then
git push origin gh-pages
fi
fi
}
# Switch back to the previous branch and exit block
function checkout_previous_branch() {
# If -version was provided we need to come back to root project
cd ${ROOT_FOLDER}
git checkout ${CURRENT_BRANCH} || echo "Failed to check the branch... continuing with the script"
if [ "$dirty" != "0" ]; then git stash pop; fi
exit 0
}
# Assert if properties have been properly passed
function assert_properties() {
echo "VERSION [${VERSION}], DESTINATION [${DESTINATION}], CLONE [${CLONE}]"
if [[ "${VERSION}" != "" && (-z "${DESTINATION}" && -z "${CLONE}") ]] ; then echo "Version was set but destination / clone was not!"; exit 1;fi
if [[ ("${DESTINATION}" != "" && "${CLONE}" != "") && -z "${VERSION}" ]] ; then echo "Destination / clone was set but version was not!"; exit 1;fi
if [[ "${DESTINATION}" != "" && "${CLONE}" == "yes" ]] ; then echo "Destination and clone was set. Pick one!"; exit 1;fi
}
# Prints the usage
function print_usage() {
cat <<EOF
The idea of this script is to update gh-pages branch with the generated docs. Without any options
the script will work in the following manner:
- if there's no gh-pages / target for docs module then the script ends
- for master branch the generated docs are copied to the root of gh-pages branch
- for any other branch (if that branch is allowed) a subfolder with branch name is created
and docs are copied there
- if the version switch is passed (-v) then a tag with (v) prefix will be retrieved and a folder
with that version number will be created in the gh-pages branch. WARNING! No allow verification will take place
- if the destination switch is passed (-d) then the script will check if the provided dir is a git repo and then will
switch to gh-pages of that repo and copy the generated docs to `docs/<project-name>/<version>`
- if the destination switch is passed (-d) then the script will check if the provided dir is a git repo and then will
switch to gh-pages of that repo and copy the generated docs to `docs/<project-name>/<version>`
USAGE:
You can use the following options:
-v|--version - the script will apply the whole procedure for a particular library version
-d|--destination - the root of destination folder where the docs should be copied. You have to use the full path.
E.g. point to spring-cloud-static folder. Can't be used with (-c)
-b|--build - will run the standard build process after checking out the branch
-c|--clone - will automatically clone the spring-cloud-static repo instead of providing the destination.
Obviously can't be used with (-d)
EOF
}
# ==========================================
# ____ ____ _____ _____ _____ _______
# / ____|/ ____| __ \|_ _| __ \__ __|
# | (___ | | | |__) | | | | |__) | | |
# \___ \| | | _ / | | | ___/ | |
# ____) | |____| | \ \ _| |_| | | |
# |_____/ \_____|_| \_\_____|_| |_|
#
# ==========================================
while [[ $# > 0 ]]
do
key="$1"
case ${key} in
-v|--version)
VERSION="$2"
shift # past argument
;;
-d|--destination)
DESTINATION="$2"
shift # past argument
;;
-b|--build)
BUILD="yes"
;;
-c|--clone)
CLONE="yes"
;;
-h|--help)
print_usage
exit 0
;;
*)
echo "Invalid option: [$1]"
print_usage
exit 1
;;
esac
shift # past argument or value
done
assert_properties
set_default_props
check_if_anything_to_sync
if [[ -z "${VERSION}" ]] ; then
retrieve_current_branch
else
switch_to_tag
fi
build_docs_if_applicable
retrieve_doc_properties
stash_changes
add_docs_from_target
checkout_previous_branch

36
mvnw vendored
View File

@@ -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
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
@@ -114,7 +114,6 @@ if $mingw ; then
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
@@ -212,7 +211,11 @@ else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
@@ -221,22 +224,38 @@ else
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
wget "$jarUrl" -O "$wrapperJarPath"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
curl -o "$wrapperJarPath" "$jarUrl"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
@@ -277,6 +296,11 @@ if $cygwin; then
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
exec "$JAVACMD" \

177
mvnw.bat
View File

@@ -1,177 +0,0 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@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
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@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_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
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
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"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto chkMHome
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:chkMHome
if not "%M2_HOME%"=="" goto valMHome
SET "M2_HOME=%~dp0.."
if not "%M2_HOME%"=="" goto valMHome
echo.
echo Error: M2_HOME not found in your environment. >&2
echo Please set the M2_HOME variable in your environment to match the >&2
echo location of the Maven installation. >&2
echo.
goto error
:valMHome
:stripMHome
if not "_%M2_HOME:~-1%"=="_\" goto checkMCmd
set "M2_HOME=%M2_HOME:~0,-1%"
goto stripMHome
:checkMCmd
if exist "%M2_HOME%\bin\mvn.cmd" goto init
echo.
echo Error: M2_HOME is set to an invalid directory. >&2
echo M2_HOME = "%M2_HOME%" >&2
echo Please set the M2_HOME variable in your environment to match the >&2
echo location of the Maven installation >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
set MAVEN_CMD_LINE_ARGS=%*
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
for %%i in ("%M2_HOME%"\boot\plexus-classworlds-*) do set CLASSWORLDS_JAR="%%i"
set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.home=%M2_HOME%" "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
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"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

343
mvnw.cmd vendored Executable file → Normal file
View File

@@ -1,161 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@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
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@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_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
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
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"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
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.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_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%
) 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%
)
@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% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
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"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@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 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
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@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 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
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@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
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"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
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.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_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% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_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('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@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
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
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"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

284
pom.xml
View File

@@ -1,258 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<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">
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-consul</artifactId>
<version>4.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Spring Cloud Consul</name>
<description>Spring Cloud Consul</description>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-build</artifactId>
<version>4.1.0-SNAPSHOT</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<properties>
<spring-cloud-bus.version>4.1.0-SNAPSHOT</spring-cloud-bus.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>
<spring-cloud-deployer.version>2.8.3</spring-cloud-deployer.version>
<spring-cloud-openfeign.version>4.1.0-SNAPSHOT</spring-cloud-openfeign.version>
<spring-cloud-stream.version>4.1.0-SNAPSHOT</spring-cloud-stream.version>
<testcontainers.version>1.17.6</testcontainers.version>
<mockserverclient.version>5.15.0</mockserverclient.version>
</properties>
<artifactId>spring-cloud-consul-docs-build</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Spring Cloud Consul Docs Build</name>
<description>Builds Spring Cloud Consul Docs.</description>
<url>https://spring.io/projects/spring-cloud-consul</url>
<scm>
<url>https://github.com/spring-cloud/spring-cloud-consul</url>
<connection>scm:git:git://github.com/spring-cloud/spring-cloud-consul.git
<connection>scm:git:https://github.com/spring-cloud/spring-cloud-consul.git
</connection>
<developerConnection>
scm:git:ssh://git@github.com/spring-cloud/spring-cloud-consul.git
scm:git:git@github.com:spring-cloud/spring-cloud-consul.git
</developerConnection>
<tag>HEAD</tag>
<url>https://github.com/spring-cloud/spring-cloud-consul</url>
</scm>
<issueManagement>
<url>https://github.com/spring-cloud/spring-cloud-consul/issues</url>
</issueManagement>
<properties>
<io.spring.maven.antora-version>0.0.3</io.spring.maven.antora-version>
</properties>
<modules>
<module>spring-cloud-consul-dependencies</module>
<module>spring-cloud-consul-core</module>
<module>spring-cloud-consul-config</module>
<module>spring-cloud-consul-discovery</module>
<module>spring-cloud-consul-binder</module>
<module>spring-cloud-consul-integration-tests</module>
<module>spring-cloud-starter-consul</module>
<module>spring-cloud-starter-consul-bus</module>
<module>spring-cloud-starter-consul-config</module>
<module>spring-cloud-starter-consul-discovery</module>
<module>spring-cloud-starter-consul-all</module>
<module>docs</module>
</modules>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<groupId>io.spring.maven.antora</groupId>
<artifactId>antora-maven-plugin</artifactId>
<version>${io.spring.maven.antora-version}</version>
<extensions>true</extensions>
<configuration>
<source>1.8</source>
<target>1.8</target>
<options>
<option>--to-dir=target/antora/site</option>
<option>--stacktrace</option>
<option>--fetch</option>
</options>
<environment>
<ALGOLIA_API_KEY>9d489079e5ec46dbb238909fee5c9c29</ALGOLIA_API_KEY>
<ALGOLIA_APP_ID>WB1FQYI187</ALGOLIA_APP_ID>
<ALGOLIA_INDEX_NAME>springcloudconsul</ALGOLIA_INDEX_NAME>
</environment>
</configuration>
</plugin>
<plugin>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</reporting>
<repositories>
<repository>
<id>spring-snapshot</id>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-consul-dependencies</artifactId>
<version>${project.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-deployer-local</artifactId>
<version>${spring-cloud-deployer.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-test</artifactId>
<version>${spring-cloud-stream.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-dependencies</artifactId>
<version>${spring-cloud-stream.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-bus-dependencies</artifactId>
<version>${spring-cloud-bus.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons-dependencies</artifactId>
<version>${spring-cloud-commons.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-test-support</artifactId>
<scope>test</scope>
<version>${spring-cloud-commons.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-dependencies</artifactId>
<version>${spring-cloud-config.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign-dependencies</artifactId>
<version>${spring-cloud-openfeign.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>consul</artifactId>
<version>${testcontainers.version}</version>
</dependency>
<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.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.16</version>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-client-java</artifactId>
<version>${mockserverclient.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<profiles>
<profile>
<id>spring</id>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/release</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
</project>

View File

@@ -1,3 +0,0 @@
#!/bin/bash
./mvnw clean install -B -Pdocs ${@}

View File

@@ -1,3 +0,0 @@
#!/bin/bash
./mvnw clean install -B -Pdocs -DskipTests -fae

View File

@@ -1,19 +0,0 @@
#!/bin/bash
set -o errexit
mkdir -p target
SCRIPT_URL="https://raw.githubusercontent.com/spring-cloud-samples/brewery/2021.0.x/runAcceptanceTests.sh"
AT_WHAT_TO_TEST="CONSUL"
cd target
curl "${SCRIPT_URL}" --output runAcceptanceTests.sh
chmod +x runAcceptanceTests.sh
echo "Killing all running apps"
./runAcceptanceTests.sh -t "${AT_WHAT_TO_TEST}" -n
./runAcceptanceTests.sh --whattotest "${AT_WHAT_TO_TEST}" --killattheend

View File

@@ -1,90 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>
<artifactId>spring-cloud-consul-binder</artifactId>
<packaging>jar</packaging>
<name>Spring Cloud Consul Binder</name>
<description>Spring Cloud Consul Binder</description>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-consul</artifactId>
<version>4.1.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-consul-core</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
</dependency>
<dependency>
<groupId>com.ecwid.consul</groupId>
<artifactId>consul-api</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-deployer-local</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-test-support</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8-standalone</artifactId>
<version>2.35.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>4.0.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>consul</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-consul-core</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -1,71 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.binder;
import org.springframework.cloud.stream.binder.AbstractBinder;
import org.springframework.cloud.stream.binder.Binding;
import org.springframework.cloud.stream.binder.ConsumerProperties;
import org.springframework.cloud.stream.binder.DefaultBinding;
import org.springframework.cloud.stream.binder.ProducerProperties;
import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.util.Assert;
/**
* @author Spencer Gibb
*/
public class ConsulBinder extends AbstractBinder<MessageChannel, ConsumerProperties, ProducerProperties> {
private static final String BEAN_NAME_TEMPLATE = "outbound.%s";
private final EventService eventService;
public ConsulBinder(EventService eventService) {
this.eventService = eventService;
}
@Override
protected Binding<MessageChannel> doBindConsumer(String name, String group, MessageChannel inputChannel,
ConsumerProperties properties) {
ConsulInboundMessageProducer messageProducer = new ConsulInboundMessageProducer(this.eventService);
messageProducer.setOutputChannel(inputChannel);
messageProducer.setBeanFactory(this.getBeanFactory());
messageProducer.afterPropertiesSet();
messageProducer.start();
return new DefaultBinding<>(name, group, inputChannel, messageProducer);
}
@Override
protected Binding<MessageChannel> doBindProducer(String name, MessageChannel channel,
ProducerProperties properties) {
Assert.isInstanceOf(SubscribableChannel.class, channel);
this.logger.debug("Binding Consul client to eventName " + name);
ConsulSendingHandler sendingHandler = new ConsulSendingHandler(this.eventService.getConsulClient(), name);
EventDrivenConsumer consumer = new EventDrivenConsumer((SubscribableChannel) channel, sendingHandler);
consumer.setBeanFactory(getBeanFactory());
consumer.setBeanName(String.format(BEAN_NAME_TEMPLATE, name));
consumer.afterPropertiesSet();
consumer.start();
return new DefaultBinding<>(name, null, channel, consumer);
}
}

View File

@@ -1,122 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.binder;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import com.ecwid.consul.v1.OperationException;
import com.ecwid.consul.v1.event.model.Event;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.endpoint.MessageProducerSupport;
import static org.springframework.util.Base64Utils.decodeFromString;
/**
* Adapter that receives Messages from Consul Events, converts them into Spring
* Integration Messages, and sends the results to a Message Channel.
*
* @author Spencer Gibb
*/
public class ConsulInboundMessageProducer extends MessageProducerSupport {
protected static final Log logger = LogFactory.getLog(ConsulInboundMessageProducer.class);
private final ScheduledExecutorService scheduler;
private final Runnable eventsRunnable;
private EventService eventService;
private ScheduledFuture<?> eventsHandle;
public ConsulInboundMessageProducer(EventService eventService) {
this.eventService = eventService;
this.scheduler = Executors.newScheduledThreadPool(1);
this.eventsRunnable = new Runnable() {
@Override
public void run() {
getEvents();
}
};
}
// link eventService to sendMessage
/*
* Map<String, Object> headers =
* headerMapper.toHeadersFromRequest(message.getMessageProperties()); if
* (messageListenerContainer.getAcknowledgeMode() == AcknowledgeMode.MANUAL) {
* headers.put(AmqpHeaders.DELIVERY_TAG,
* message.getMessageProperties().getDeliveryTag()); headers.put(AmqpHeaders.CHANNEL,
* channel); }
* sendMessage(AmqpInboundChannelAdapter.this.getMessageBuilderFactory().withPayload
* (payload).copyHeaders(headers).build());
*/
// start thread
// make blocking calls
// foreach event -> send message
@Override
protected void doStart() {
// TODO: make configurable
this.eventsHandle = this.scheduler.scheduleWithFixedDelay(this.eventsRunnable, 500, 500, TimeUnit.MILLISECONDS);
}
@Override
protected void doStop() {
if (this.eventsHandle != null) {
this.eventsHandle.cancel(true);
}
this.scheduler.shutdown();
}
// @Scheduled(fixedDelayString = "${spring.cloud.consul.binder.eventDelay:30000}")
public void getEvents() {
try {
List<Event> events = this.eventService.watch();
for (Event event : events) {
// Map<String, Object> headers = new HashMap<>();
// headers.put(MessageHeaders.REPLY_CHANNEL, outputChannel.)
String decoded = new String(decodeFromString(event.getPayload()));
sendMessage(getMessageBuilderFactory().withPayload(decoded)
// TODO: support headers
.build());
}
}
catch (OperationException e) {
if (logger.isErrorEnabled()) {
logger.error("Error getting consul events: " + e);
}
}
catch (Exception e) {
if (logger.isErrorEnabled()) {
logger.error("Error getting consul events: " + e.getMessage());
}
if (logger.isDebugEnabled()) {
logger.debug("Error getting consul events", e);
}
}
}
}

View File

@@ -1,64 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.binder;
import java.util.Arrays;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.event.model.Event;
import com.ecwid.consul.v1.event.model.EventParams;
import org.springframework.integration.handler.AbstractMessageHandler;
import org.springframework.messaging.Message;
/**
* Adapter that converts and sends Messages as Consul events.
*
* @author Spencer Gibb
*/
public class ConsulSendingHandler extends AbstractMessageHandler {
private final ConsulClient consul;
private final String eventName;
public ConsulSendingHandler(ConsulClient consul, String eventName) {
this.consul = consul;
this.eventName = eventName;
}
@Override
protected void handleMessageInternal(Message<?> message) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("Publishing message" + message);
}
Object payload = message.getPayload();
if (payload instanceof byte[]) {
payload = Arrays.toString((byte[]) payload);
}
// TODO: support headers
// TODO: support consul event filters: NodeFilter, ServiceFilter, TagFilter
Response<Event> event = this.consul.eventFire(this.eventName, (String) payload, new EventParams(),
QueryParams.DEFAULT);
// TODO: return event?
}
}

View File

@@ -1,134 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.binder;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.event.EventListRequest;
import com.ecwid.consul.v1.event.model.Event;
import com.ecwid.consul.v1.event.model.EventParams;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import org.springframework.cloud.consul.binder.config.ConsulBinderProperties;
/**
* @author Spencer Gibb
*/
public class EventService {
protected ConsulBinderProperties properties;
protected ConsulClient consul;
protected ObjectMapper objectMapper = new ObjectMapper();
private AtomicReference<Long> lastIndex = new AtomicReference<>();
public EventService(ConsulBinderProperties properties, ConsulClient consul, ObjectMapper objectMapper) {
this.properties = properties;
this.consul = consul;
this.objectMapper = objectMapper;
}
public ConsulClient getConsulClient() {
return this.consul;
}
@PostConstruct
public void init() {
setLastIndex(getEventsResponse());
}
public Long getLastIndex() {
return this.lastIndex.get();
}
private void setLastIndex(Response<?> response) {
Long consulIndex = response.getConsulIndex();
if (consulIndex != null) {
this.lastIndex.set(response.getConsulIndex());
}
}
public Event fire(String name, String payload) {
Response<Event> response = this.consul.eventFire(name, payload, new EventParams(), QueryParams.DEFAULT);
return response.getValue();
}
public Response<List<Event>> getEventsResponse() {
return this.consul.eventList(EventListRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
}
public List<Event> getEvents() {
return getEventsResponse().getValue();
}
public List<Event> getEvents(Long lastIndex) {
return filterEvents(readEvents(getEventsResponse()), lastIndex);
}
public List<Event> watch() {
return watch(this.lastIndex.get());
}
public List<Event> watch(Long lastIndex) {
// TODO: parameterized or configurable watch time
long index = -1;
if (lastIndex != null) {
index = lastIndex;
}
int eventTimeout = 5;
if (this.properties != null) {
eventTimeout = this.properties.getEventTimeout();
}
Response<List<Event>> watch = this.consul
.eventList(EventListRequest.newBuilder().setQueryParams(new QueryParams(eventTimeout, index)).build());
return filterEvents(readEvents(watch), lastIndex);
}
protected List<Event> readEvents(Response<List<Event>> response) {
setLastIndex(response);
return response.getValue();
}
/**
* from https://github.com/hashicorp/consul/blob/master/watch/funcs.go#L169-L194 .
* @param toFilter events to filter
* @param lastIndex last index to pick from the list of events
* @return filtered list of events
*/
protected List<Event> filterEvents(List<Event> toFilter, Long lastIndex) {
List<Event> events = toFilter;
if (lastIndex != null) {
for (int i = 0; i < events.size(); i++) {
Event event = events.get(i);
Long eventIndex = event.getWaitIndex();
if (lastIndex.equals(eventIndex)) {
events = events.subList(i + 1, events.size());
break;
}
}
}
return events;
}
}

View File

@@ -1,67 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.binder.config;
import com.ecwid.consul.v1.ConsulClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.cloud.consul.ConditionalOnConsulEnabled;
import org.springframework.cloud.consul.binder.ConsulBinder;
import org.springframework.cloud.consul.binder.EventService;
import org.springframework.cloud.stream.binder.Binder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Configures the Consul binder.
*
* @author Spencer Gibb
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(Binder.class)
@Import({ PropertyPlaceholderAutoConfiguration.class })
@ConditionalOnConsulEnabled
@ConditionalOnProperty(name = "spring.cloud.consul.binder.enabled", matchIfMissing = true)
// FIXME: boot 2.0.0 @EnableConfigurationProperties({ConsulBinderProperties.class})
public class ConsulBinderConfiguration {
// @Autowired
// private ConsulBinderProperties consulBinderProperties;
@Autowired(required = false)
protected ObjectMapper objectMapper = new ObjectMapper();
@Bean
@ConditionalOnMissingBean
public EventService eventService(ConsulClient consulClient) {
return new EventService(null/* consulBinderProperties */, consulClient, this.objectMapper);
}
@Bean
@ConditionalOnMissingBean
public ConsulBinder consulClientBinder(EventService eventService) {
return new ConsulBinder(eventService);
}
// TODO: create consul client if needed
}

View File

@@ -1,46 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.binder.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.style.ToStringCreator;
/**
* @author Spencer Gibb
*/
@ConfigurationProperties("spring.cloud.stream.consul.binder")
public class ConsulBinderProperties {
private int eventTimeout = 5;
public ConsulBinderProperties() {
}
public int getEventTimeout() {
return this.eventTimeout;
}
public void setEventTimeout(int eventTimeout) {
this.eventTimeout = eventTimeout;
}
@Override
public String toString() {
return new ToStringCreator(this).append("eventTimeout", this.eventTimeout).toString();
}
}

View File

@@ -1,17 +0,0 @@
#
# Copyright 2013-2016 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
#
spring.cloud.stream.binder.consul.default.host=localhost
spring.cloud.stream.binder.consul.default.port=8500

View File

@@ -1,2 +0,0 @@
consul:\
org.springframework.cloud.consul.binder.config.ConsulBinderConfiguration

View File

@@ -1,128 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.binder;
import java.util.concurrent.TimeUnit;
import com.ecwid.consul.v1.ConsulClient;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.consul.test.ConsulTestcontainers;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
/**
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulBinderApplicationTests.Application.class)
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
// FIXME: 4.0.0 https://github.com/spring-cloud/spring-cloud-consul/issues/763
@Ignore("update to stream 4.0.0 testing")
public class ConsulBinderApplicationTests {
@Rule
public final WireMockRule wireMock = new WireMockRule(18500);
@Autowired
private Events events;
@Before
public void setUp() throws Exception {
this.wireMock.stubFor(put(urlPathMatching("/v1/event/fire/purchases")).willReturn(aResponse().withStatus(200)));
/*
* wireMock.stubFor(get(urlPathMatching("/v1/event/list"))
* .willReturn(aResponse().withBody("[]") .withStatus(200)
* .withHeader("X-Consul-Index", "1")));
*/
}
@Test
public void shouldInitializeConsulSource() {
assertThat(this.events).isNotNull();
}
@Test
public void shouldPublishTextConsulMessage() {
// given
final Message<String> message = MessageBuilder.withPayload("Hello Consul!").build();
// when
this.events.purchases().send(message);
// then
await().atMost(1, TimeUnit.SECONDS);
verify(1, putRequestedFor(urlPathMatching("/v1/event/fire/purchases")));
}
interface Events {
// @Output
MessageChannel purchases();
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
// @EnableBinding(Events.class)
public static class Application {
@Bean
public ConsulClient consulClient() {
return new ConsulClient("localhost", 18500);
}
@Bean
public EventService eventService(ConsulClient consulClient) {
EventService eventService = mock(EventService.class);
when(eventService.getConsulClient()).thenReturn(consulClient);
return eventService;
}
}
}

View File

@@ -1,379 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.binder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.consul.binder.test.consumer.TestConsumer;
import org.springframework.cloud.consul.binder.test.producer.TestProducer;
import org.springframework.cloud.deployer.spi.app.AppDeployer;
import org.springframework.cloud.deployer.spi.core.AppDefinition;
import org.springframework.cloud.deployer.spi.core.AppDeploymentRequest;
import org.springframework.cloud.deployer.spi.local.LocalAppDeployer;
import org.springframework.cloud.deployer.spi.local.LocalDeployerProperties;
import org.springframework.cloud.test.TestSocketUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link org.springframework.cloud.consul.binder.ConsulBinder}.
*
* @author Spencer Gibb
*/
public class ConsulBinderTests {
/**
* Payload of test message.
*/
public static final String MESSAGE_PAYLOAD = "hello world";
/**
* Name of binding used for producer and consumer bindings.
*/
public static final String BINDING_NAME = "test";
private static final Logger logger = LoggerFactory.getLogger(ConsulBinderTests.class);
/**
* Timeout value in milliseconds for operations to complete.
*/
private static final long TIMEOUT = 30000;
/**
* Deployer to launch producer and consumer test applications.
*/
private final AppDeployer deployer;
/**
* Rest template for communicating with producer/consumer test applications.
*/
private final RestTemplate restTemplate = new RestTemplate();
public ConsulBinderTests() {
LocalDeployerProperties properties = new LocalDeployerProperties();
properties.setDeleteFilesOnExit(false);
this.deployer = new ClasspathDeployer(properties);
}
/**
* Test basic message sending functionality.
* @throws InterruptedException when waiting for message was interrupted
*/
@Test
@Ignore // FIXME: 2.0.0 need stream fix
public void testMessageSendReceive() throws InterruptedException {
testMessageSendReceive(null);
}
/**
* Test usage of partition selector.
* @throws Exception
*/
/*
* @Test public void testPartitionedMessageSendReceive() throws Exception {
* testMessageSendReceive(null, true); }
*/
/**
* Test consumer group functionality.
* @throws Exception
*/
/*
* @Test public void testMessageSendReceiveConsumerGroups() throws Exception {
* testMessageSendReceive(new String[]{"a", "b"}, false); }
*/
/**
* Test message sending functionality.
* @param groups consumer groups; may be {@code null}
* @throws InterruptedException when waiting for message was interrupted
*/
private void testMessageSendReceive(String[] groups) throws InterruptedException {
Set<AppId> consumers = null;
AppId producer = null;
try {
consumers = launchConsumers(groups);
producer = launchProducer();
for (AppId consumer : consumers) {
assertThat(waitForMessage(consumer.port)).isEqualTo(MESSAGE_PAYLOAD);
}
}
finally {
if (producer != null) {
shutdownApplication(producer.id);
}
if (consumers != null) {
for (AppId consumer : consumers) {
shutdownApplication(consumer.id);
}
}
}
}
/**
* Launch one or more consumers based on the number of consumer groups. Blocks
* execution until the consumers are bound.
* @param groups consumer groups; may be {@code null}
* @return a set of {@link AppId}s for the consumers
* @throws InterruptedException when waiting for message was interrupted
*/
private Set<AppId> launchConsumers(String[] groups) throws InterruptedException {
Set<AppId> consumers = new HashSet<>();
Map<String, String> appProperties = new HashMap<>();
int consumerCount = groups == null ? 1 : groups.length;
for (int i = 0; i < consumerCount; i++) {
int consumerPort = TestSocketUtils.findAvailableTcpPort();
appProperties.put("server.port", String.valueOf(consumerPort));
List<String> args = new ArrayList<>();
args.add(String.format("--server.port=%d", consumerPort));
args.add("--management.context-path=/");
args.add("--management.security.enabled=false");
args.add("--endpoints.shutdown.enabled=true");
args.add("--debug");
if (groups != null) {
args.add(String.format("--group=%s", groups[i]));
}
consumers.add(new AppId(launchApplication(TestConsumer.class, appProperties, args), consumerPort));
}
for (AppId app : consumers) {
waitForConsumer(app.port);
}
return consumers;
}
/**
* Launch a producer that publishes a test message.
* @return {@link AppId} for producer
*/
private AppId launchProducer() {
int producerPort = TestSocketUtils.findAvailableTcpPort();
Map<String, String> appProperties = new HashMap<>();
appProperties.put("server.port", String.valueOf(producerPort));
List<String> args = new ArrayList<>();
args.add(String.format("--server.port=%d", producerPort));
args.add("--management.context-path=/");
args.add("--management.security.enabled=false");
args.add("--endpoints.shutdown.enabled=true");
args.add(String.format("--partitioned=%b", false));
args.add("--debug");
return new AppId(launchApplication(TestProducer.class, appProperties, args), producerPort);
}
/**
* Block the executing thread until the consumer is bound.
* @param port server port of the consumer application
* @throws InterruptedException if the thread is interrupted
* @throws AssertionError if the consumer is not bound after {@value #TIMEOUT}
* milliseconds
*/
private void waitForConsumer(int port) throws InterruptedException {
long start = System.currentTimeMillis();
while (System.currentTimeMillis() < start + TIMEOUT) {
if (isConsumerBound(port)) {
return;
}
else {
Thread.sleep(1000);
}
}
assertThat(isConsumerBound(port)).as("Consumer not bound").isTrue();
}
/**
* Return {@code true} if the consumer at the provided port is bound.
* @param port http port for consumer
* @return true if consumer is bound
*/
private boolean isConsumerBound(int port) {
try {
return this.restTemplate.getForObject(String.format("http://localhost:%d/is-bound", port), Boolean.class);
}
catch (ResourceAccessException e) {
logger.trace("isConsumerBound", e);
return false;
}
}
/**
* Return the most recent payload message a consumer received.
* @param port http port for consumer
* @return the most recent payload message a consumer received; may be {@code null}
*/
private String getConsumerMessagePayload(int port) {
try {
return this.restTemplate.getForObject(String.format("http://localhost:%d/message-payload", port),
String.class);
}
catch (ResourceAccessException e) {
logger.debug("getConsumerMessagePayload", e);
return null;
}
}
/**
* Return {@code true} if the producer made use of a custom partition selector.
* @param port http port for producer
* @return true if the producer used a custom partition selector
*/
private boolean partitionSelectorUsed(int port) {
try {
return this.restTemplate.getForObject(String.format("http://localhost:%d/partition-strategy-invoked", port),
Boolean.class);
}
catch (ResourceAccessException e) {
logger.debug("partitionSelectorUsed", e);
return false;
}
}
/**
* Block the executing thread until a message is received by the consumer application,
* or until {@value #TIMEOUT} milliseconds elapses.
* @param port server port of the consumer application
* @return the message payload that was received
* @throws InterruptedException if the thread is interrupted
*/
private String waitForMessage(int port) throws InterruptedException {
long start = System.currentTimeMillis();
String message = null;
while (System.currentTimeMillis() < start + TIMEOUT) {
message = getConsumerMessagePayload(port);
if (message == null) {
Thread.sleep(1000);
}
else {
break;
}
}
return message;
}
/**
* Launch an application in a separate JVM.
* @param clz the main class to launch
* @param properties the properties to pass to the application
* @param args the command line arguments for the application
* @return a string identifier for the application
*/
private String launchApplication(Class<?> clz, Map<String, String> properties, List<String> args) {
Resource resource = new UrlResource(clz.getProtectionDomain().getCodeSource().getLocation());
properties.put(AppDeployer.GROUP_PROPERTY_KEY, "test-group");
properties.put("main", clz.getName());
properties.put("classpath", System.getProperty("java.class.path"));
String appName = String.format("%s-%s", clz.getSimpleName(), properties.get("server.port"));
AppDefinition definition = new AppDefinition(appName, properties);
AppDeploymentRequest request = new AppDeploymentRequest(definition, resource, properties, args);
return this.deployer.deploy(request);
}
/**
* Shut down the application with the provided id.
* @param id id of application to shut down
*/
private void shutdownApplication(String id) {
this.deployer.undeploy(id);
}
private static class ClasspathDeployer extends LocalAppDeployer {
/**
* Instantiates a new local app deployer.
* @param properties the properties
*/
ClasspathDeployer(LocalDeployerProperties properties) {
super(properties);
}
/**
* Builds the jar execution command.
* @param jarPath the jar path
* @param request the request
* @return the string[]
*/
protected String[] buildJarExecutionCommand(String jarPath, AppDeploymentRequest request) {
ArrayList<String> commands = new ArrayList<>();
commands.add(super.getLocalDeployerProperties().getJavaCmd());
commands.add("-cp");
commands.add(request.getDefinition().getProperties().get("classpath"));
commands.add(request.getDefinition().getProperties().get("main"));
commands.addAll(request.getCommandlineArguments());
return commands.toArray(new String[commands.size()]);
}
}
/**
* String identification and http port for a launched application.
*/
private static class AppId {
final String id;
final int port;
AppId(String id, int port) {
this.id = id;
this.port = port;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AppId appId = (AppId) o;
return this.port == appId.port && this.id.equals(appId.id);
}
@Override
public int hashCode() {
int result = this.id.hashCode();
result = 31 * result + this.port;
return result;
}
}
}

View File

@@ -1,47 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.binder;
import com.ecwid.consul.v1.OperationException;
import org.junit.Test;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Spencer Gibb
*/
public class ConsulInboundMessageProducerTests {
@Test
public void getEventsShouldNotThrowException() {
EventService eventService = mock(EventService.class);
when(eventService.watch()).thenThrow(new OperationException(500, "error", ""));
ConsulInboundMessageProducer producer = new ConsulInboundMessageProducer(eventService);
try {
producer.getEvents();
}
catch (Exception e) {
fail("ConsulInboundMessageProducer threw unexpected exception: " + e);
}
}
}

View File

@@ -1,70 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.binder.config;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.consul.test.ConsulTestcontainers;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.MessageChannel;
import static org.hamcrest.Matchers.containsString;
/**
* @author Spencer Gibb
*/
public class ConsulBinderConfigurationTests {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
@Ignore // FIXME 2.0.0 need stream fix
public void consulBinderDisabledWorks() {
this.exception.expectMessage(containsString("no proper implementation found"));
new SpringApplicationBuilder(Application.class).initializers(new ConsulTestcontainers())
.properties("spring.cloud.consul.binder.enabled=false").run();
}
@Test
@Ignore // FIXME 2.0.0 need stream fix
public void consulDisabledDisablesBinder() {
this.exception.expectMessage(containsString("no proper implementation found"));
new SpringApplicationBuilder(Application.class).initializers(new ConsulTestcontainers())
.properties("spring.cloud.consul.enabled=false").run();
}
interface Events {
// @Output
MessageChannel purchases();
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
// @EnableBinding(Events.class)
public static class Application {
}
}

View File

@@ -1,105 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.binder.test.consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.consul.binder.ConsulBinder;
import org.springframework.cloud.consul.binder.ConsulBinderTests;
import org.springframework.cloud.consul.binder.config.ConsulBinderConfiguration;
import org.springframework.cloud.stream.binder.ConsumerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.support.ExecutorSubscribableChannel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Consumer application that binds a channel to a {@link ConsulBinder} and stores the
* received message payload.
*/
@RestController
@Import(ConsulBinderConfiguration.class)
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
public class TestConsumer implements ApplicationRunner {
private static final Logger logger = LoggerFactory.getLogger(TestConsumer.class);
/**
* Flag that indicates if the consumer has been bound.
*/
private volatile boolean isBound = false;
/**
* Payload of last received message.
*/
private volatile String messagePayload;
@Autowired
private ConsulBinder binder;
/**
* Main method.
* @param args if present, first arg is consumer group name
*/
public static void main(String[] args) {
SpringApplication.run(TestConsumer.class, args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
logger.info("Consumer running with binder {}", this.binder);
SubscribableChannel consumerChannel = new ExecutorSubscribableChannel();
consumerChannel.subscribe(new MessageHandler() {
@Override
public void handleMessage(Message<?> message) throws MessagingException {
TestConsumer.this.messagePayload = (String) message.getPayload();
logger.info("Received message: {}", TestConsumer.this.messagePayload);
}
});
String group = null;
if (args.containsOption("group")) {
group = args.getOptionValues("group").get(0);
}
this.binder.bindConsumer(ConsulBinderTests.BINDING_NAME, group, consumerChannel, new ConsumerProperties());
this.isBound = true;
}
@GetMapping("/is-bound")
public boolean isBound() {
return this.isBound;
}
@GetMapping("/message-payload")
public String getMessagePayload() {
return this.messagePayload;
}
}

View File

@@ -1,107 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.binder.test.producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.consul.binder.ConsulBinder;
import org.springframework.cloud.consul.binder.ConsulBinderTests;
import org.springframework.cloud.consul.binder.config.ConsulBinderConfiguration;
import org.springframework.cloud.stream.binder.PartitionSelectorStrategy;
import org.springframework.cloud.stream.binder.ProducerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.messaging.Message;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.support.ExecutorSubscribableChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Producer application that binds a channel to a {@link ConsulBinder} and sends a test
* message.
*/
@RestController
@Import(ConsulBinderConfiguration.class)
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
public class TestProducer implements ApplicationRunner {
private static final Logger logger = LoggerFactory.getLogger(TestProducer.class);
@Autowired
private ConsulBinder binder;
public static void main(String[] args) {
SpringApplication.run(TestProducer.class, args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
/*
* if (args.containsOption("partitioned") &&
* Boolean.valueOf(args.getOptionValues("partitioned").get(0))) {
* binder.setPartitionSelector(stubPartitionSelectorStrategy()); }
*/
SubscribableChannel producerChannel = producerChannel();
ProducerProperties properties = new ProducerProperties();
properties.setPartitionKeyExpression(new SpelExpressionParser().parseExpression("payload"));
this.binder.bindProducer(ConsulBinderTests.BINDING_NAME, producerChannel, properties);
Message<String> message = new GenericMessage<>(ConsulBinderTests.MESSAGE_PAYLOAD);
logger.info("Writing message to binder {}", this.binder);
producerChannel.send(message);
}
@Bean
public SubscribableChannel producerChannel() {
return new ExecutorSubscribableChannel();
}
@Bean
public StubPartitionSelectorStrategy stubPartitionSelectorStrategy() {
return new StubPartitionSelectorStrategy();
}
@GetMapping("/partition-strategy-invoked")
public boolean partitionStrategyInvoked() {
return stubPartitionSelectorStrategy().invoked;
}
public static class StubPartitionSelectorStrategy implements PartitionSelectorStrategy {
public volatile boolean invoked = false;
@Override
public int selectPartition(Object key, int partitionCount) {
logger.info("Selecting partition for key {}; partition count: {}", key, partitionCount);
this.invoked = true;
return 1;
}
}
}

View File

@@ -1,13 +0,0 @@
spring:
cloud:
stream:
binders:
purchases:
type: consul
consul:
binder:
management:
security:
enabled: false
# host: localhost
# port: 18500

View File

@@ -1,99 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>
<artifactId>spring-cloud-consul-config</artifactId>
<packaging>jar</packaging>
<name>Spring Cloud Consul Config</name>
<description>Spring Cloud Consul Config</description>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-consul</artifactId>
<version>4.1.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.ecwid.consul</groupId>
<artifactId>consul-api</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-consul-core</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<optional>true</optional>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>consul</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-consul-core</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -1,261 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.kv.model.GetValue;
import io.micrometer.core.annotation.Timed;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.SmartLifecycle;
import org.springframework.core.style.ToStringCreator;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.FILES;
/**
* @author Spencer Gibb
*/
public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecycle {
private static final Log log = LogFactory.getLog(ConfigWatch.class);
private final ConsulConfigProperties properties;
private final ConsulClient consul;
private final TaskScheduler taskScheduler;
private final AtomicBoolean running = new AtomicBoolean(false);
private LinkedHashMap<String, Long> consulIndexes;
private ApplicationEventPublisher publisher;
private boolean firstTime = true;
private ScheduledFuture<?> watchFuture;
public ConfigWatch(ConsulConfigProperties properties, ConsulClient consul,
LinkedHashMap<String, Long> initialIndexes) {
this(properties, consul, initialIndexes, getTaskScheduler());
}
public ConfigWatch(ConsulConfigProperties properties, ConsulClient consul,
LinkedHashMap<String, Long> initialIndexes, TaskScheduler taskScheduler) {
this.properties = properties;
this.consul = consul;
this.consulIndexes = new LinkedHashMap<>(initialIndexes);
this.taskScheduler = taskScheduler;
}
private static ThreadPoolTaskScheduler getTaskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
return taskScheduler;
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
@Override
public void start() {
if (this.running.compareAndSet(false, true)) {
this.watchFuture = this.taskScheduler.scheduleWithFixedDelay(this::watchConfigKeyValues,
this.properties.getWatch().getDelay());
}
}
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public void stop(Runnable callback) {
this.stop();
callback.run();
}
@Override
public int getPhase() {
return 0;
}
@Override
public void stop() {
if (this.running.compareAndSet(true, false) && this.watchFuture != null) {
this.watchFuture.cancel(true);
}
}
@Override
public boolean isRunning() {
return this.running.get();
}
@Timed("consul.watch-config-keys")
public void watchConfigKeyValues() {
if (!this.running.get()) {
return;
}
for (String context : this.consulIndexes.keySet()) {
// turn the context into a Consul folder path (unless our config format
// are FILES)
if (this.properties.getFormat() != FILES && !context.endsWith("/")) {
context = context + "/";
}
try {
Long currentIndex = this.consulIndexes.get(context);
if (currentIndex == null) {
currentIndex = -1L;
}
if (log.isTraceEnabled()) {
log.trace("watching consul for context '" + context + "' with index " + currentIndex);
}
// use the consul ACL token if found
String aclToken = this.properties.getAclToken();
if (ObjectUtils.isEmpty(aclToken)) {
aclToken = null;
}
Response<List<GetValue>> response = this.consul.getKVValues(context, aclToken,
new QueryParams(this.properties.getWatch().getWaitTime(), currentIndex));
// if response.value == null, response was a 404, otherwise it was a
// 200, reducing churn if there wasn't anything
if (response.getValue() != null && !response.getValue().isEmpty()) {
Long newIndex = response.getConsulIndex();
if (newIndex != null && !newIndex.equals(currentIndex)) {
// don't publish the same index again, don't publish the first
// time (-1) so index can be primed
if (!this.consulIndexes.containsValue(newIndex) && !currentIndex.equals(-1L)) {
if (log.isTraceEnabled()) {
log.trace("Context " + context + " has new index " + newIndex);
}
RefreshEventData data = new RefreshEventData(context, currentIndex, newIndex);
this.publisher.publishEvent(new RefreshEvent(this, data, data.toString()));
}
else if (log.isTraceEnabled()) {
log.trace("Event for index already published for context " + context);
}
this.consulIndexes.put(context, newIndex);
}
else if (log.isTraceEnabled()) {
log.trace("Same index for context " + context);
}
}
else if (log.isTraceEnabled()) {
log.trace("No value for context " + context);
}
}
catch (Exception e) {
// only fail fast on the initial query, otherwise just log the error
if (this.firstTime && this.properties.isFailFast()) {
log.error("Fail fast is set and there was an error reading configuration from consul.");
ReflectionUtils.rethrowRuntimeException(e);
}
else if (log.isTraceEnabled()) {
log.trace("Error querying consul Key/Values for context '" + context + "'", e);
}
else if (log.isWarnEnabled()) {
// simplified one line log message in the event of an agent
// failure
log.warn("Error querying consul Key/Values for context '" + context + "'. Message: "
+ e.getMessage());
}
}
}
this.firstTime = false;
}
public static class RefreshEventData {
private final String context;
private final Long prevIndex;
private final Long newIndex;
RefreshEventData(String context, Long prevIndex, Long newIndex) {
this.context = context;
this.prevIndex = prevIndex;
this.newIndex = newIndex;
}
public String getContext() {
return this.context;
}
public Long getPrevIndex() {
return this.prevIndex;
}
public Long getNewIndex() {
return this.newIndex;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RefreshEventData that = (RefreshEventData) o;
return Objects.equals(this.context, that.context) && Objects.equals(this.prevIndex, that.prevIndex)
&& Objects.equals(this.newIndex, that.newIndex);
}
@Override
public int hashCode() {
return Objects.hash(this.context, this.prevIndex, this.newIndex);
}
@Override
public String toString() {
return new ToStringCreator(this).append("context", this.context).append("prevIndex", this.prevIndex)
.append("newIndex", this.newIndex).toString();
}
}
}

View File

@@ -1,125 +0,0 @@
/*
* Copyright 2015-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.function.BiFunction;
import java.util.function.Function;
import com.ecwid.consul.v1.ConsulClient;
import org.springframework.boot.BootstrapContext;
import org.springframework.boot.BootstrapRegistry;
import org.springframework.boot.BootstrapRegistryInitializer;
import org.springframework.boot.context.config.ConfigData;
import org.springframework.boot.context.config.ConfigDataLoaderContext;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.cloud.consul.ConsulProperties;
import org.springframework.util.Assert;
public class ConsulBootstrapper implements BootstrapRegistryInitializer {
private Function<BootstrapContext, ConsulClient> consulClientFactory;
private LoaderInterceptor loaderInterceptor;
static BootstrapRegistryInitializer fromConsulProperties(Function<ConsulProperties, ConsulClient> factory) {
return registry -> registry.register(ConsulClient.class, context -> {
ConsulProperties properties = context.get(ConsulProperties.class);
return factory.apply(properties);
});
}
static BootstrapRegistryInitializer fromBootstrapContext(Function<BootstrapContext, ConsulClient> factory) {
return registry -> registry.register(ConsulClient.class, factory::apply);
}
static ConsulBootstrapper create() {
return new ConsulBootstrapper();
}
// TODO: document there will be a ConsulProperties in BootstrapContext
public ConsulBootstrapper withConsulClientFactory(Function<BootstrapContext, ConsulClient> consulClientFactory) {
this.consulClientFactory = consulClientFactory;
return this;
}
public ConsulBootstrapper withLoaderInterceptor(LoaderInterceptor loaderInterceptor) {
this.loaderInterceptor = loaderInterceptor;
return this;
}
@Override
public void initialize(BootstrapRegistry registry) {
if (consulClientFactory != null) {
registry.register(ConsulClient.class, consulClientFactory::apply);
}
if (loaderInterceptor != null) {
registry.register(LoaderInterceptor.class, BootstrapRegistry.InstanceSupplier.of(loaderInterceptor));
}
}
public interface LoaderInterceptor extends Function<LoadContext, ConfigData> {
}
@FunctionalInterface
public interface LoaderInvocation
extends BiFunction<ConfigDataLoaderContext, ConsulConfigDataResource, ConfigData> {
}
public static class LoadContext {
private final ConfigDataLoaderContext loaderContext;
private final ConsulConfigDataResource resource;
private final Binder binder;
private final LoaderInvocation invocation;
LoadContext(ConfigDataLoaderContext loaderContext, ConsulConfigDataResource resource, Binder binder,
LoaderInvocation invocation) {
Assert.notNull(loaderContext, "loaderContext may not be null");
Assert.notNull(resource, "resource may not be null");
Assert.notNull(binder, "binder may not be null");
Assert.notNull(invocation, "invocation may not be null");
this.loaderContext = loaderContext;
this.resource = resource;
this.binder = binder;
this.invocation = invocation;
}
public ConfigDataLoaderContext getLoaderContext() {
return this.loaderContext;
}
public ConsulConfigDataResource getResource() {
return this.resource;
}
public Binder getBinder() {
return this.binder;
}
public LoaderInvocation getInvocation() {
return this.invocation;
}
}
}

View File

@@ -1,66 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import com.ecwid.consul.v1.ConsulClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.consul.ConditionalOnConsulEnabled;
import org.springframework.cloud.endpoint.RefreshEndpoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* @author Spencer Gibb
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnConsulEnabled
@ConditionalOnProperty(name = "spring.cloud.consul.config.enabled", matchIfMissing = true)
@EnableConfigurationProperties
public class ConsulConfigAutoConfiguration {
/**
* Name of the config watch task scheduler bean.
*/
public static final String CONFIG_WATCH_TASK_SCHEDULER_NAME = "configWatchTaskScheduler";
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RefreshEndpoint.class)
@ConditionalOnProperty(name = "spring.cloud.consul.config.watch.enabled", matchIfMissing = true)
protected static class ConsulRefreshConfiguration {
@Bean
@ConditionalOnBean(ConsulConfigIndexes.class)
public ConfigWatch configWatch(ConsulConfigProperties properties, ConsulConfigIndexes indexes,
ConsulClient consul, @Qualifier(CONFIG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) {
return new ConfigWatch(properties, consul, indexes.getIndexes(), taskScheduler);
}
@Bean(name = CONFIG_WATCH_TASK_SCHEDULER_NAME)
public TaskScheduler configWatchTaskScheduler() {
return new ThreadPoolTaskScheduler();
}
}
}

View File

@@ -1,67 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import com.ecwid.consul.v1.ConsulClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.consul.ConditionalOnConsulEnabled;
import org.springframework.cloud.consul.ConsulAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.util.ObjectUtils;
/**
* @author Spencer Gibb
* @author Edvin Eriksson
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnConsulEnabled
public class ConsulConfigBootstrapConfiguration {
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
@Import(ConsulAutoConfiguration.class)
@ConditionalOnProperty(name = "spring.cloud.consul.config.enabled", matchIfMissing = true)
protected static class ConsulPropertySourceConfiguration {
@Autowired
private ConsulClient consul;
@Bean
@ConditionalOnMissingBean
public ConsulConfigProperties consulConfigProperties(Environment env) {
ConsulConfigProperties properties = new ConsulConfigProperties();
if (ObjectUtils.isEmpty(properties.getName())) {
properties.setName(env.getProperty("spring.application.name", "application"));
}
return properties;
}
@Bean
public ConsulPropertySourceLocator consulPropertySourceLocator(ConsulConfigProperties consulConfigProperties) {
return new ConsulPropertySourceLocator(this.consul, consulConfigProperties);
}
}
}

View File

@@ -1,109 +0,0 @@
/*
* Copyright 2015-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import com.ecwid.consul.v1.ConsulClient;
import org.apache.commons.logging.Log;
import org.springframework.boot.context.config.ConfigData;
import org.springframework.boot.context.config.ConfigData.Option;
import org.springframework.boot.context.config.ConfigData.Options;
import org.springframework.boot.context.config.ConfigDataLoader;
import org.springframework.boot.context.config.ConfigDataLoaderContext;
import org.springframework.boot.context.config.ConfigDataResourceNotFoundException;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.logging.DeferredLogFactory;
import org.springframework.cloud.consul.config.ConsulBootstrapper.LoadContext;
import org.springframework.cloud.consul.config.ConsulBootstrapper.LoaderInterceptor;
import org.springframework.util.StringUtils;
public class ConsulConfigDataLoader implements ConfigDataLoader<ConsulConfigDataResource> {
private static final EnumSet<Option> ALL_OPTIONS = EnumSet.allOf(Option.class);
private final Log log;
public ConsulConfigDataLoader(DeferredLogFactory logFactory) {
this.log = logFactory.getLog(ConsulConfigDataLoader.class);
}
@Override
public ConfigData load(ConfigDataLoaderContext context, ConsulConfigDataResource resource) {
if (context.getBootstrapContext().isRegistered(LoaderInterceptor.class)) {
LoaderInterceptor interceptor = context.getBootstrapContext().get(LoaderInterceptor.class);
if (interceptor != null) {
Binder binder = context.getBootstrapContext().get(Binder.class);
return interceptor.apply(new LoadContext(context, resource, binder, this::doLoad));
}
}
return doLoad(context, resource);
}
public ConfigData doLoad(ConfigDataLoaderContext context, ConsulConfigDataResource resource) {
try {
ConsulClient consul = getBean(context, ConsulClient.class);
ConsulConfigIndexes indexes = getBean(context, ConsulConfigIndexes.class);
ConsulPropertySource propertySource = resource.getConsulPropertySources()
.createPropertySource(resource.getContext(), consul, indexes.getIndexes()::put);
if (propertySource == null) {
return null;
}
List<ConsulPropertySource> propertySources = Collections.singletonList(propertySource);
if (ALL_OPTIONS.size() == 1) {
// boot 2.4.2 and prior
return new ConfigData(propertySources);
}
else if (ALL_OPTIONS.size() == 2) {
// boot 2.4.3 and 2.4.4
return new ConfigData(propertySources, Option.IGNORE_IMPORTS, Option.IGNORE_PROFILES);
}
else if (ALL_OPTIONS.size() > 2) {
// boot 2.4.5+
return new ConfigData(propertySources, source -> {
List<Option> options = new ArrayList<>();
options.add(Option.IGNORE_IMPORTS);
options.add(Option.IGNORE_PROFILES);
if (StringUtils.hasText(resource.getProfile())) {
options.add(Option.PROFILE_SPECIFIC);
}
return Options.of(options.toArray(new Option[0]));
});
}
}
catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Error getting properties from consul: " + resource, e);
}
throw new ConfigDataResourceNotFoundException(resource, e);
}
return null;
}
protected <T> T getBean(ConfigDataLoaderContext context, Class<T> type) {
if (context.getBootstrapContext().isRegistered(type)) {
return context.getBootstrapContext().get(type);
}
return null;
}
}

View File

@@ -1,239 +0,0 @@
/*
* Copyright 2015-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;
import com.ecwid.consul.v1.ConsulClient;
import org.apache.commons.logging.Log;
import org.springframework.boot.BootstrapContext;
import org.springframework.boot.BootstrapRegistry.InstanceSupplier;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.context.config.ConfigDataLocation;
import org.springframework.boot.context.config.ConfigDataLocationNotFoundException;
import org.springframework.boot.context.config.ConfigDataLocationResolver;
import org.springframework.boot.context.config.ConfigDataLocationResolverContext;
import org.springframework.boot.context.config.Profiles;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.logging.DeferredLogFactory;
import org.springframework.cloud.consul.ConsulAutoConfiguration;
import org.springframework.cloud.consul.ConsulProperties;
import org.springframework.cloud.consul.config.ConsulPropertySources.Context;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.FILES;
public class ConsulConfigDataLocationResolver implements ConfigDataLocationResolver<ConsulConfigDataResource> {
/**
* Consul ConfigData prefix.
*/
public static final String PREFIX = "consul:";
protected static final List<String> DIR_SUFFIXES = Collections.singletonList("/");
protected static final List<String> FILES_SUFFIXES = Collections
.unmodifiableList(Arrays.asList(".yml", ".yaml", ".properties"));
private final Log log;
public ConsulConfigDataLocationResolver(DeferredLogFactory logFactory) {
this.log = logFactory.getLog(ConsulConfigDataLocationResolver.class);
}
@Override
public boolean isResolvable(ConfigDataLocationResolverContext context, ConfigDataLocation location) {
if (!location.hasPrefix(PREFIX)) {
return false;
}
// only bind if correct prefix
boolean enabled = context.getBinder().bind(ConsulProperties.PREFIX + ".enabled", Boolean.class).orElse(true);
boolean configEnabled = context.getBinder().bind(ConsulConfigProperties.PREFIX + ".enabled", Boolean.class)
.orElse(true);
return configEnabled && enabled;
}
@Override
public List<ConsulConfigDataResource> resolve(ConfigDataLocationResolverContext context,
ConfigDataLocation location) throws ConfigDataLocationNotFoundException {
return Collections.emptyList();
}
@Override
public List<ConsulConfigDataResource> resolveProfileSpecific(ConfigDataLocationResolverContext resolverContext,
ConfigDataLocation location, Profiles profiles) throws ConfigDataLocationNotFoundException {
UriComponents locationUri = parseLocation(resolverContext, location);
// create consul client
registerBean(resolverContext, ConsulProperties.class, loadProperties(resolverContext, locationUri));
registerAndPromoteBean(resolverContext, ConsulClient.class, this::createConsulClient);
// create locations
ConsulConfigProperties properties = loadConfigProperties(resolverContext);
ConsulPropertySources consulPropertySources = new ConsulPropertySources(properties, log);
List<Context> contexts = (locationUri == null || CollectionUtils.isEmpty(locationUri.getPathSegments()))
? consulPropertySources.generateAutomaticContexts(profiles.getAccepted(), false)
: getCustomContexts(locationUri, properties);
registerAndPromoteBean(resolverContext, ConsulConfigProperties.class, InstanceSupplier.of(properties));
registerAndPromoteBean(resolverContext, ConsulConfigIndexes.class,
InstanceSupplier.from(ConsulConfigDataIndexes::new));
return contexts
.stream().map(propertySourceContext -> new ConsulConfigDataResource(propertySourceContext.getPath(),
properties, consulPropertySources, propertySourceContext.getProfile()))
.collect(Collectors.toList());
}
private BindHandler getBindHandler(ConfigDataLocationResolverContext context) {
return context.getBootstrapContext().getOrElse(BindHandler.class, null);
}
private List<Context> getCustomContexts(UriComponents uriComponents, ConsulConfigProperties properties) {
if (!StringUtils.hasText(uriComponents.getPath())) {
return Collections.emptyList();
}
List<Context> contexts = new ArrayList<>();
for (String path : uriComponents.getPath().split(";")) {
for (String suffix : getSuffixes(properties)) {
contexts.add(new Context(path + suffix));
}
}
return contexts;
}
protected List<String> getSuffixes(ConsulConfigProperties properties) {
if (properties.getFormat() == FILES) {
return FILES_SUFFIXES;
}
return DIR_SUFFIXES;
}
@Nullable
protected UriComponents parseLocation(ConfigDataLocationResolverContext context, ConfigDataLocation location) {
String originalLocation = location.getNonPrefixedValue(PREFIX);
if (!StringUtils.hasText(originalLocation)) {
return null;
}
String uri;
if (!originalLocation.startsWith("//")) {
uri = PREFIX + "//" + originalLocation;
}
else {
uri = originalLocation;
}
return UriComponentsBuilder.fromUriString(uri).build();
}
protected <T> void registerAndPromoteBean(ConfigDataLocationResolverContext context, Class<T> type,
InstanceSupplier<T> supplier) {
registerBean(context, type, supplier);
context.getBootstrapContext().addCloseListener(event -> {
T instance = event.getBootstrapContext().get(type);
String name = "configData" + type.getSimpleName();
ConfigurableApplicationContext appCtxt = event.getApplicationContext();
if (!appCtxt.containsBean(name)) {
appCtxt.getBeanFactory().registerSingleton(name, instance);
}
});
}
public <T> void registerBean(ConfigDataLocationResolverContext context, Class<T> type, T instance) {
context.getBootstrapContext().registerIfAbsent(type, InstanceSupplier.of(instance));
}
protected <T> void registerBean(ConfigDataLocationResolverContext context, Class<T> type,
InstanceSupplier<T> supplier) {
ConfigurableBootstrapContext bootstrapContext = context.getBootstrapContext();
bootstrapContext.registerIfAbsent(type, supplier);
}
protected ConsulClient createConsulClient(BootstrapContext context) {
ConsulProperties properties = context.get(ConsulProperties.class);
return ConsulAutoConfiguration.createConsulClient(properties,
ConsulAutoConfiguration.createConsulRawClientBuilder());
}
protected ConsulProperties loadProperties(ConfigDataLocationResolverContext resolverContext,
UriComponents location) {
Binder binder = resolverContext.getBinder();
ConsulProperties consulProperties = binder
.bind(ConsulProperties.PREFIX, Bindable.of(ConsulProperties.class), getBindHandler(resolverContext))
.orElseGet(ConsulProperties::new);
if (location != null) {
if (StringUtils.hasText(location.getHost())) {
consulProperties.setHost(location.getHost());
}
if (location.getPort() >= 0) {
consulProperties.setPort(location.getPort());
}
}
return consulProperties;
}
protected ConsulConfigProperties loadConfigProperties(ConfigDataLocationResolverContext resolverContext) {
Binder binder = resolverContext.getBinder();
BindHandler bindHandler = getBindHandler(resolverContext);
ConsulConfigProperties properties = binder
.bind(ConsulConfigProperties.PREFIX, Bindable.of(ConsulConfigProperties.class), bindHandler)
.orElseGet(ConsulConfigProperties::new);
if (!StringUtils.hasText(properties.getName())) {
properties.setName(binder.bind("spring.application.name", String.class).orElse("application"));
}
if (!StringUtils.hasText(properties.getAclToken())) {
properties.setAclToken(binder.bind("spring.cloud.consul.token", String.class)
.orElse(binder.bind("consul.token", String.class).orElse(null)));
}
return properties;
}
protected static class ConsulConfigDataIndexes implements ConsulConfigIndexes {
private final LinkedHashMap<String, Long> indexes = new LinkedHashMap<>();
@Override
public LinkedHashMap<String, Long> getIndexes() {
return indexes;
}
}
}

View File

@@ -1,85 +0,0 @@
/*
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor;
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer;
import org.springframework.boot.diagnostics.FailureAnalysis;
import org.springframework.cloud.commons.ConfigDataMissingEnvironmentPostProcessor;
import org.springframework.cloud.consul.ConsulProperties;
import org.springframework.core.env.Environment;
import static org.springframework.cloud.consul.config.ConsulConfigDataLocationResolver.PREFIX;
import static org.springframework.cloud.util.PropertyUtils.bootstrapEnabled;
import static org.springframework.cloud.util.PropertyUtils.useLegacyProcessing;
public class ConsulConfigDataMissingEnvironmentPostProcessor extends ConfigDataMissingEnvironmentPostProcessor {
/**
* Order of post processor, set to run after
* {@link ConfigDataEnvironmentPostProcessor}.
*/
public static final int ORDER = ConfigDataEnvironmentPostProcessor.ORDER + 1000;
@Override
public int getOrder() {
return ORDER;
}
@Override
protected boolean shouldProcessEnvironment(Environment environment) {
// don't run if using bootstrap or legacy processing
if (bootstrapEnabled(environment) || useLegacyProcessing(environment)) {
return false;
}
boolean coreEnabled = environment.getProperty(ConsulProperties.PREFIX + ".enabled", Boolean.class, true);
boolean configEnabled = environment.getProperty(ConsulConfigProperties.PREFIX + ".enabled", Boolean.class,
true);
boolean importCheckEnabled = environment.getProperty(ConsulConfigProperties.PREFIX + ".import-check.enabled",
Boolean.class, true);
if (!coreEnabled || !configEnabled || !importCheckEnabled) {
return false;
}
return true;
}
@Override
protected String getPrefix() {
return PREFIX;
}
static class ImportExceptionFailureAnalyzer extends AbstractFailureAnalyzer<ImportException> {
@Override
protected FailureAnalysis analyze(Throwable rootFailure, ImportException cause) {
String description;
if (cause.missingPrefix) {
description = "The spring.config.import property is missing a " + PREFIX + " entry";
}
else {
description = "No spring.config.import property has been defined";
}
String action = "Add a spring.config.import=consul: property to your configuration.\n"
+ "\tIf configuration is not required add spring.config.import=optional:consul: instead.\n"
+ "\tTo disable this check, set spring.cloud.consul.config.enabled=false or \n"
+ "\tspring.cloud.consul.config.import-check.enabled=false.";
return new FailureAnalysis(description, action, cause);
}
}
}

View File

@@ -1,107 +0,0 @@
/*
* Copyright 2015-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.Objects;
import org.springframework.boot.context.config.ConfigDataResource;
import org.springframework.core.style.ToStringCreator;
public class ConsulConfigDataResource extends ConfigDataResource {
private final ConsulConfigProperties properties;
private final String context;
private final boolean optional;
private final ConsulPropertySources consulPropertySources;
private final String profile;
public ConsulConfigDataResource(String context, ConsulConfigProperties properties,
ConsulPropertySources consulPropertySources, String profile) {
this.properties = properties;
this.context = context;
this.optional = true;
this.consulPropertySources = consulPropertySources;
this.profile = profile;
}
@Deprecated
public ConsulConfigDataResource(String context, ConsulConfigProperties properties,
ConsulPropertySources consulPropertySources) {
this(context, true, properties, consulPropertySources);
}
@Deprecated
public ConsulConfigDataResource(String context, boolean optional, ConsulConfigProperties properties,
ConsulPropertySources consulPropertySources) {
this.properties = properties;
this.context = context;
this.optional = optional;
this.consulPropertySources = consulPropertySources;
this.profile = null;
}
public String getContext() {
return this.context;
}
@Deprecated
public boolean isOptional() {
return this.optional;
}
public ConsulConfigProperties getProperties() {
return this.properties;
}
public ConsulPropertySources getConsulPropertySources() {
return this.consulPropertySources;
}
String getProfile() {
return this.profile;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConsulConfigDataResource that = (ConsulConfigDataResource) o;
return this.optional == that.optional && this.context.equals(that.context)
&& Objects.equals(this.profile, that.profile);
}
@Override
public int hashCode() {
return Objects.hash(this.context, this.optional, this.profile);
}
@Override
public String toString() {
return new ToStringCreator(this).append("context", context).append("optional", optional)
.append("properties", properties).append("profile", profile).toString();
}
}

View File

@@ -1,25 +0,0 @@
/*
* Copyright 2015-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.LinkedHashMap;
public interface ConsulConfigIndexes {
LinkedHashMap<String, Long> getIndexes();
}

View File

@@ -1,304 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import jakarta.annotation.PostConstruct;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.DeprecatedConfigurationProperty;
import org.springframework.core.style.ToStringCreator;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import static org.springframework.cloud.consul.config.ConsulConfigProperties.PREFIX;
/**
* @author Spencer Gibb
*/
@ConfigurationProperties(PREFIX)
@Validated
public class ConsulConfigProperties {
/**
* Prefix for configuration properties.
*/
public static final String PREFIX = "spring.cloud.consul.config";
private boolean enabled = true;
private List<String> prefixes = new ArrayList<>(Collections.singletonList("config"));
@NotEmpty
private String defaultContext = "application";
@NotEmpty
private String profileSeparator = ",";
@NotNull
private Format format = Format.KEY_VALUE;
/**
* If format is Format.PROPERTIES or Format.YAML then the following field is used as
* key to look up consul for configuration.
*/
@NotEmpty
private String dataKey = "data";
@Value("${consul.token:${CONSUL_TOKEN:${spring.cloud.consul.token:${SPRING_CLOUD_CONSUL_TOKEN:}}}}")
private String aclToken;
private Watch watch = new Watch();
/**
* Throw exceptions during config lookup if true, otherwise, log warnings.
*/
private boolean failFast = true;
/**
* Alternative to spring.application.name to use in looking up values in consul KV.
*/
private String name;
public ConsulConfigProperties() {
}
@PostConstruct
public void init() {
if (this.format == Format.FILES) {
this.profileSeparator = "-";
}
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public List<String> getPrefixes() {
return this.prefixes;
}
public void setPrefixes(List<String> prefixes) {
this.prefixes = prefixes;
}
@DeprecatedConfigurationProperty(reason = "replaced to support multiple prefixes",
replacement = PREFIX + ".prefixes")
public String getPrefix() {
if (CollectionUtils.isEmpty(this.prefixes)) {
return null;
}
return this.prefixes.get(0);
}
@Deprecated
public void setPrefix(String prefix) {
if (prefix != null) {
this.prefixes = new ArrayList<>(Collections.singletonList(prefix));
}
else {
this.prefixes = new ArrayList<>();
}
}
public @NotEmpty String getDefaultContext() {
return this.defaultContext;
}
public void setDefaultContext(@NotEmpty String defaultContext) {
this.defaultContext = defaultContext;
}
public @NotEmpty String getProfileSeparator() {
return this.profileSeparator;
}
public void setProfileSeparator(@NotEmpty String profileSeparator) {
this.profileSeparator = profileSeparator;
}
public @NotNull Format getFormat() {
return this.format;
}
public void setFormat(@NotNull Format format) {
this.format = format;
}
public @NotEmpty String getDataKey() {
return this.dataKey;
}
public void setDataKey(@NotEmpty String dataKey) {
this.dataKey = dataKey;
}
public String getAclToken() {
return this.aclToken;
}
public void setAclToken(String aclToken) {
this.aclToken = aclToken;
}
public Watch getWatch() {
return this.watch;
}
public void setWatch(Watch watch) {
this.watch = watch;
}
public boolean isFailFast() {
return this.failFast;
}
public void setFailFast(boolean failFast) {
this.failFast = failFast;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return new ToStringCreator(this).append("enabled", this.enabled).append("prefixes", this.prefixes)
.append("defaultContext", this.defaultContext).append("profileSeparator", this.profileSeparator)
.append("format", this.format).append("dataKey", this.dataKey).append("aclToken", this.aclToken)
.append("watch", this.watch).append("failFast", this.failFast).append("name", this.name).toString();
}
/**
* There are many ways in which we can specify configuration in consul i.e.,
*
* <ol>
* <li>Nested key value style: Where value is either a constant or part of the key
* (nested). For e.g., For following configuration a.b.c=something a.b.d=something
* else One can specify the configuration in consul with key as
* "../kv/config/application/a/b/c" and value as "something" and key as
* "../kv/config/application/a/b/d" and value as "something else"</li>
* <li>Entire contents of properties file as value For e.g., For following
* configuration a.b.c=something a.b.d=something else One can specify the
* configuration in consul with key as "../kv/config/application/properties" and value
* as whole configuration " a.b.c=something a.b.d=something else "</li>
* <li>as Json or YML. You get it.</li>
* </ol>
*
* This enum specifies the different Formats/styles supported for loading the
* configuration.
*
* @author srikalyan.swayampakula
*/
public enum Format {
/**
* Indicates that the configuration specified in consul is of type native key
* values.
*/
KEY_VALUE,
/**
* Indicates that the configuration specified in consul is of property style i.e.,
* value of the consul key would be a list of key=value pairs separated by new
* lines.
*/
PROPERTIES,
/**
* Indicates that the configuration specified in consul is of YAML style i.e.,
* value of the consul key would be YAML format.
*/
YAML,
/**
* Indicates that the configuration specified in consul uses keys as files. This
* is useful for tools like git2consul.
*/
FILES,
}
/**
* Consul watch properties.
*/
public static class Watch {
/**
* The number of seconds to wait (or block) for watch query, defaults to 55. Needs
* to be less than default ConsulClient (defaults to 60). To increase ConsulClient
* timeout create a ConsulClient bean with a custom ConsulRawClient with a custom
* HttpClient.
*/
private int waitTime = 55;
/** If the watch is enabled. Defaults to true. */
private boolean enabled = true;
/** The value of the fixed delay for the watch in millis. Defaults to 1000. */
private int delay = 1000;
public Watch() {
}
public int getWaitTime() {
return this.waitTime;
}
public void setWaitTime(int waitTime) {
this.waitTime = waitTime;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public int getDelay() {
return this.delay;
}
public void setDelay(int delay) {
this.delay = delay;
}
@Override
public String toString() {
return new ToStringCreator(this).append("waitTime", this.waitTime).append("enabled", this.enabled)
.append("delay", this.delay).toString();
}
}
}

View File

@@ -1,51 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.kv.model.GetValue;
import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.PROPERTIES;
import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.YAML;
/**
* @author Spencer Gibb
*/
public class ConsulFilesPropertySource extends ConsulPropertySource {
public ConsulFilesPropertySource(String context, ConsulClient source, ConsulConfigProperties configProperties) {
super(context, source, configProperties);
}
@Override
public void init() {
// noop
}
public void init(GetValue value) {
if (this.getContext().endsWith(".yml") || this.getContext().endsWith(".yaml")) {
parseValue(value, YAML);
}
else if (this.getContext().endsWith(".properties")) {
parseValue(value, PROPERTIES);
}
else {
throw new IllegalStateException("Unknown files extension for context " + this.getContext());
}
}
}

View File

@@ -1,204 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.kv.model.GetValue;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.util.StringUtils;
import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.PROPERTIES;
import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.YAML;
import static org.springframework.util.Base64Utils.decodeFromString;
/**
* @author Spencer Gibb
*/
public class ConsulPropertySource extends EnumerablePropertySource<ConsulClient> {
private final Map<String, Object> properties = new LinkedHashMap<>();
private String context;
private ConsulConfigProperties configProperties;
private Long initialIndex;
public ConsulPropertySource(String context, ConsulClient source, ConsulConfigProperties configProperties) {
super(context, source);
this.context = context;
this.configProperties = configProperties;
}
public void init() {
if (!this.context.endsWith("/")) {
this.context = this.context + "/";
}
if (this.context.startsWith("/")) {
this.context = this.context.substring(1);
}
Response<List<GetValue>> response = this.source.getKVValues(this.context, this.configProperties.getAclToken(),
QueryParams.DEFAULT);
this.initialIndex = response.getConsulIndex();
final List<GetValue> values = response.getValue();
ConsulConfigProperties.Format format = this.configProperties.getFormat();
switch (format) {
case KEY_VALUE:
parsePropertiesInKeyValueFormat(values);
break;
case PROPERTIES:
case YAML:
parsePropertiesWithNonKeyValueFormat(values, format);
}
}
public Long getInitialIndex() {
return this.initialIndex;
}
/**
* Parses the properties in key value style i.e., values are expected to be either a
* sub key or a constant.
* @param values values to parse
*/
protected void parsePropertiesInKeyValueFormat(List<GetValue> values) {
if (values == null) {
return;
}
for (GetValue getValue : values) {
String key = getValue.getKey();
if (!StringUtils.endsWithIgnoreCase(key, "/")) {
key = key.replace(this.context, "").replace('/', '.');
String value = getValue.getDecodedValue();
this.properties.put(key, value);
}
}
}
/**
* Parses the properties using the format which is not a key value style i.e., either
* java properties style or YAML style.
* @param values values to parse
* @param format format in which the values should be parsed
*/
protected void parsePropertiesWithNonKeyValueFormat(List<GetValue> values, ConsulConfigProperties.Format format) {
if (values == null) {
return;
}
for (GetValue getValue : values) {
String key = getValue.getKey().replace(this.context, "");
if (this.configProperties.getDataKey().equals(key)) {
parseValue(getValue, format);
}
}
}
protected void parseValue(GetValue getValue, ConsulConfigProperties.Format format) {
String value = getValue.getDecodedValue();
if (value == null) {
return;
}
Properties props = generateProperties(value, format);
for (Map.Entry entry : props.entrySet()) {
this.properties.put(entry.getKey().toString(), entry.getValue());
}
}
protected Properties generateProperties(String value, ConsulConfigProperties.Format format) {
final Properties props = new Properties();
if (format == PROPERTIES) {
try {
// Must use the ISO-8859-1 encoding because Properties.load(stream)
// expects it.
props.load(new ByteArrayInputStream(value.getBytes("ISO-8859-1")));
}
catch (IOException e) {
throw new IllegalArgumentException(value + " can't be encoded using ISO-8859-1");
}
return props;
}
else if (format == YAML) {
final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ByteArrayResource(value.getBytes(Charset.forName("UTF-8"))));
return yaml.getObject();
}
return props;
}
/**
* @param value encoded value
* @return the decoded string
* @deprecated As of 1.1.0 use {@link GetValue#getDecodedValue()}.
*/
@Deprecated
public String getDecoded(String value) {
if (value == null) {
return null;
}
return new String(decodeFromString(value));
}
protected Map<String, Object> getProperties() {
return this.properties;
}
protected ConsulConfigProperties getConfigProperties() {
return this.configProperties;
}
protected String getContext() {
return this.context;
}
@Override
public Object getProperty(String name) {
return this.properties.get(name);
}
@Override
public String[] getPropertyNames() {
Set<String> strings = this.properties.keySet();
return strings.toArray(new String[strings.size()]);
}
}

View File

@@ -1,111 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import com.ecwid.consul.v1.ConsulClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.retry.annotation.Retryable;
/**
* @author Spencer Gibb
*/
@Order(0)
public class ConsulPropertySourceLocator implements PropertySourceLocator, ConsulConfigIndexes {
private static final Log log = LogFactory.getLog(ConsulPropertySourceLocator.class);
private final ConsulClient consul;
private final ConsulConfigProperties properties;
private final List<String> contexts = new ArrayList<>();
private final LinkedHashMap<String, Long> contextIndex = new LinkedHashMap<>();
public ConsulPropertySourceLocator(ConsulClient consul, ConsulConfigProperties properties) {
this.consul = consul;
this.properties = properties;
}
@Deprecated
public List<String> getContexts() {
return this.contexts;
}
@Override
public LinkedHashMap<String, Long> getIndexes() {
return this.contextIndex;
}
@Override
@Retryable(interceptor = "consulRetryInterceptor")
public Collection<PropertySource<?>> locateCollection(Environment environment) {
return PropertySourceLocator.locateCollection(this, environment);
}
@Override
@Retryable(interceptor = "consulRetryInterceptor")
public PropertySource<?> locate(Environment environment) {
if (environment instanceof ConfigurableEnvironment) {
ConfigurableEnvironment env = (ConfigurableEnvironment) environment;
ConsulPropertySources sources = new ConsulPropertySources(properties, log);
List<String> profiles = Arrays.asList(env.getActiveProfiles());
this.contexts.addAll(sources.getAutomaticContexts(profiles));
CompositePropertySource composite = new CompositePropertySource("consul");
for (String propertySourceContext : this.contexts) {
ConsulPropertySource propertySource = sources.createPropertySource(propertySourceContext, this.consul,
contextIndex::put);
if (propertySource != null) {
composite.addPropertySource(propertySource);
}
}
return composite;
}
return null;
}
private void addIndex(String propertySourceContext, Long consulIndex) {
this.contextIndex.put(propertySourceContext, consulIndex);
}
private ConsulPropertySource create(String context) {
ConsulPropertySource propertySource = new ConsulPropertySource(context, this.consul, this.properties);
propertySource.init();
addIndex(context, propertySource.getInitialIndex());
return propertySource;
}
}

View File

@@ -1,211 +0,0 @@
/*
* Copyright 2015-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.kv.model.GetValue;
import org.apache.commons.logging.Log;
import org.springframework.core.style.ToStringCreator;
import org.springframework.util.StringUtils;
import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.FILES;
public class ConsulPropertySources {
protected static final List<String> DIR_SUFFIXES = Collections.singletonList("/");
protected static final List<String> FILES_SUFFIXES = Collections
.unmodifiableList(Arrays.asList(".yml", ".yaml", ".properties"));
private final ConsulConfigProperties properties;
private final Log log;
public ConsulPropertySources(ConsulConfigProperties properties, Log log) {
this.properties = properties;
this.log = log;
}
public List<String> getAutomaticContexts(List<String> profiles) {
return getAutomaticContexts(profiles, true);
}
public List<String> getAutomaticContexts(List<String> profiles, boolean reverse) {
return generateAutomaticContexts(profiles, reverse).stream().map(Context::getPath).collect(Collectors.toList());
}
public List<Context> generateAutomaticContexts(List<String> profiles, boolean reverse) {
List<Context> contexts = new ArrayList<>();
for (String prefix : this.properties.getPrefixes()) {
String defaultContext = getContext(prefix, properties.getDefaultContext());
List<String> suffixes = getSuffixes();
for (String suffix : suffixes) {
contexts.add(new Context(defaultContext + suffix));
}
for (String suffix : suffixes) {
addProfiles(contexts, defaultContext, profiles, suffix);
}
// getName() defaults to ${spring.application.name} or application
String baseContext = getContext(prefix, properties.getName());
for (String suffix : suffixes) {
contexts.add(new Context(baseContext + suffix));
}
for (String suffix : suffixes) {
addProfiles(contexts, baseContext, profiles, suffix);
}
}
if (reverse) {
// we build them backwards, first wins, so reverse
Collections.reverse(contexts);
}
return contexts;
}
protected String getContext(String prefix, String context) {
if (!StringUtils.hasText(prefix)) {
return context;
}
else {
return prefix + "/" + context;
}
}
protected List<String> getSuffixes() {
if (properties.getFormat() == FILES) {
return FILES_SUFFIXES;
}
return DIR_SUFFIXES;
}
private void addProfiles(List<Context> contexts, String baseContext, List<String> profiles, String suffix) {
for (String profile : profiles) {
String path = baseContext + properties.getProfileSeparator() + profile + suffix;
contexts.add(new Context(path, profile));
}
}
@Deprecated
public ConsulPropertySource createPropertySource(String propertySourceContext, boolean optional,
ConsulClient consul, BiConsumer<String, Long> indexConsumer) {
return createPropertySource(propertySourceContext, consul, indexConsumer);
}
public ConsulPropertySource createPropertySource(String propertySourceContext, ConsulClient consul,
BiConsumer<String, Long> indexConsumer) {
try {
ConsulPropertySource propertySource = null;
if (properties.getFormat() == FILES) {
Response<GetValue> response = consul.getKVValue(propertySourceContext, properties.getAclToken());
indexConsumer.accept(propertySourceContext, response.getConsulIndex());
if (response.getValue() != null) {
ConsulFilesPropertySource filesPropertySource = new ConsulFilesPropertySource(propertySourceContext,
consul, properties);
filesPropertySource.init(response.getValue());
propertySource = filesPropertySource;
}
}
else {
propertySource = create(propertySourceContext, consul, indexConsumer);
}
return propertySource;
}
catch (PropertySourceNotFoundException e) {
throw e;
}
catch (Exception e) {
if (properties.isFailFast()) {
throw new PropertySourceNotFoundException(propertySourceContext, e);
}
else {
log.warn("Unable to load consul config from " + propertySourceContext, e);
}
}
return null;
}
private ConsulPropertySource create(String context, ConsulClient consulClient,
BiConsumer<String, Long> indexConsumer) {
ConsulPropertySource propertySource = new ConsulPropertySource(context, consulClient, this.properties);
propertySource.init();
indexConsumer.accept(context, propertySource.getInitialIndex());
return propertySource;
}
public static class Context {
private final String path;
private final String profile;
public Context(String path) {
this.path = path;
this.profile = null;
}
public Context(String path, String profile) {
this.path = path;
this.profile = profile;
}
public String getPath() {
return this.path;
}
public String getProfile() {
return this.profile;
}
@Override
public String toString() {
return new ToStringCreator(this).append("path", path).append("profile", profile).toString();
}
}
static class PropertySourceNotFoundException extends RuntimeException {
private final String context;
PropertySourceNotFoundException(String context) {
this.context = context;
}
PropertySourceNotFoundException(String context, Exception cause) {
super(cause);
this.context = context;
}
public String getContext() {
return this.context;
}
}
}

View File

@@ -1,69 +0,0 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import org.springframework.boot.BootstrapRegistry;
import org.springframework.boot.BootstrapRegistryInitializer;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.cloud.consul.RetryProperties;
import org.springframework.cloud.consul.config.ConsulBootstrapper.LoaderInterceptor;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.util.ClassUtils;
/**
* Consul Retry Bootstrapper.
*
* @author Spencer Gibb
* @since 3.0.2
*/
public class ConsulRetryBootstrapper implements BootstrapRegistryInitializer {
static final boolean RETRY_IS_PRESENT = ClassUtils.isPresent("org.springframework.retry.annotation.Retryable",
null);
@Override
public void initialize(BootstrapRegistry registry) {
if (!RETRY_IS_PRESENT) {
return;
}
registry.registerIfAbsent(RetryProperties.class, context -> context.get(Binder.class)
.bind(RetryProperties.PREFIX, RetryProperties.class).orElseGet(RetryProperties::new));
registry.registerIfAbsent(RetryTemplate.class, context -> {
RetryProperties properties = context.get(RetryProperties.class);
if (properties.isEnabled()) {
return RetryTemplate.builder().maxAttempts(properties.getMaxAttempts())
.exponentialBackoff(properties.getInitialInterval(), properties.getMultiplier(),
properties.getMaxInterval())
.build();
}
return null;
});
registry.registerIfAbsent(LoaderInterceptor.class, context -> {
RetryTemplate retryTemplate = context.get(RetryTemplate.class);
if (retryTemplate != null) {
return loadContext -> retryTemplate.execute(retryContext -> loadContext.getInvocation()
.apply(loadContext.getLoaderContext(), loadContext.getResource()));
}
// disabled
return null;
});
}
}

View File

@@ -1,44 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.LinkedHashMap;
import org.springframework.context.ApplicationEvent;
/**
* @author Spencer Gibb
*/
public class PropertySourcesLocatedEvent extends ApplicationEvent {
private final LinkedHashMap<String, Long> contextsToIndexes;
/**
* Create a new ApplicationEvent.
* @param source the object on which the event initially occurred (never {@code null})
* @param contextsToIndexes contexts to indexes
*/
public PropertySourcesLocatedEvent(Object source, LinkedHashMap<String, Long> contextsToIndexes) {
super(source);
this.contextsToIndexes = contextsToIndexes;
}
public LinkedHashMap<String, Long> getContextsToIndexes() {
return this.contextsToIndexes;
}
}

View File

@@ -1,22 +0,0 @@
# Bootstrap Configuration
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
org.springframework.cloud.consul.config.ConsulConfigBootstrapConfiguration
# Environment PostProcessor
org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.cloud.consul.config.ConsulConfigDataMissingEnvironmentPostProcessor
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.cloud.consul.config.ConsulConfigDataMissingEnvironmentPostProcessor.ImportExceptionFailureAnalyzer
# ConfigData Location Resolvers
org.springframework.boot.context.config.ConfigDataLocationResolver=\
org.springframework.cloud.consul.config.ConsulConfigDataLocationResolver
# ConfigData Loaders
org.springframework.boot.context.config.ConfigDataLoader=\
org.springframework.cloud.consul.config.ConsulConfigDataLoader
# Spring Boot Bootstrappers
org.springframework.boot.BootstrapRegistryInitializer=\
org.springframework.cloud.consul.config.ConsulRetryBootstrapper

View File

@@ -1 +0,0 @@
org.springframework.cloud.consul.config.ConsulConfigAutoConfiguration

View File

@@ -1,145 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.kv.model.GetValue;
import org.junit.Before;
import org.junit.Test;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.util.StringUtils;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.FILES;
/**
* @author Spencer Gibb
*/
public class ConfigWatchTests {
private ConsulConfigProperties configProperties;
@Before
public void setUp() throws Exception {
this.configProperties = new ConsulConfigProperties();
}
@Test
public void watchPublishesEventWithAcl() {
ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
setupWatch(eventPublisher, new GetValue(), "/app/", "2ee647bd-bd69-4118-9f34-b9a6e9e60746");
verify(eventPublisher, atLeastOnce()).publishEvent(any(RefreshEvent.class));
}
@Test
public void watchPublishesEvent() {
ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
setupWatch(eventPublisher, new GetValue(), "/app/");
verify(eventPublisher, times(1)).publishEvent(any(RefreshEvent.class));
}
@Test
public void watchWithNullValueDoesNotPublishEvent() {
ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
setupWatch(eventPublisher, null, "/app/");
verify(eventPublisher, never()).publishEvent(any(RefreshEvent.class));
}
@Test
public void watchForFileFormatPublishesEvent() {
ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
this.configProperties.setFormat(FILES);
setupWatch(eventPublisher, new GetValue(), "/config/app.yml");
verify(eventPublisher, atLeastOnce()).publishEvent(any(RefreshEvent.class));
}
private void setupWatch(ApplicationEventPublisher eventPublisher, GetValue getValue, String context) {
setupWatch(eventPublisher, getValue, context, null);
}
private void setupWatch(ApplicationEventPublisher eventPublisher, GetValue getValue, String context,
String aclToken) {
ConsulClient consul = mock(ConsulClient.class);
List<GetValue> getValues = null;
if (getValue != null) {
getValues = Arrays.asList(getValue);
}
Response<List<GetValue>> response = new Response<>(getValues, 1L, false, 1L);
when(consul.getKVValues(eq(context), nullable(String.class), any(QueryParams.class))).thenReturn(response);
if (StringUtils.hasText(aclToken)) {
this.configProperties.setAclToken(aclToken);
}
LinkedHashMap<String, Long> initialIndexes = new LinkedHashMap<>();
initialIndexes.put(context, 0L);
ConfigWatch watch = new ConfigWatch(this.configProperties, consul, initialIndexes);
watch.setApplicationEventPublisher(eventPublisher);
watch.start();
watch.watchConfigKeyValues();
}
@Test
public void firstCallDoesNotPublishEvent() {
ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
this.configProperties.setFormat(FILES);
GetValue getValue = new GetValue();
String context = "/config/app.yml";
ConsulClient consul = mock(ConsulClient.class);
List<GetValue> getValues = Collections.singletonList(getValue);
Response<List<GetValue>> response = new Response<>(getValues, 1L, false, 1L);
when(consul.getKVValues(eq(context), anyString(), any(QueryParams.class))).thenReturn(response);
ConfigWatch watch = new ConfigWatch(this.configProperties, consul, new LinkedHashMap<String, Long>());
watch.setApplicationEventPublisher(eventPublisher);
watch.watchConfigKeyValues();
verify(eventPublisher, times(0)).publishEvent(any(RefreshEvent.class));
}
}

View File

@@ -1,78 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.Collections;
import org.junit.Test;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.cloud.consul.test.ConsulTestcontainers;
import org.springframework.context.annotation.Bean;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Edvin Eriksson
*/
public class ConsulConfigBootstrapConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
/**
* Tests that the auto-config bean backs off if a user provided their own.
*/
@Test
public void testConfigPropsBeanBacksOff() {
this.contextRunner.withUserConfiguration(TestConfig.class).withInitializer(new ConsulTestcontainers())
.withUserConfiguration(ConsulConfigBootstrapConfiguration.class).run(context -> {
ConsulConfigProperties config = context.getBean(ConsulConfigProperties.class);
assertThat(config.getPrefixes().get(0)).as("Prefix did not match").isEqualTo("platform-config");
assertThat(config.getDefaultContext()).as("Default context did not match").isEqualTo("defaults");
});
}
/**
* Tests that the auto-config bean kicks in if the user did not provide any custom
* bean.
*/
@Test
public void testConfigPropsBeanKicksIn() {
this.contextRunner.withUserConfiguration(ConsulConfigBootstrapConfiguration.class)
.withInitializer(new ConsulTestcontainers()).run(context -> {
ConsulConfigProperties config = context.getBean(ConsulConfigProperties.class);
assertThat(config.getPrefixes().get(0)).as("Prefix did not match").isEqualTo("config");
assertThat(config.getDefaultContext()).as("Default context did not match").isEqualTo("application");
});
}
/**
* Test config that simulates a "user provided bean".
*/
private static class TestConfig {
@Bean
public ConsulConfigProperties consulConfigProperties() {
ConsulConfigProperties config = new ConsulConfigProperties();
config.setPrefixes(Collections.singletonList("platform-config"));
config.setDefaultContext("defaults");
return config;
}
}
}

View File

@@ -1,141 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.UUID;
import com.ecwid.consul.v1.ConsulClient;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.BootstrapRegistry;
import org.springframework.boot.BootstrapRegistryInitializer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.config.ConfigData;
import org.springframework.boot.context.properties.bind.BindContext;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.cloud.consul.ConsulProperties;
import org.springframework.cloud.consul.test.ConsulTestcontainers;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.PropertySource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Spencer Gibb
*/
@DirtiesContext
public class ConsulConfigDataCustomizationIntegrationTests {
private static final String APP_NAME = "testConsulConfigDataCustomization";
private static final String PREFIX = "_configDataIntegrationTests_config__";
private static final String ROOT = PREFIX + UUID.randomUUID();
private static ConfigurableApplicationContext context;
private static BindHandlerBootstrapper bindHandlerBootstrapper;
@BeforeAll
public static void setup() {
ConsulTestcontainers.start();
SpringApplication application = new SpringApplication(Config.class);
application.setWebApplicationType(WebApplicationType.NONE);
bindHandlerBootstrapper = new BindHandlerBootstrapper();
application.addBootstrapRegistryInitializer(bindHandlerBootstrapper);
application.addBootstrapRegistryInitializer(ConsulBootstrapper.fromConsulProperties(TestConsulClient::new));
application.addBootstrapRegistryInitializer(
registry -> registry.register(ConsulBootstrapper.LoaderInterceptor.class, context1 -> loadContext -> {
ConfigData configData = loadContext.getInvocation().apply(loadContext.getLoaderContext(),
loadContext.getResource());
assertThat(configData).as("ConfigData was null for location %s", loadContext.getResource())
.isNotNull();
assertThat(configData.getPropertySources()).hasSize(1);
PropertySource<?> propertySource = configData.getPropertySources().iterator().next();
ConfigData.Options options = configData.getOptions(propertySource);
assertThat(options).as("ConfigData.options was null for location %s property source %s",
loadContext.getResource(), propertySource.getName()).isNotNull();
assertThat(options.contains(ConfigData.Option.IGNORE_IMPORTS)).isTrue();
assertThat(options.contains(ConfigData.Option.IGNORE_PROFILES)).isTrue();
boolean hasProfile = StringUtils.hasText(loadContext.getResource().getProfile());
assertThat(options.contains(ConfigData.Option.PROFILE_SPECIFIC)).isEqualTo(hasProfile);
return configData;
}));
context = application.run("--spring.application.name=" + APP_NAME,
"--spring.config.import=consul:" + ConsulTestcontainers.getHost() + ":"
+ ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefixes=" + ROOT, "--spring.cloud.consul.config.watch.delay=10");
}
@AfterAll
public static void teardown() {
if (context != null) {
context.close();
}
}
@Test
public void consulClientIsCustom() {
ConsulClient client = context.getBean(ConsulClient.class);
assertThat(client).isInstanceOf(TestConsulClient.class);
assertThat(bindHandlerBootstrapper.onSuccessCount).isGreaterThan(0);
}
static class TestConsulClient extends ConsulClient {
TestConsulClient(ConsulProperties properties) {
super(properties.getHost(), properties.getPort());
}
}
@Configuration
@EnableAutoConfiguration
static class Config {
}
static class BindHandlerBootstrapper implements BootstrapRegistryInitializer {
private int onSuccessCount = 0;
@Override
public void initialize(BootstrapRegistry registry) {
registry.register(BindHandler.class, context -> new BindHandler() {
@Override
public Object onSuccess(ConfigurationPropertyName name, Bindable<?> target, BindContext context,
Object result) {
onSuccessCount++;
return result;
}
});
}
}
}

View File

@@ -1,169 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.ecwid.consul.v1.ConsulClient;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.consul.test.ConsulTestcontainers;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.test.annotation.DirtiesContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Spencer Gibb
*/
@DirtiesContext
public class ConsulConfigDataFileIntegrationTests {
private static final String APP_NAME = "testConsulConfigDataFile";
private static final String PREFIX = "_configDataIntegrationFileTests_config__";
private static final String ROOT = PREFIX + UUID.randomUUID();
private static final String VALUE1 = "testPropVal";
private static final String TEST_PROP = "testProp";
private static final String TEST_PROP_CANONICAL = "test-prop";
private static final String KEY1 = ROOT + "/application.properties";
private static final String VALUE2 = "testPropVal2";
private static final String TEST_PROP2 = "testProp2";
private static final String TEST_PROP2_CANONICAL = "test-prop2";
private static final String TEST_PROP3 = "testProp3";
private static final String TEST_PROP3_CANONICAL = "test-prop3";
private static final String KEY3 = ROOT + "/" + APP_NAME + ".properties";
private static ConfigurableApplicationContext context;
private static ConfigurableEnvironment environment;
private static ConsulClient client;
@BeforeAll
public static void setup() {
ConsulTestcontainers.start();
client = ConsulTestcontainers.client();
client.deleteKVValues(PREFIX);
client.setKVValue(KEY1, TEST_PROP + "=" + VALUE1 + "\n" + TEST_PROP2 + "=" + VALUE2);
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--spring.application.name=" + APP_NAME, "--spring.cloud.consul.config.format=files",
"--spring.config.import=optional:consul:" + ConsulTestcontainers.getHost() + ":"
+ ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.watch.delay=10");
client = context.getBean(ConsulClient.class);
environment = context.getEnvironment();
}
@AfterAll
public static void teardown() {
client.deleteKVValues(PREFIX);
if (context != null) {
context.close();
}
}
@Test
public void propertyLoaded() {
String testProp = environment.getProperty(TEST_PROP_CANONICAL);
assertThat(testProp).as(TEST_PROP + " was wrong").isEqualTo(VALUE1);
String testProp2 = environment.getProperty(TEST_PROP2_CANONICAL);
assertThat(testProp2).as(TEST_PROP2 + " was wrong").isEqualTo(VALUE2);
}
@Test
public void propertyLoadedAndUpdated() throws Exception {
String testProp = environment.getProperty(TEST_PROP_CANONICAL);
assertThat(testProp).as("testProp was wrong").isEqualTo(VALUE1);
client.setKVValue(KEY1, TEST_PROP + "=testPropValUpdate\n" + TEST_PROP2 + "=" + VALUE2);
CountDownLatch latch = context.getBean("countDownLatch1", CountDownLatch.class);
boolean receivedEvent = latch.await(15, TimeUnit.SECONDS);
assertThat(receivedEvent).as("listener didn't receive event").isTrue();
testProp = environment.getProperty(TEST_PROP_CANONICAL);
assertThat(testProp).as("testProp was wrong after update").isEqualTo("testPropValUpdate");
}
@Test
public void contextDoesNotExistThenExists() throws Exception {
String testProp = environment.getProperty(TEST_PROP3_CANONICAL);
assertThat(testProp).as(TEST_PROP3 + " was wrong").isNull();
client.setKVValue(KEY3, TEST_PROP3 + "=testPropValInsert");
CountDownLatch latch = context.getBean("countDownLatch2", CountDownLatch.class);
boolean receivedEvent = latch.await(15, TimeUnit.SECONDS);
assertThat(receivedEvent).as("listener didn't receive event").isTrue();
testProp = environment.getProperty(TEST_PROP3_CANONICAL);
assertThat(testProp).as(TEST_PROP3 + " was wrong after update").isEqualTo("testPropValInsert");
}
@Configuration
@EnableAutoConfiguration
static class Config implements ApplicationListener<EnvironmentChangeEvent> {
@Bean
public CountDownLatch countDownLatch1() {
return new CountDownLatch(1);
}
@Bean
public CountDownLatch countDownLatch2() {
return new CountDownLatch(1);
}
@Override
public void onApplicationEvent(EnvironmentChangeEvent event) {
if (event.getKeys().contains(TEST_PROP)) {
countDownLatch1().countDown();
}
else if (event.getKeys().contains(TEST_PROP3)) {
countDownLatch2().countDown();
}
}
}
}

View File

@@ -1,177 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.ecwid.consul.v1.ConsulClient;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.consul.test.ConsulTestcontainers;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.test.annotation.DirtiesContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Spencer Gibb
*/
@DirtiesContext
public class ConsulConfigDataIntegrationTests {
private static final String APP_NAME = "testConsulConfigData";
private static final String PREFIX = "_configDataIntegrationTests_config__";
private static final String ROOT = PREFIX + UUID.randomUUID();
private static final String VALUE1 = "testPropVal";
private static final String TEST_PROP = "testProp";
private static final String TEST_PROP_CANONICAL = "test-prop";
private static final String KEY1 = ROOT + "/application/" + TEST_PROP;
private static final String VALUE2 = "testPropVal2";
private static final String VALUE2_DEFAULT = "testPropVal2Default";
private static final String TEST_PROP2 = "testProp2";
private static final String TEST_PROP2_CANONICAL = "test-prop2";
private static final String KEY2 = ROOT + "/application/" + TEST_PROP2;
private static final String KEY2_APP_NAME = ROOT + "/" + APP_NAME + "/" + TEST_PROP2;
private static final String TEST_PROP3 = "testProp3";
private static final String TEST_PROP3_CANONICAL = "test-prop3";
private static final String KEY3 = ROOT + "/" + APP_NAME + "/" + TEST_PROP3;
private static ConfigurableApplicationContext context;
private static ConfigurableEnvironment environment;
private static ConsulClient client;
@BeforeAll
public static void setup() {
ConsulTestcontainers.start();
client = ConsulTestcontainers.client();
client.deleteKVValues(PREFIX);
client.setKVValue(KEY1, VALUE1);
client.setKVValue(KEY2, VALUE2_DEFAULT);
client.setKVValue(KEY2_APP_NAME, VALUE2);
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--logging.level.org.springframework.cloud.consul.config.ConfigWatch=TRACE",
"--spring.application.name=" + APP_NAME,
"--spring.config.import=consul:" + ConsulTestcontainers.getHost() + ":"
+ ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.watch.delay=10",
"--spring.cloud.consul.config.watch.wait-time=1");
client = context.getBean(ConsulClient.class);
environment = context.getEnvironment();
}
@AfterAll
public static void teardown() {
client.deleteKVValues(PREFIX);
if (context != null) {
context.close();
}
}
@Test
public void propertyLoaded() {
String testProp2 = environment.getProperty(TEST_PROP2_CANONICAL);
assertThat(testProp2).as(TEST_PROP2 + " was wrong").isEqualTo(VALUE2);
}
@Test
public void propertyLoadedAndUpdated() throws Exception {
String testProp = environment.getProperty(TEST_PROP_CANONICAL);
assertThat(testProp).as("testProp was wrong").isEqualTo(VALUE1);
client.setKVValue(KEY1, "testPropValUpdate");
CountDownLatch latch = context.getBean("countDownLatch1", CountDownLatch.class);
boolean receivedEvent = latch.await(15, TimeUnit.SECONDS);
assertThat(receivedEvent).as("listener didn't receive event").isTrue();
testProp = environment.getProperty(TEST_PROP_CANONICAL);
assertThat(testProp).as("testProp was wrong after update").isEqualTo("testPropValUpdate");
}
@Test
public void contextDoesNotExistThenExists() throws Exception {
String testProp = environment.getProperty(TEST_PROP3_CANONICAL);
assertThat(testProp).as("testProp was wrong").isNull();
client.setKVValue(KEY3, "testPropValInsert");
CountDownLatch latch = context.getBean("countDownLatch2", CountDownLatch.class);
boolean receivedEvent = latch.await(15, TimeUnit.SECONDS);
assertThat(receivedEvent).as("listener didn't receive event").isTrue();
testProp = environment.getProperty(TEST_PROP3_CANONICAL);
assertThat(testProp).as(TEST_PROP3 + " was wrong after update").isEqualTo("testPropValInsert");
}
@Configuration
@EnableAutoConfiguration
static class Config implements ApplicationListener<EnvironmentChangeEvent> {
@Bean
public CountDownLatch countDownLatch1() {
return new CountDownLatch(1);
}
@Bean
public CountDownLatch countDownLatch2() {
return new CountDownLatch(1);
}
@Override
public void onApplicationEvent(EnvironmentChangeEvent event) {
if (event.getKeys().contains(TEST_PROP)) {
countDownLatch1().countDown();
}
else if (event.getKeys().contains(TEST_PROP3)) {
countDownLatch2().countDown();
}
}
}
}

View File

@@ -1,148 +0,0 @@
/*
* Copyright 2015-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.boot.BootstrapRegistry.InstanceSupplier;
import org.springframework.boot.DefaultBootstrapContext;
import org.springframework.boot.context.config.ConfigDataLocation;
import org.springframework.boot.context.config.ConfigDataLocationResolverContext;
import org.springframework.boot.context.config.Profiles;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.cloud.consul.ConsulProperties;
import org.springframework.core.env.SystemEnvironmentPropertySource;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ConsulConfigDataLocationResolverTests {
@Test
public void testParseLocation() {
ConsulConfigDataLocationResolver resolver = new ConsulConfigDataLocationResolver(
destination -> LogFactory.getLog(ConsulConfigDataLocationResolver.class));
UriComponents uriComponents = resolver.parseLocation(null,
ConfigDataLocation.of("consul:myhost:8501/mypath1;/mypath2;/mypath3"));
assertThat(uriComponents.toUri()).hasScheme("consul").hasHost("myhost").hasPort(8501)
.hasPath("/mypath1;/mypath2;/mypath3");
uriComponents = resolver.parseLocation(null, ConfigDataLocation.of("consul:myhost:8501"));
assertThat(uriComponents.toUri()).hasScheme("consul").hasHost("myhost").hasPort(8501).hasPath("");
}
@Test
public void testResolveProfileSpecificWithCustomPaths() {
String location = "consul:myhost:8501/mypath1;/mypath2;/mypath3";
List<ConsulConfigDataResource> locations = testResolveProfileSpecific(location);
assertThat(locations).hasSize(3);
assertThat(toContexts(locations)).containsExactly("/mypath1/", "/mypath2/", "/mypath3/");
}
@Test
public void testResolveProfileSpecificWithAutomaticPaths() {
String location = "consul:myhost";
List<ConsulConfigDataResource> locations = testResolveProfileSpecific(location);
assertThat(locations).hasSize(4);
assertThat(toContexts(locations)).containsExactly("config/application/", "config/application,dev/",
"config/testapp/", "config/testapp,dev/");
}
@Test
public void testLoadProperties() {
Binder binder = Binder.get(new MockEnvironment());
ConfigDataLocationResolverContext resolverContext = mock(ConfigDataLocationResolverContext.class);
when(resolverContext.getBinder()).thenReturn(binder);
when(resolverContext.getBootstrapContext()).thenReturn(new DefaultBootstrapContext());
ConsulProperties properties = createResolver().loadProperties(resolverContext,
UriComponentsBuilder.fromUriString("consul://myhost:8502").build());
assertThat(properties.getHost()).isEqualTo("myhost");
assertThat(properties.getPort()).isEqualTo(8502);
}
@ParameterizedTest
@ValueSource(strings = { "consul.token", "CONSUL_TOKEN", "spring.cloud.consul.token", "SPRING_CLOUD_CONSUL_TOKEN",
"spring.cloud.consul.config.acl-token" })
public void testLoadConfigProperties(String property) {
MockEnvironment mockEnvironment = new MockEnvironment();
String tokenValue = "mytoken";
if (property.contains("_")) {
SystemEnvironmentPropertySource envPS = new SystemEnvironmentPropertySource("mocksysenv",
Collections.singletonMap(property, tokenValue));
mockEnvironment.getPropertySources().addLast(envPS);
}
else {
mockEnvironment.setProperty(property, tokenValue);
}
Binder binder = Binder.get(mockEnvironment);
ConfigDataLocationResolverContext resolverContext = mock(ConfigDataLocationResolverContext.class);
when(resolverContext.getBinder()).thenReturn(binder);
when(resolverContext.getBootstrapContext()).thenReturn(new DefaultBootstrapContext());
ConsulConfigProperties properties = createResolver().loadConfigProperties(resolverContext);
assertThat(properties.getAclToken()).isEqualTo(tokenValue);
}
private List<String> toContexts(List<ConsulConfigDataResource> locations) {
return locations.stream().map(ConsulConfigDataResource::getContext).collect(Collectors.toList());
}
private List<ConsulConfigDataResource> testResolveProfileSpecific(String location) {
ConsulConfigDataLocationResolver resolver = createResolver();
ConfigDataLocationResolverContext context = mock(ConfigDataLocationResolverContext.class);
when(context.getBootstrapContext()).thenReturn(new DefaultBootstrapContext());
MockEnvironment env = new MockEnvironment();
env.setProperty("spring.application.name", "testapp");
when(context.getBinder()).thenReturn(Binder.get(env));
Profiles profiles = mock(Profiles.class);
when(profiles.getAccepted()).thenReturn(Collections.singletonList("dev"));
return resolver.resolveProfileSpecific(context, ConfigDataLocation.of(location), profiles);
}
private ConsulConfigDataLocationResolver createResolver() {
return new ConsulConfigDataLocationResolver(
destination -> LogFactory.getLog(ConsulConfigDataLocationResolver.class)) {
@Override
public <T> void registerBean(ConfigDataLocationResolverContext context, Class<T> type, T instance) {
// do nothing
}
@Override
protected <T> void registerBean(ConfigDataLocationResolverContext context, Class<T> type,
InstanceSupplier<T> supplier) {
// do nothing
}
@Override
protected <T> void registerAndPromoteBean(ConfigDataLocationResolverContext context, Class<T> type,
InstanceSupplier<T> supplier) {
// do nothing
}
};
}
}

View File

@@ -1,106 +0,0 @@
/*
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import org.junit.jupiter.api.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.mock.env.MockEnvironment;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
/**
* @author Ryan Baxter
*/
class ConsulConfigDataMissingEnvironmentPostProcessorTests {
@Test
void noSpringConfigImport() {
MockEnvironment environment = new MockEnvironment();
SpringApplication app = mock(SpringApplication.class);
ConsulConfigDataMissingEnvironmentPostProcessor processor = new ConsulConfigDataMissingEnvironmentPostProcessor();
assertThatThrownBy(() -> processor.postProcessEnvironment(environment, app))
.isInstanceOf(ConsulConfigDataMissingEnvironmentPostProcessor.ImportException.class);
}
@Test
void boostrap() {
MockEnvironment environment = new MockEnvironment();
environment.setProperty("spring.cloud.bootstrap.enabled", "true");
SpringApplication app = mock(SpringApplication.class);
ConsulConfigDataMissingEnvironmentPostProcessor processor = new ConsulConfigDataMissingEnvironmentPostProcessor();
assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException();
}
@Test
void legacy() {
MockEnvironment environment = new MockEnvironment();
environment.setProperty("spring.config.use-legacy-processing", "true");
SpringApplication app = mock(SpringApplication.class);
ConsulConfigDataMissingEnvironmentPostProcessor processor = new ConsulConfigDataMissingEnvironmentPostProcessor();
assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException();
}
@Test
void configNotEnabled() {
MockEnvironment environment = new MockEnvironment();
environment.setProperty("spring.cloud.consul.enabled", "false");
SpringApplication app = mock(SpringApplication.class);
ConsulConfigDataMissingEnvironmentPostProcessor processor = new ConsulConfigDataMissingEnvironmentPostProcessor();
assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException();
}
@Test
void importCheckNotEnabled() {
MockEnvironment environment = new MockEnvironment();
environment.setProperty("spring.cloud.consul.config.import-check.enabled", "false");
SpringApplication app = mock(SpringApplication.class);
ConsulConfigDataMissingEnvironmentPostProcessor processor = new ConsulConfigDataMissingEnvironmentPostProcessor();
assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException();
}
@Test
void importSinglePropertySource() {
MockEnvironment environment = new MockEnvironment();
environment.setProperty("spring.config.import", "consul:http://localhost:8888");
SpringApplication app = mock(SpringApplication.class);
ConsulConfigDataMissingEnvironmentPostProcessor processor = new ConsulConfigDataMissingEnvironmentPostProcessor();
assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException();
}
@Test
void importMultiplePropertySource() {
MockEnvironment environment = new MockEnvironment();
environment.setProperty("spring.config.import", "consul:http://localhost:8888,file:./app.properties");
SpringApplication app = mock(SpringApplication.class);
ConsulConfigDataMissingEnvironmentPostProcessor processor = new ConsulConfigDataMissingEnvironmentPostProcessor();
assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException();
}
@Test
void importMultiplePropertySourceAsList() {
MockEnvironment environment = new MockEnvironment();
environment.setProperty("spring.config.import[0]", "consul:http://localhost:8888");
environment.setProperty("spring.config.import[1]", "file:./app.properties");
SpringApplication app = mock(SpringApplication.class);
ConsulConfigDataMissingEnvironmentPostProcessor processor = new ConsulConfigDataMissingEnvironmentPostProcessor();
assertThatCode(() -> processor.postProcessEnvironment(environment, app)).doesNotThrowAnyException();
}
}

View File

@@ -1,119 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import java.util.UUID;
import com.ecwid.consul.v1.ConsulClient;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.consul.test.ConsulTestcontainers;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.test.annotation.DirtiesContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Spencer Gibb
*/
@DirtiesContext
public class ConsulConfigDataMultiplePrefixesIntegrationTests {
private static final String APP_NAME = "testConsulConfigData";
private static final String PREFIX = "_configDataMultiplePrefixesIntegrationTests_config__";
private static final String PREFIX2 = "_configDataMultiplePrefixesIntegrationTests_config2__";
private static final String ROOT = PREFIX + UUID.randomUUID();
private static final String ROOT2 = PREFIX2 + UUID.randomUUID();
private static final String VALUE1 = "testPropVal";
private static final String TEST_PROP = "testProp";
private static final String TEST_PROP_CANONICAL = "test-prop";
private static final String KEY1 = ROOT + "/application/" + TEST_PROP;
private static final String VALUE2 = "testPropVal2";
private static final String TEST_PROP2 = "testProp2";
private static final String TEST_PROP2_CANONICAL = "test-prop2";
private static final String KEY2 = ROOT2 + "/application/" + TEST_PROP2;
private static ConfigurableApplicationContext context;
private static ConfigurableEnvironment environment;
private static ConsulClient client;
@BeforeAll
public static void setup() {
ConsulTestcontainers.start();
client = ConsulTestcontainers.client();
client.deleteKVValues(PREFIX);
client.deleteKVValues(PREFIX2);
client.setKVValue(KEY1, VALUE1);
client.setKVValue(KEY2, VALUE2);
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--logging.level.org.springframework.cloud.consul.config.ConfigWatch=TRACE",
"--spring.application.name=" + APP_NAME,
"--spring.config.import=consul:" + ConsulTestcontainers.getHost() + ":"
+ ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefixes=" + ROOT + "," + ROOT2,
"--spring.cloud.consul.config.watch.delay=10", "--spring.cloud.consul.config.watch.wait-time=1");
client = context.getBean(ConsulClient.class);
environment = context.getEnvironment();
}
@AfterAll
public static void teardown() {
client.deleteKVValues(PREFIX);
client.deleteKVValues(PREFIX2);
if (context != null) {
context.close();
}
}
@Test
public void propertyLoaded() {
String testProp = environment.getProperty(TEST_PROP_CANONICAL);
assertThat(testProp).as(TEST_PROP + " was wrong").isEqualTo(VALUE1);
String testProp2 = environment.getProperty(TEST_PROP2_CANONICAL);
assertThat(testProp2).as(TEST_PROP2 + " was wrong").isEqualTo(VALUE2);
}
@Configuration
@EnableAutoConfiguration
static class Config {
}
}

View File

@@ -1,119 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.config;
import com.ecwid.consul.v1.ConsulClient;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.cloud.commons.ConfigDataMissingEnvironmentPostProcessor;
import org.springframework.cloud.consul.test.ConsulTestcontainers;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.cloud.consul.config.ConsulConfigDataLocationResolver.PREFIX;
/**
* @author Spencer Gibb
*/
@ExtendWith(OutputCaptureExtension.class)
public class ConsulConfigDataNoImportIntegrationTests {
private static final String APP_NAME = "testConsulConfigDataNoImport";
private static final String KV_PREFIX = "_configDataNoImportIntegrationTests_config__";
private static ConsulClient client;
@BeforeAll
public static void setup() {
ConsulTestcontainers.start();
client = ConsulTestcontainers.client();
client.deleteKVValues(KV_PREFIX);
}
@AfterAll
public static void teardown() {
client.deleteKVValues(KV_PREFIX);
}
@Test
public void exceptionThrownIfNoImport(CapturedOutput output) {
Assertions
.assertThatThrownBy(() -> new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--spring.application.name=" + APP_NAME))
.isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class);
assertThat(output).contains("No spring.config.import property has been defined")
.contains("Add a spring.config.import=consul: property to your configuration");
}
@Test
public void exceptionThrownIfImportMissingConsul(CapturedOutput output) {
Assertions
.assertThatThrownBy(() -> new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--spring.config.import=optional:file:somefile.properties",
"--spring.application.name=" + APP_NAME))
.isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class);
assertThat(output).contains("spring.config.import property is missing a " + PREFIX)
.contains("Add a spring.config.import=consul: property to your configuration");
}
@Test
public void noExceptionThrownIfConsulDisabled() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Config.class)
.web(WebApplicationType.NONE)
.run("--spring.cloud.consul.enabled=false", "--spring.application.name=" + APP_NAME)) {
// nothing to do
}
}
@Test
public void noExceptionThrownIfConsulConfigDisabled() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Config.class)
.web(WebApplicationType.NONE)
.run("--spring.cloud.consul.config.enabled=false", "--spring.application.name=" + APP_NAME)) {
// nothing to do
}
}
@Test
public void noExceptionThrownIfImportCheckDisabled() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Config.class)
.web(WebApplicationType.NONE).run("--spring.cloud.consul.config.import-check.enabled=false",
"--spring.application.name=" + APP_NAME)) {
// nothing to do
}
}
@Configuration
@EnableAutoConfiguration
static class Config {
}
}

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