diff --git a/spring-cloud-netflix/2.0.0.M7/css/highlight.css b/spring-cloud-netflix/2.0.0.M7/css/highlight.css new file mode 100644 index 00000000..ffefef72 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/css/highlight.css @@ -0,0 +1,35 @@ +/* + code highlight CSS resemblign the Eclipse IDE default color schema + @author Costin Leau +*/ + +.hl-keyword { + color: #7F0055; + font-weight: bold; +} + +.hl-comment { + color: #3F5F5F; + font-style: italic; +} + +.hl-multiline-comment { + color: #3F5FBF; + font-style: italic; +} + +.hl-tag { + color: #3F7F7F; +} + +.hl-attribute { + color: #7F007F; +} + +.hl-value { + color: #2A00FF; +} + +.hl-string { + color: #2A00FF; +} \ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/css/manual-multipage.css b/spring-cloud-netflix/2.0.0.M7/css/manual-multipage.css new file mode 100644 index 00000000..0c484531 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/css/manual-multipage.css @@ -0,0 +1,9 @@ +@IMPORT url("manual.css"); + +body.firstpage { + background: url("../images/background.png") no-repeat center top; +} + +div.part h1 { + border-top: none; +} diff --git a/spring-cloud-netflix/2.0.0.M7/css/manual-singlepage.css b/spring-cloud-netflix/2.0.0.M7/css/manual-singlepage.css new file mode 100644 index 00000000..4a7fd140 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/css/manual-singlepage.css @@ -0,0 +1,6 @@ +@IMPORT url("manual.css"); + +body { + background: url("../images/background.png") no-repeat center top; +} + diff --git a/spring-cloud-netflix/2.0.0.M7/css/manual.css b/spring-cloud-netflix/2.0.0.M7/css/manual.css new file mode 100644 index 00000000..0ecbe2e8 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/css/manual.css @@ -0,0 +1,344 @@ +@IMPORT url("highlight.css"); + +html { + padding: 0pt; + margin: 0pt; +} + +body { + color: #333333; + margin: 15px 30px; + font-family: Helvetica, Arial, Freesans, Clean, Sans-serif; + line-height: 1.6; + -webkit-font-smoothing: antialiased; +} + +code { + font-size: 16px; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +:not(a)>code { + color: #6D180B; +} + +:not(pre)>code { + background-color: #F2F2F2; + border: 1px solid #CCCCCC; + border-radius: 4px; + padding: 1px 3px 0; + text-shadow: none; + white-space: nowrap; +} + +body>*:first-child { + margin-top: 0 !important; +} + +div { + margin: 0pt; +} + +hr { + border: 1px solid #CCCCCC; + background: #CCCCCC; +} + +h1,h2,h3,h4,h5,h6 { + color: #000000; + cursor: text; + font-weight: bold; + margin: 30px 0 10px; + padding: 0; +} + +h1,h2,h3 { + margin: 40px 0 10px; +} + +h1 { + margin: 70px 0 30px; + padding-top: 20px; +} + +div.part h1 { + border-top: 1px dotted #CCCCCC; +} + +h1,h1 code { + font-size: 32px; +} + +h2,h2 code { + font-size: 24px; +} + +h3,h3 code { + font-size: 20px; +} + +h4,h1 code,h5,h5 code,h6,h6 code { + font-size: 18px; +} + +div.book,div.chapter,div.appendix,div.part,div.preface { + min-width: 300px; + max-width: 1200px; + margin: 0 auto; +} + +p.releaseinfo { + font-weight: bold; + margin-bottom: 40px; + margin-top: 40px; +} + +div.authorgroup { + line-height: 1; +} + +p.copyright { + line-height: 1; + margin-bottom: -5px; +} + +.legalnotice p { + font-style: italic; + font-size: 14px; + line-height: 1; +} + +div.titlepage+p,div.titlepage+p { + margin-top: 0; +} + +pre { + line-height: 1.0; + color: black; +} + +a { + color: #4183C4; + text-decoration: none; +} + +p { + margin: 15px 0; + text-align: left; +} + +ul,ol { + padding-left: 30px; +} + +li p { + margin: 0; +} + +div.table { + margin: 1em; + padding: 0.5em; + text-align: center; +} + +div.table table,div.informaltable table { + display: table; + width: 100%; +} + +div.table td { + padding-left: 7px; + padding-right: 7px; +} + +.sidebar { + line-height: 1.4; + padding: 0 20px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; +} + +.sidebar p.title { + color: #6D180B; +} + +pre.programlisting,pre.screen { + font-size: 15px; + padding: 6px 10px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; + clear: both; + overflow: auto; + line-height: 1.4; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +table { + border-collapse: collapse; + border-spacing: 0; + border: 1px solid #DDDDDD !important; + border-radius: 4px !important; + border-collapse: separate !important; + line-height: 1.6; +} + +table thead { + background: #F5F5F5; +} + +table tr { + border: none; + border-bottom: none; +} + +table th { + font-weight: bold; +} + +table th,table td { + border: none !important; + padding: 6px 13px; +} + +table tr:nth-child(2n) { + background-color: #F8F8F8; +} + +td p { + margin: 0 0 15px 0; +} + +div.table-contents td p { + margin: 0; +} + +div.important *,div.note *,div.tip *,div.warning *,div.navheader *,div.navfooter *,div.calloutlist * + { + border: none !important; + background: none !important; + margin: 0; +} + +div.important p,div.note p,div.tip p,div.warning p { + color: #6F6F6F; + line-height: 1.6; +} + +div.important code,div.note code,div.tip code,div.warning code { + background-color: #F2F2F2 !important; + border: 1px solid #CCCCCC !important; + border-radius: 4px !important; + padding: 1px 3px 0 !important; + text-shadow: none !important; + white-space: nowrap !important; +} + +.note th,.tip th,.warning th { + display: none; +} + +.note tr:first-child td,.tip tr:first-child td,.warning tr:first-child td + { + border-right: 1px solid #CCCCCC !important; + padding-top: 10px; +} + +div.calloutlist p,div.calloutlist td { + padding: 0; + margin: 0; +} + +div.calloutlist>table>tbody>tr>td:first-child { + padding-left: 10px; + width: 30px !important; +} + +div.important,div.note,div.tip,div.warning { + margin-left: 0px !important; + margin-right: 20px !important; + margin-top: 20px; + margin-bottom: 20px; + padding-top: 10px; + padding-bottom: 10px; +} + +div.toc { + line-height: 1.2; +} + +dl,dt { + margin-top: 1px; + margin-bottom: 0; +} + +div.toc>dl>dt { + font-size: 32px; + font-weight: bold; + margin: 30px 0 10px 0; + display: block; +} + +div.toc>dl>dd>dl>dt { + font-size: 24px; + font-weight: bold; + margin: 20px 0 10px 0; + display: block; +} + +div.toc>dl>dd>dl>dd>dl>dt { + font-weight: bold; + font-size: 20px; + margin: 10px 0 0 0; +} + +tbody.footnotes * { + border: none !important; +} + +div.footnote p { + margin: 0; + line-height: 1; +} + +div.footnote p sup { + margin-right: 6px; + vertical-align: middle; +} + +div.navheader { + border-bottom: 1px solid #CCCCCC; +} + +div.navfooter { + border-top: 1px solid #CCCCCC; +} + +.title { + margin-left: -1em; + padding-left: 1em; +} + +.title>a { + position: absolute; + visibility: hidden; + display: block; + font-size: 0.85em; + margin-top: 0.05em; + margin-left: -1em; + vertical-align: text-top; + color: black; +} + +.title>a:before { + content: "\00A7"; +} + +.title:hover>a,.title>a:hover,.title:hover>a:hover { + visibility: visible; +} + +.title:focus>a,.title>a:focus,.title:focus>a:focus { + outline: 0; +} diff --git a/spring-cloud-netflix/2.0.0.M7/ghpages.sh b/spring-cloud-netflix/2.0.0.M7/ghpages.sh new file mode 100644 index 00000000..57c5da3a --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/ghpages.sh @@ -0,0 +1,330 @@ +#!/bin/bash -x + +set -e + +# Set default props like MAVEN_PATH, ROOT_FOLDER etc. +function set_default_props() { + # The script should be executed 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 + # http://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 whitelisted 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}]" + + + WHITELIST_PROPERTY=${WHITELIST_PROPERTY:-"docs.whitelisted.branches"} + WHITELISTED_BRANCHES_VALUE=$("${MAVEN_PATH}"mvn -q \ + -Dexec.executable="echo" \ + -Dexec.args="\${${WHITELIST_PROPERTY}}" \ + org.codehaus.mojo:exec-maven-plugin:1.3.1:exec \ + -P docs \ + -pl docs) + echo "Extracted '${WHITELIST_PROPERTY}' from Maven build [${WHITELISTED_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}]" + # http://stackoverflow.com/questions/29300806/a-bash-script-to-check-if-a-string-is-present-in-a-comma-separated-list-of-strin + if [[ ",${WHITELISTED_BRANCHES_VALUE}," = *",${CURRENT_BRANCH},"* ]] ; then + mkdir -p ${ROOT_FOLDER}/${CURRENT_BRANCH} + echo -e "Branch [${CURRENT_BRANCH}] is whitelisted! 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 white list! Check out the Maven [${WHITELIST_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 </` +- 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//` + +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 \ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/images/Hystrix.png b/spring-cloud-netflix/2.0.0.M7/images/Hystrix.png new file mode 100644 index 00000000..7d4e17ed Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/images/Hystrix.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/images/HystrixFallback.png b/spring-cloud-netflix/2.0.0.M7/images/HystrixFallback.png new file mode 100644 index 00000000..372018c7 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/images/HystrixFallback.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/images/HystrixGraph.png b/spring-cloud-netflix/2.0.0.M7/images/HystrixGraph.png new file mode 100644 index 00000000..c07c6bd5 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/images/HystrixGraph.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/images/RequestLatency.png b/spring-cloud-netflix/2.0.0.M7/images/RequestLatency.png new file mode 100644 index 00000000..6c7e93be Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/images/RequestLatency.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/images/background.png b/spring-cloud-netflix/2.0.0.M7/images/background.png new file mode 100644 index 00000000..15dca6fb Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/images/background.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/images/caution.png b/spring-cloud-netflix/2.0.0.M7/images/caution.png new file mode 100644 index 00000000..8a5e4fca Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/images/caution.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/images/important.png b/spring-cloud-netflix/2.0.0.M7/images/important.png new file mode 100644 index 00000000..ec54df65 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/images/important.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/images/logo.png b/spring-cloud-netflix/2.0.0.M7/images/logo.png new file mode 100644 index 00000000..ade2ce6e Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/images/logo.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/images/note.png b/spring-cloud-netflix/2.0.0.M7/images/note.png new file mode 100644 index 00000000..88d997b1 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/images/note.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/images/sts_exception.png b/spring-cloud-netflix/2.0.0.M7/images/sts_exception.png new file mode 100644 index 00000000..8607c38a Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/images/sts_exception.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/images/tip.png b/spring-cloud-netflix/2.0.0.M7/images/tip.png new file mode 100644 index 00000000..6530abb4 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/images/tip.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/images/warning.png b/spring-cloud-netflix/2.0.0.M7/images/warning.png new file mode 100644 index 00000000..0d5b5244 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/images/warning.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/images/web-selected.png b/spring-cloud-netflix/2.0.0.M7/images/web-selected.png new file mode 100644 index 00000000..aa6b2da6 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/images/web-selected.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/index.html b/spring-cloud-netflix/2.0.0.M7/index.html new file mode 100644 index 00000000..acc6b0f4 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/index.html @@ -0,0 +1,117 @@ + + + + + + + +spring-cloud-netflix + + + + + + + + +
+
+
+
+

2.0.0.M7

+
+
+
+
+

Pick The Documentation Option

+
+
+ +
+
+
+
+ + + + + \ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/css/highlight.css b/spring-cloud-netflix/2.0.0.M7/multi/css/highlight.css new file mode 100644 index 00000000..ffefef72 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/css/highlight.css @@ -0,0 +1,35 @@ +/* + code highlight CSS resemblign the Eclipse IDE default color schema + @author Costin Leau +*/ + +.hl-keyword { + color: #7F0055; + font-weight: bold; +} + +.hl-comment { + color: #3F5F5F; + font-style: italic; +} + +.hl-multiline-comment { + color: #3F5FBF; + font-style: italic; +} + +.hl-tag { + color: #3F7F7F; +} + +.hl-attribute { + color: #7F007F; +} + +.hl-value { + color: #2A00FF; +} + +.hl-string { + color: #2A00FF; +} \ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/css/manual-multipage.css b/spring-cloud-netflix/2.0.0.M7/multi/css/manual-multipage.css new file mode 100644 index 00000000..0c484531 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/css/manual-multipage.css @@ -0,0 +1,9 @@ +@IMPORT url("manual.css"); + +body.firstpage { + background: url("../images/background.png") no-repeat center top; +} + +div.part h1 { + border-top: none; +} diff --git a/spring-cloud-netflix/2.0.0.M7/multi/css/manual-singlepage.css b/spring-cloud-netflix/2.0.0.M7/multi/css/manual-singlepage.css new file mode 100644 index 00000000..4a7fd140 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/css/manual-singlepage.css @@ -0,0 +1,6 @@ +@IMPORT url("manual.css"); + +body { + background: url("../images/background.png") no-repeat center top; +} + diff --git a/spring-cloud-netflix/2.0.0.M7/multi/css/manual.css b/spring-cloud-netflix/2.0.0.M7/multi/css/manual.css new file mode 100644 index 00000000..0ecbe2e8 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/css/manual.css @@ -0,0 +1,344 @@ +@IMPORT url("highlight.css"); + +html { + padding: 0pt; + margin: 0pt; +} + +body { + color: #333333; + margin: 15px 30px; + font-family: Helvetica, Arial, Freesans, Clean, Sans-serif; + line-height: 1.6; + -webkit-font-smoothing: antialiased; +} + +code { + font-size: 16px; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +:not(a)>code { + color: #6D180B; +} + +:not(pre)>code { + background-color: #F2F2F2; + border: 1px solid #CCCCCC; + border-radius: 4px; + padding: 1px 3px 0; + text-shadow: none; + white-space: nowrap; +} + +body>*:first-child { + margin-top: 0 !important; +} + +div { + margin: 0pt; +} + +hr { + border: 1px solid #CCCCCC; + background: #CCCCCC; +} + +h1,h2,h3,h4,h5,h6 { + color: #000000; + cursor: text; + font-weight: bold; + margin: 30px 0 10px; + padding: 0; +} + +h1,h2,h3 { + margin: 40px 0 10px; +} + +h1 { + margin: 70px 0 30px; + padding-top: 20px; +} + +div.part h1 { + border-top: 1px dotted #CCCCCC; +} + +h1,h1 code { + font-size: 32px; +} + +h2,h2 code { + font-size: 24px; +} + +h3,h3 code { + font-size: 20px; +} + +h4,h1 code,h5,h5 code,h6,h6 code { + font-size: 18px; +} + +div.book,div.chapter,div.appendix,div.part,div.preface { + min-width: 300px; + max-width: 1200px; + margin: 0 auto; +} + +p.releaseinfo { + font-weight: bold; + margin-bottom: 40px; + margin-top: 40px; +} + +div.authorgroup { + line-height: 1; +} + +p.copyright { + line-height: 1; + margin-bottom: -5px; +} + +.legalnotice p { + font-style: italic; + font-size: 14px; + line-height: 1; +} + +div.titlepage+p,div.titlepage+p { + margin-top: 0; +} + +pre { + line-height: 1.0; + color: black; +} + +a { + color: #4183C4; + text-decoration: none; +} + +p { + margin: 15px 0; + text-align: left; +} + +ul,ol { + padding-left: 30px; +} + +li p { + margin: 0; +} + +div.table { + margin: 1em; + padding: 0.5em; + text-align: center; +} + +div.table table,div.informaltable table { + display: table; + width: 100%; +} + +div.table td { + padding-left: 7px; + padding-right: 7px; +} + +.sidebar { + line-height: 1.4; + padding: 0 20px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; +} + +.sidebar p.title { + color: #6D180B; +} + +pre.programlisting,pre.screen { + font-size: 15px; + padding: 6px 10px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; + clear: both; + overflow: auto; + line-height: 1.4; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +table { + border-collapse: collapse; + border-spacing: 0; + border: 1px solid #DDDDDD !important; + border-radius: 4px !important; + border-collapse: separate !important; + line-height: 1.6; +} + +table thead { + background: #F5F5F5; +} + +table tr { + border: none; + border-bottom: none; +} + +table th { + font-weight: bold; +} + +table th,table td { + border: none !important; + padding: 6px 13px; +} + +table tr:nth-child(2n) { + background-color: #F8F8F8; +} + +td p { + margin: 0 0 15px 0; +} + +div.table-contents td p { + margin: 0; +} + +div.important *,div.note *,div.tip *,div.warning *,div.navheader *,div.navfooter *,div.calloutlist * + { + border: none !important; + background: none !important; + margin: 0; +} + +div.important p,div.note p,div.tip p,div.warning p { + color: #6F6F6F; + line-height: 1.6; +} + +div.important code,div.note code,div.tip code,div.warning code { + background-color: #F2F2F2 !important; + border: 1px solid #CCCCCC !important; + border-radius: 4px !important; + padding: 1px 3px 0 !important; + text-shadow: none !important; + white-space: nowrap !important; +} + +.note th,.tip th,.warning th { + display: none; +} + +.note tr:first-child td,.tip tr:first-child td,.warning tr:first-child td + { + border-right: 1px solid #CCCCCC !important; + padding-top: 10px; +} + +div.calloutlist p,div.calloutlist td { + padding: 0; + margin: 0; +} + +div.calloutlist>table>tbody>tr>td:first-child { + padding-left: 10px; + width: 30px !important; +} + +div.important,div.note,div.tip,div.warning { + margin-left: 0px !important; + margin-right: 20px !important; + margin-top: 20px; + margin-bottom: 20px; + padding-top: 10px; + padding-bottom: 10px; +} + +div.toc { + line-height: 1.2; +} + +dl,dt { + margin-top: 1px; + margin-bottom: 0; +} + +div.toc>dl>dt { + font-size: 32px; + font-weight: bold; + margin: 30px 0 10px 0; + display: block; +} + +div.toc>dl>dd>dl>dt { + font-size: 24px; + font-weight: bold; + margin: 20px 0 10px 0; + display: block; +} + +div.toc>dl>dd>dl>dd>dl>dt { + font-weight: bold; + font-size: 20px; + margin: 10px 0 0 0; +} + +tbody.footnotes * { + border: none !important; +} + +div.footnote p { + margin: 0; + line-height: 1; +} + +div.footnote p sup { + margin-right: 6px; + vertical-align: middle; +} + +div.navheader { + border-bottom: 1px solid #CCCCCC; +} + +div.navfooter { + border-top: 1px solid #CCCCCC; +} + +.title { + margin-left: -1em; + padding-left: 1em; +} + +.title>a { + position: absolute; + visibility: hidden; + display: block; + font-size: 0.85em; + margin-top: 0.05em; + margin-left: -1em; + vertical-align: text-top; + color: black; +} + +.title>a:before { + content: "\00A7"; +} + +.title:hover>a,.title>a:hover,.title:hover>a:hover { + visibility: visible; +} + +.title:focus>a,.title>a:focus,.title:focus>a:focus { + outline: 0; +} diff --git a/spring-cloud-netflix/2.0.0.M7/multi/images/background.png b/spring-cloud-netflix/2.0.0.M7/multi/images/background.png new file mode 100644 index 00000000..15dca6fb Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/multi/images/background.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/multi/images/caution.png b/spring-cloud-netflix/2.0.0.M7/multi/images/caution.png new file mode 100644 index 00000000..8a5e4fca Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/multi/images/caution.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/multi/images/important.png b/spring-cloud-netflix/2.0.0.M7/multi/images/important.png new file mode 100644 index 00000000..ec54df65 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/multi/images/important.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/multi/images/logo.png b/spring-cloud-netflix/2.0.0.M7/multi/images/logo.png new file mode 100644 index 00000000..ade2ce6e Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/multi/images/logo.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/multi/images/note.png b/spring-cloud-netflix/2.0.0.M7/multi/images/note.png new file mode 100644 index 00000000..88d997b1 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/multi/images/note.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/multi/images/sts_exception.png b/spring-cloud-netflix/2.0.0.M7/multi/images/sts_exception.png new file mode 100644 index 00000000..8607c38a Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/multi/images/sts_exception.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/multi/images/tip.png b/spring-cloud-netflix/2.0.0.M7/multi/images/tip.png new file mode 100644 index 00000000..6530abb4 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/multi/images/tip.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/multi/images/warning.png b/spring-cloud-netflix/2.0.0.M7/multi/images/warning.png new file mode 100644 index 00000000..0d5b5244 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/multi/images/warning.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/multi/images/web-selected.png b/spring-cloud-netflix/2.0.0.M7/multi/images/web-selected.png new file mode 100644 index 00000000..aa6b2da6 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/multi/images/web-selected.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi__circuit_breaker_hystrix_clients.html b/spring-cloud-netflix/2.0.0.M7/multi/multi__circuit_breaker_hystrix_clients.html new file mode 100644 index 00000000..12b8c4a3 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi__circuit_breaker_hystrix_clients.html @@ -0,0 +1,52 @@ + + + 3. Circuit Breaker: Hystrix Clients

3. Circuit Breaker: Hystrix Clients

Netflix has created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture it is common to have multiple layers of service calls.

Figure 3.1. Microservice Graph

Hystrix

A service failure in the lower level of services can cause cascading failure all the way up to the user. When calls to a particular service is greater than circuitBreaker.requestVolumeThreshold (default: 20 requests) and failue percentage is greater than circuitBreaker.errorThresholdPercentage (default: >50%) in a rolling window defined by metrics.rollingStats.timeInMilliseconds (default: 10 seconds), the circuit opens and the call is not made. In cases of error and an open circuit a fallback can be provided by the developer.

Figure 3.2. Hystrix fallback prevents cascading failures

HystrixFallback

Having an open circuit stops cascading failures and allows overwhelmed or failing services time to heal. The fallback can be another Hystrix protected call, static data or a sane empty value. Fallbacks may be chained so the first fallback makes some other business call which in turn falls back to static data.

3.1 How to Include Hystrix

To include Hystrix in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-hystrix. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train.

Example boot app:

@SpringBootApplication
+@EnableCircuitBreaker
+public class Application {
+
+    public static void main(String[] args) {
+        new SpringApplicationBuilder(Application.class).web(true).run(args);
+    }
+
+}
+
+@Component
+public class StoreIntegration {
+
+    @HystrixCommand(fallbackMethod = "defaultStores")
+    public Object getStores(Map<String, Object> parameters) {
+        //do stuff that might fail
+    }
+
+    public Object defaultStores(Map<String, Object> parameters) {
+        return /* something useful */;
+    }
+}

The @HystrixCommand is provided by a Netflix contrib library called +"javanica". +Spring Cloud automatically wraps Spring beans with that +annotation in a proxy that is connected to the Hystrix circuit +breaker. The circuit breaker calculates when to open and close the +circuit, and what to do in case of a failure.

To configure the @HystrixCommand you can use the commandProperties +attribute with a list of @HystrixProperty annotations. See +here +for more details. See the Hystrix wiki +for details on the properties available.

3.2 Propagating the Security Context or using Spring Scopes

If you want some thread local context to propagate into a @HystrixCommand the default declaration will not work because it executes the command in a thread pool (in case of timeouts). You can switch Hystrix to use the same thread as the caller using some configuration, or directly in the annotation, by asking it to use a different "Isolation Strategy". For example:

@HystrixCommand(fallbackMethod = "stubMyService",
+    commandProperties = {
+      @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
+    }
+)
+...

The same thing applies if you are using @SessionScope or @RequestScope. You will know when you need to do this because of a runtime exception that says it can’t find the scoped context.

You also have the option to set the hystrix.shareSecurityContext property to true. Doing so will auto configure an Hystrix concurrency strategy plugin hook who will transfer the SecurityContext from your main thread to the one used by the Hystrix command. Hystrix does not allow multiple hystrix concurrency strategy to be registered so an extension mechanism is available by declaring your own HystrixConcurrencyStrategy as a Spring bean. Spring Cloud will lookup for your implementation within the Spring context and wrap it inside its own plugin.

3.3 Health Indicator

The state of the connected circuit breakers are also exposed in the +/health endpoint of the calling application.

{
+    "hystrix": {
+        "openCircuitBreakers": [
+            "StoreIntegration::getStoresByLocationLink"
+        ],
+        "status": "CIRCUIT_OPEN"
+    },
+    "status": "UP"
+}

3.4 Hystrix Metrics Stream

To enable the Hystrix metrics stream include a dependency on spring-boot-starter-actuator. This will expose the /hystrix.stream as a management endpoint.

    <dependency>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-actuator</artifactId>
+    </dependency>
\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi__circuit_breaker_hystrix_dashboard.html b/spring-cloud-netflix/2.0.0.M7/multi/multi__circuit_breaker_hystrix_dashboard.html new file mode 100644 index 00000000..5ae0f758 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi__circuit_breaker_hystrix_dashboard.html @@ -0,0 +1,3 @@ + + + 4. Circuit Breaker: Hystrix Dashboard

4. Circuit Breaker: Hystrix Dashboard

One of the main benefits of Hystrix is the set of metrics it gathers about each HystrixCommand. The Hystrix Dashboard displays the health of each circuit breaker in an efficient manner.

Figure 4.1. Hystrix Dashboard

Hystrix

\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi__external_configuration_archaius.html b/spring-cloud-netflix/2.0.0.M7/multi/multi__external_configuration_archaius.html new file mode 100644 index 00000000..c7e0f93b --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi__external_configuration_archaius.html @@ -0,0 +1,13 @@ + + + 7. External Configuration: Archaius

7. External Configuration: Archaius

Archaius is the Netflix client side configuration library. It is the library used by all of the Netflix OSS components for configuration. Archaius is an extension of the Apache Commons Configuration project. It allows updates to configuration by either polling a source for changes or for a source to push changes to the client. Archaius uses Dynamic<Type>Property classes as handles to properties.

Archaius Example.  +

class ArchaiusTest {
+    DynamicStringProperty myprop = DynamicPropertyFactory
+            .getInstance()
+            .getStringProperty("my.prop");
+
+    void doSomething() {
+        OtherClass.someMethod(myprop.get());
+    }
+}

+

Archaius has its own set of configuration files and loading priorities. Spring applications should generally not use Archaius directly, but the need to configure the Netflix tools natively remains. Spring Cloud has a Spring Environment Bridge so Archaius can read properties from the Spring Environment. This allows Spring Boot projects to use the normal configuration toolchain, while allowing them to configure the Netflix tools, for the most part, as documented.

\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi__http_clients.html b/spring-cloud-netflix/2.0.0.M7/multi/multi__http_clients.html new file mode 100644 index 00000000..19a129f8 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi__http_clients.html @@ -0,0 +1,8 @@ + + + 12. HTTP Clients

12. HTTP Clients

Spring Cloud Netflix will automatically create the HTTP client used by Ribbon, Feign, and +Zuul for you. However you can also provide your own HTTP clients customized how you please +yourself. To do this you can either create a bean of type ClosableHttpClient if you +are using the Apache Http Cient, or OkHttpClient if you are using OK HTTP.

[Note]Note

When you create your own HTTP client you are also responsible for implementing +the correct connection management strategies for these clients. Doing this improperly +can result in resource management issues.

\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi__hystrix_timeouts_and_ribbon_clients.html b/spring-cloud-netflix/2.0.0.M7/multi/multi__hystrix_timeouts_and_ribbon_clients.html new file mode 100644 index 00000000..ba6a89eb --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi__hystrix_timeouts_and_ribbon_clients.html @@ -0,0 +1,26 @@ + + + 5. Hystrix Timeouts And Ribbon Clients

5. Hystrix Timeouts And Ribbon Clients

When using Hystrix commands that wrap Ribbon clients you want to make sure your Hystrix timeout +is configured to be longer than the configured Ribbon timeout, including any potential +retries that might be made. For example, if your Ribbon connection timeout is one second and +the Ribbon client might retry the request three times, than your Hystrix timeout should +be slightly more than three seconds.

5.1 How to Include Hystrix Dashboard

To include the Hystrix Dashboard in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-hystrix-dashboard. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train.

To run the Hystrix Dashboard annotate your Spring Boot main class with @EnableHystrixDashboard. You then visit /hystrix and point the dashboard to an individual instances /hystrix.stream endpoint in a Hystrix client application.

[Note]Note

When connecting to a /hystrix.stream endpoint which uses HTTPS the certificate used by the server +must be trusted by the JVM. If the certificate is not trusted you must import the certificate into the JVM +in order for the Hystrix Dashboard to make a successful connection to the stream endpoint.

5.2 Turbine

Looking at an individual instances Hystrix data is not very useful in terms of the overall health of the system. Turbine is an application that aggregates all of the relevant /hystrix.stream endpoints into a combined /turbine.stream for use in the Hystrix Dashboard. Individual instances are located via Eureka. Running Turbine is as simple as annotating your main class with the @EnableTurbine annotation (e.g. using spring-cloud-starter-netflix-turbine to set up the classpath). All of the documented configuration properties from the Turbine 1 wiki apply. The only difference is that the turbine.instanceUrlSuffix does not need the port prepended as this is handled automatically unless turbine.instanceInsertPort=false.

[Note]Note

By default, Turbine looks for the /hystrix.stream endpoint on a registered instance by looking up its hostName and port entries in Eureka, then appending /hystrix.stream to it. +If the instance’s metadata contains management.port, it will be used instead of the port value for the /hystrix.stream endpoint. +By default, metadata entry management.port is equal to the management.port configuration property, it can be overridden though with following configuration:

eureka:
+  instance:
+    metadata-map:
+      management.port: ${management.port:8081}

The configuration key turbine.appConfig is a list of eureka serviceIds that turbine will use to lookup instances. The turbine stream is then used in the Hystrix dashboard using a url that looks like: http://my.turbine.server:8080/turbine.stream?cluster=CLUSTERNAME (the cluster parameter can be omitted if the name is "default"). The cluster parameter must match an entry in turbine.aggregator.clusterConfig. Values returned from eureka are uppercase, thus we expect this example to work if there is an app registered with Eureka called "customers":

turbine:
+  aggregator:
+    clusterConfig: CUSTOMERS
+  appConfig: customers

If you need to customize which cluster names should be used by Turbine (you don’t want to store cluster names in +turbine.aggregator.clusterConfig configuration) provide a bean of type TurbineClustersProvider.

The clusterName can be customized by a SPEL expression in turbine.clusterNameExpression with root an instance of InstanceInfo. The default value is appName, which means that the Eureka serviceId ends up as the cluster key (i.e. the InstanceInfo for customers has an appName of "CUSTOMERS"). A different example would be turbine.clusterNameExpression=aSGName, which would get the cluster name from the AWS ASG name. Another example:

turbine:
+  aggregator:
+    clusterConfig: SYSTEM,USER
+  appConfig: customers,stores,ui,admin
+  clusterNameExpression: metadata['cluster']

In this case, the cluster name from 4 services is pulled from their metadata map, and is expected to have values that include "SYSTEM" and "USER".

To use the "default" cluster for all apps you need a string literal expression (with single quotes, and escaped with double quotes if it is in YAML as well):

turbine:
+  appConfig: customers,stores
+  clusterNameExpression: "'default'"

Spring Cloud provides a spring-cloud-starter-netflix-turbine that has all the dependencies you need to get a Turbine server running. Just create a Spring Boot application and annotate it with @EnableTurbine.

[Note]Note

by default Spring Cloud allows Turbine to use the host and port to allow multiple processes per host, per cluster. If you want the native Netflix behaviour built into Turbine that does not allow multiple processes per host, per cluster (the key to the instance id is the hostname), then set the property turbine.combineHostPort=false.

5.3 Turbine Stream

In some environments (e.g. in a PaaS setting), the classic Turbine model of pulling metrics from all the distributed Hystrix commands doesn’t work. In that case you might want to have your Hystrix commands push metrics to Turbine, and Spring Cloud enables that with messaging. All you need to do on the client is add a dependency to spring-cloud-netflix-hystrix-stream and the spring-cloud-starter-stream-* of your choice (see Spring Cloud Stream documentation for details on the brokers, and how to configure the client credentials, but it should work out of the box for a local broker).

On the server side Just create a Spring Boot application and annotate it with @EnableTurbineStream and by default it will come up on port 8989 (point your Hystrix dashboard to that port, any path). You can customize the port using either server.port or turbine.stream.port. If you have spring-boot-starter-web and spring-boot-starter-actuator on the classpath as well, then you can open up the Actuator endpoints on a separate port (with Tomcat by default) by providing a management.port which is different.

You can then point the Hystrix Dashboard to the Turbine Stream Server instead of individual Hystrix streams. If Turbine Stream is running on port 8989 on myhost, then put http://myhost:8989 in the stream input field in the Hystrix Dashboard. Circuits will be prefixed by their respective serviceId, followed by a dot, then the circuit name.

Spring Cloud provides a spring-cloud-starter-netflix-turbine-stream that has all the dependencies you need to get a Turbine Stream server running - just add the Stream binder of your choice, e.g. spring-cloud-starter-stream-rabbit. You need Java 8 to run the app because it is Netty-based.

\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi__polyglot_support_with_sidecar.html b/spring-cloud-netflix/2.0.0.M7/multi/multi__polyglot_support_with_sidecar.html new file mode 100644 index 00000000..928fb49e --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi__polyglot_support_with_sidecar.html @@ -0,0 +1,67 @@ + + + 9. Polyglot support with Sidecar

9. Polyglot support with Sidecar

Do you have non-jvm languages you want to take advantage of Eureka, Ribbon and +Config Server? The Spring Cloud Netflix Sidecar was inspired by +Netflix Prana. It includes a simple http api +to get all of the instances (ie host and port) for a given service. You can +also proxy service calls through an embedded Zuul proxy which gets its route +entries from Eureka. The Spring Cloud Config Server can be accessed directly +via host lookup or through the Zuul Proxy. The non-jvm app should implement +a health check so the Sidecar can report to eureka if the app is up or down.

To include Sidecar in your project use the dependency with group org.springframework.cloud +and artifact id spring-cloud-netflix-sidecar.

To enable the Sidecar, create a Spring Boot application with @EnableSidecar. +This annotation includes @EnableCircuitBreaker, @EnableDiscoveryClient, +and @EnableZuulProxy. Run the resulting application on the same host as the +non-jvm application.

To configure the side car add sidecar.port and sidecar.health-uri to application.yml. +The sidecar.port property is the port the non-jvm app is listening on. This +is so the Sidecar can properly register the app with Eureka. The sidecar.health-uri +is a uri accessible on the non-jvm app that mimicks a Spring Boot health +indicator. It should return a json document like the following:

health-uri-document.  +

{
+  "status":"UP"
+}

+

Here is an example application.yml for a Sidecar application:

application.yml.  +

server:
+  port: 5678
+spring:
+  application:
+    name: sidecar
+
+sidecar:
+  port: 8000
+  health-uri: http://localhost:8000/health.json

+

The api for the DiscoveryClient.getInstances() method is /hosts/{serviceId}. +Here is an example response for /hosts/customers that returns two instances on +different hosts. This api is accessible to the non-jvm app (if the sidecar is +on port 5678) at http://localhost:5678/hosts/{serviceId}.

/hosts/customers.  +

[
+    {
+        "host": "myhost",
+        "port": 9000,
+        "uri": "http://myhost:9000",
+        "serviceId": "CUSTOMERS",
+        "secure": false
+    },
+    {
+        "host": "myhost2",
+        "port": 9000,
+        "uri": "http://myhost2:9000",
+        "serviceId": "CUSTOMERS",
+        "secure": false
+    }
+]

+

The Zuul proxy automatically adds routes for each service known in eureka to +/<serviceId>, so the customers service is available at /customers. The +Non-jvm app can access the customer service via http://localhost:5678/customers +(assuming the sidecar is listening on port 5678).

If the Config Server is registered with Eureka, non-jvm application can access +it via the Zuul proxy. If the serviceId of the ConfigServer is configserver +and the Sidecar is on port 5678, then it can be accessed at +http://localhost:5678/configserver

Non-jvm app can take advantage of the Config Server’s ability to return YAML +documents. For example, a call to http://sidecar.local.spring.io:5678/configserver/default-master.yml +might result in a YAML document like the following

eureka:
+  client:
+    serviceUrl:
+      defaultZone: http://localhost:8761/eureka/
+  password: password
+info:
+  description: Spring Cloud Samples
+  url: https://github.com/spring-cloud-samples
\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi__router_and_filter_zuul.html b/spring-cloud-netflix/2.0.0.M7/multi/multi__router_and_filter_zuul.html new file mode 100644 index 00000000..4459d7df --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi__router_and_filter_zuul.html @@ -0,0 +1,536 @@ + + + 8. Router and Filter: Zuul

8. Router and Filter: Zuul

Routing is an integral part of a microservice architecture. For example, / may be mapped to your web application, /api/users is mapped to the user service and /api/shop is mapped to the shop service. Zuul is a JVM based router and server side load balancer by Netflix.

Netflix uses Zuul for the following:

  • Authentication
  • Insights
  • Stress Testing
  • Canary Testing
  • Dynamic Routing
  • Service Migration
  • Load Shedding
  • Security
  • Static Response handling
  • Active/Active traffic management

Zuul’s rule engine allows rules and filters to be written in essentially any JVM language, with built in support for Java and Groovy.

[Note]Note

The configuration property zuul.max.host.connections has been replaced by two new properties, zuul.host.maxTotalConnections and zuul.host.maxPerRouteConnections which default to 200 and 20 respectively.

[Note]Note

Default Hystrix isolation pattern (ExecutionIsolationStrategy) for all routes is SEMAPHORE. zuul.ribbonIsolationStrategy can be changed to THREAD if this isolation pattern is preferred.

8.1 How to Include Zuul

To include Zuul in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-zuul. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train.

8.2 Embedded Zuul Reverse Proxy

Spring Cloud has created an embedded Zuul proxy to ease the +development of a very common use case where a UI application wants to +proxy calls to one or more back end services. This feature is useful +for a user interface to proxy to the backend services it requires, +avoiding the need to manage CORS and authentication concerns +independently for all the backends.

To enable it, annotate a Spring Boot main class with +@EnableZuulProxy, and this forwards local calls to the appropriate +service. By convention, a service with the ID "users", will +receive requests from the proxy located at /users (with the prefix +stripped). The proxy uses Ribbon to locate an instance to forward to +via discovery, and all requests are executed in a +hystrix command, so +failures will show up in Hystrix metrics, and once the circuit is open +the proxy will not try to contact the service.

[Note]Note

the Zuul starter does not include a discovery client, so for +routes based on service IDs you need to provide one of those +on the classpath as well (e.g. Eureka is one choice).

To skip having a service automatically added, set +zuul.ignored-services to a list of service id patterns. If a service +matches a pattern that is ignored, but also included in the explicitly +configured routes map, then it will be unignored. Example:

application.yml.  +

 zuul:
+  ignoredServices: '*'
+  routes:
+    users: /myusers/**

+

In this example, all services are ignored except "users".

To augment or change +the proxy routes, you can add external configuration like the +following:

application.yml.  +

 zuul:
+  routes:
+    users: /myusers/**

+

This means that http calls to "/myusers" get forwarded to the "users" +service (for example "/myusers/101" is forwarded to "/101").

To get more fine-grained control over a route you can specify the path +and the serviceId independently:

application.yml.  +

 zuul:
+  routes:
+    users:
+      path: /myusers/**
+      serviceId: users_service

+

This means that http calls to "/myusers" get forwarded to the +"users_service" service. The route has to have a "path" which can be +specified as an ant-style pattern, so "/myusers/*" only matches one +level, but "/myusers/**" matches hierarchically.

The location of the backend can be specified as either a "serviceId" +(for a service from discovery) or a "url" (for a physical location), e.g.

application.yml.  +

 zuul:
+  routes:
+    users:
+      path: /myusers/**
+      url: http://example.com/users_service

+

These simple url-routes don’t get executed as a HystrixCommand nor do they loadbalance multiple URLs with Ribbon. +To achieve this, you can specify a serviceId with a static list of servers:

application.yml.  +

zuul:
+  routes:
+    echo:
+      path: /myusers/**
+      serviceId: myusers-service
+      stripPrefix: true
+
+hystrix:
+  command:
+    myusers-service:
+      execution:
+        isolation:
+          thread:
+            timeoutInMilliseconds: ...
+
+myusers-service:
+  ribbon:
+    NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
+    ListOfServers: http://example1.com,http://example2.com
+    ConnectTimeout: 1000
+    ReadTimeout: 3000
+    MaxTotalHttpConnections: 500
+    MaxConnectionsPerHost: 100

+

Another method is specifiying a service-route and configure a Ribbon client for the +serviceId (this requires disabling Eureka support in Ribbon: +see above for more information), e.g.

application.yml.  +

zuul:
+  routes:
+    users:
+      path: /myusers/**
+      serviceId: users
+
+ribbon:
+  eureka:
+    enabled: false
+
+users:
+  ribbon:
+    listOfServers: example.com,google.com

+

You can provide convention between serviceId and routes using +regexmapper. It uses regular expression named groups to extract +variables from serviceId and inject them into a route pattern.

ApplicationConfiguration.java.  +

@Bean
+public PatternServiceRouteMapper serviceRouteMapper() {
+    return new PatternServiceRouteMapper(
+        "(?<name>^.+)-(?<version>v.+$)",
+        "${version}/${name}");
+}

+

This means that a serviceId "myusers-v1" will be mapped to route +"/v1/myusers/**". Any regular expression is accepted but all named +groups must be present in both servicePattern and routePattern. If +servicePattern does not match a serviceId, the default behavior is +used. In the example above, a serviceId "myusers" will be mapped to route +"/myusers/**" (no version detected) This feature is disabled by +default and only applies to discovered services.

To add a prefix to all mappings, set zuul.prefix to a value, such as +/api. The proxy prefix is stripped from the request before the +request is forwarded by default (switch this behaviour off with +zuul.stripPrefix=false). You can also switch off the stripping of +the service-specific prefix from individual routes, e.g.

application.yml.  +

 zuul:
+  routes:
+    users:
+      path: /myusers/**
+      stripPrefix: false

+

[Note]Note

zuul.stripPrefix only applies to the prefix set in zuul.prefix. It does not have any effect on prefixes +defined within a given route’s path.

In this example, requests to "/myusers/101" will be forwarded to "/myusers/101" on the "users" service.

The zuul.routes entries actually bind to an object of type ZuulProperties. If you +look at the properties of that object you will see that it also has a "retryable" flag. +Set that flag to "true" to have the Ribbon client automatically retry failed requests +(and if you need to you can modify the parameters of the retry operations using +the Ribbon client configuration).

The X-Forwarded-Host header is added to the forwarded requests by +default. To turn it off set zuul.addProxyHeaders = false. The +prefix path is stripped by default, and the request to the backend +picks up a header "X-Forwarded-Prefix" ("/myusers" in the examples +above).

An application with @EnableZuulProxy could act as a standalone +server if you set a default route ("/"), for example zuul.route.home: +/ would route all traffic (i.e. "/**") to the "home" service.

If more fine-grained ignoring is needed, you can specify specific patterns to ignore. +These patterns are evaluated at the start of the route location process, which +means prefixes should be included in the pattern to warrant a match. Ignored patterns +span all services and supersede any other route specification.

application.yml.  +

 zuul:
+  ignoredPatterns: /**/admin/**
+  routes:
+    users: /myusers/**

+

This means that all calls such as "/myusers/101" will be forwarded to "/101" on the "users" service. +But calls including "/admin/" will not resolve.

[Warning]Warning

If you need your routes to have their order preserved you need to use a YAML +file as the ordering will be lost using a properties file. For example:

application.yml.  +

 zuul:
+  routes:
+    users:
+      path: /myusers/**
+    legacy:
+      path: /**

+

If you were to use a properties file, the legacy path may end up in front of the users +path rendering the users path unreachable.

8.3 Zuul Http Client

The default HTTP client used by zuul is now backed by the Apache HTTP Client instead of the +deprecated Ribbon RestClient. To use RestClient or to use the okhttp3.OkHttpClient set +ribbon.restclient.enabled=true or ribbon.okhttp.enabled=true respectively. If you would +like to customize the Apache HTTP client or the OK HTTP client provide a bean of type +ClosableHttpClient or OkHttpClient.

8.4 Cookies and Sensitive Headers

It’s OK to share headers between services in the same system, but you +probably don’t want sensitive headers leaking downstream into external +servers. You can specify a list of ignored headers as part of the +route configuration. Cookies play a special role because they have +well-defined semantics in browsers, and they are always to be treated +as sensitive. If the consumer of your proxy is a browser, then cookies +for downstream services also cause problems for the user because they +all get jumbled up (all downstream services look like they come from +the same place).

If you are careful with the design of your services, for example if +only one of the downstream services sets cookies, then you might be +able to let them flow from the backend all the way up to the +caller. Also, if your proxy sets cookies and all your back end +services are part of the same system, it can be natural to simply +share them (and for instance use Spring Session to link them up to some +shared state). Other than that, any cookies that get set by downstream +services are likely to be not very useful to the caller, so it is +recommended that you make (at least) "Set-Cookie" and "Cookie" into +sensitive headers for routes that are not part of your domain. Even +for routes that are part of your domain, try to think carefully +about what it means before allowing cookies to flow between them and +the proxy.

The sensitive headers can be configured as a comma-separated list per +route, e.g.

application.yml.  +

 zuul:
+  routes:
+    users:
+      path: /myusers/**
+      sensitiveHeaders: Cookie,Set-Cookie,Authorization
+      url: https://downstream

+

[Note]Note

this is the default value for sensitiveHeaders, so you don’t +need to set it unless you want it to be different. N.B. this is new in +Spring Cloud Netflix 1.1 (in 1.0 the user had no control over headers +and all cookies flow in both directions).

The sensitiveHeaders are a blacklist and the default is not empty, +so to make Zuul send all headers (except the "ignored" ones) you would +have to explicitly set it to the empty list. This is necessary if you +want to pass cookie or authorization headers to your back end. Example:

application.yml.  +

 zuul:
+  routes:
+    users:
+      path: /myusers/**
+      sensitiveHeaders:
+      url: https://downstream

+

Sensitive headers can also be set globally by setting zuul.sensitiveHeaders. If sensitiveHeaders is set on a route, this will override the global sensitiveHeaders setting.

8.5 Ignored Headers

In addition to the per-route sensitive headers, you can set a global +value for zuul.ignoredHeaders for values that should be discarded +(both request and response) during interactions with downstream +services. By default these are empty, if Spring Security is not on the +classpath, and otherwise they are initialized to a set of well-known +"security" headers (e.g. involving caching) as specified by Spring +Security. The assumption in this case is that the downstream services +might add these headers too, and we want the values from the proxy. +To not discard these well known security headers in case Spring Security is on the classpath you can set zuul.ignoreSecurityHeaders to false. This can be useful if you disabled the HTTP Security response headers in Spring Security and want the values provided by downstream services

8.6 Management Endpoints

If you are using @EnableZuulProxy with the Spring Boot Actuator you +will enable (by default) two additional endpoints:

  • Routes
  • Filters

8.6.1 Routes Endpoint

A GET to the routes endpoint at /routes will return a list of the mapped +routes:

GET /routes.  +

{
+  /stores/**: "http://localhost:8081"
+}

+

Additional route details can be requested through the /routes/details endpoint. This will produce the following output:

GET /routes/details.  +

{
+  "/stores/**": {
+    "id": "stores",
+    "fullPath": "/stores/**",
+    "location": "http://localhost:8081",
+    "path": "/**",
+    "prefix": "/stores",
+    "retryable": false,
+    "customSensitiveHeaders": false,
+    "prefixStripped": true
+  }
+}

+

A POST to /routes will force a refresh of the existing routes (e.g. in +case there have been changes in the service catalog). You can disable +this endpoint by setting endpoints.routes.enabled to false.

[Note]Note

the routes should respond automatically to changes in the +service catalog, but the POST to /routes is a way to force the change +to happen immediately.

8.6.2 Filters Endpoint

A GET to the filters endpoint at /filters will return a map of Zuul +filters by type. For each filter type in the map, you will find a list +of all the filters of that type, along with their details.

8.7 Strangulation Patterns and Local Forwards

A common pattern when migrating an existing application or API is to +"strangle" old endpoints, slowly replacing them with different +implementations. The Zuul proxy is a useful tool for this because you +can use it to handle all traffic from clients of the old endpoints, +but redirect some of the requests to new ones.

Example configuration:

application.yml.  +

 zuul:
+  routes:
+    first:
+      path: /first/**
+      url: http://first.example.com
+    second:
+      path: /second/**
+      url: forward:/second
+    third:
+      path: /third/**
+      url: forward:/3rd
+    legacy:
+      path: /**
+      url: http://legacy.example.com

+

In this example we are strangling the "legacy" app which is mapped to +all requests that do not match one of the other patterns. Paths in +/first/** have been extracted into a new service with an external +URL. And paths in /second/** are forwarded so they can be handled +locally, e.g. with a normal Spring @RequestMapping. Paths in +/third/** are also forwarded, but with a different prefix +(i.e. /third/foo is forwarded to /3rd/foo).

[Note]Note

The ignored patterns aren’t completely ignored, they just +aren’t handled by the proxy (so they are also effectively forwarded +locally).

8.8 Uploading Files through Zuul

If you use @EnableZuulProxy, you can use the proxy paths to +upload files and it should just work as long as the files +are small. For large files there is an alternative path +which bypasses the Spring DispatcherServlet (to +avoid multipart processing) in "/zuul/*". I.e. if +zuul.routes.customers=/customers/** then you can +POST large files to "/zuul/customers/*". The servlet +path is externalized via zuul.servletPath. Extremely +large files will also require elevated timeout settings +if the proxy route takes you through a Ribbon load +balancer, e.g.

application.yml.  +

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000
+ribbon:
+  ConnectTimeout: 3000
+  ReadTimeout: 60000

+

Note that for streaming to work with large files, you need to use chunked encoding in the request (which some browsers +do not do by default). E.g. on the command line:

$ curl -v -H "Transfer-Encoding: chunked" \
+    -F "file=@mylarge.iso" localhost:9999/zuul/simple/file

8.9 Query String Encoding

When processing the incoming request, query params are decoded so they can be available for possible modifications in +Zuul filters. They are then re-encoded when building the backend request in the route filters. The result +can be different than the original input if it was encoded using Javascript’s encodeURIComponent() method for example. +While this causes no issues in most cases, some web servers can be picky with the encoding of complex query string.

To force the original encoding of the query string, it is possible to pass a special flag to ZuulProperties so +that the query string is taken as is with the HttpServletRequest::getQueryString method :

application.yml.  +

 zuul:
+  forceOriginalQueryStringEncoding: true

+

Note: This special flag only works with SimpleHostRoutingFilter and you loose the ability to easily override +query parameters with RequestContext.getCurrentContext().setRequestQueryParams(someOverriddenParameters) since +the query string is now fetched directly on the original HttpServletRequest.

8.10 Plain Embedded Zuul

You can also run a Zuul server without the proxying, or switch on parts of the proxying platform selectively, if you +use @EnableZuulServer (instead of @EnableZuulProxy). Any beans that you add to the application of type ZuulFilter +will be installed automatically, as they are with @EnableZuulProxy, but without any of the proxy filters being added +automatically.

In this case the routes into the Zuul server are still specified by +configuring "zuul.routes.*", but there is no service +discovery and no proxying, so the "serviceId" and "url" settings are +ignored. For example:

application.yml.  +

 zuul:
+  routes:
+    api: /api/**

+

maps all paths in "/api/**" to the Zuul filter chain.

8.11 Disable Zuul Filters

Zuul for Spring Cloud comes with a number of ZuulFilter beans enabled by default +in both proxy and server mode. See the zuul filters package for the +possible filters that are enabled. If you want to disable one, simply set +zuul.<SimpleClassName>.<filterType>.disable=true. By convention, the package after +filters is the Zuul filter type. For example to disable +org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter set +zuul.SendResponseFilter.post.disable=true.

8.12 Providing Hystrix Fallbacks For Routes

When a circuit for a given route in Zuul is tripped you can provide a fallback response +by creating a bean of type FallbackProvider. Within this bean you need to specify +the route ID the fallback is for and provide a ClientHttpResponse to return +as a fallback. Here is a very simple FallbackProvider implementation.

class MyFallbackProvider implements FallbackProvider {
+
+    @Override
+    public String getRoute() {
+        return "customers";
+    }
+
+    @Override
+    public ClientHttpResponse fallbackResponse(String route, final Throwable cause) {
+        if (cause instanceof HystrixTimeoutException) {
+            return response(HttpStatus.GATEWAY_TIMEOUT);
+        } else {
+            return response(HttpStatus.INTERNAL_SERVER_ERROR);
+        }
+    }
+
+    private ClientHttpResponse response(final HttpStatus status) {
+        return new ClientHttpResponse() {
+            @Override
+            public HttpStatus getStatusCode() throws IOException {
+                return status;
+            }
+
+            @Override
+            public int getRawStatusCode() throws IOException {
+                return status.value();
+            }
+
+            @Override
+            public String getStatusText() throws IOException {
+                return status.getReasonPhrase();
+            }
+
+            @Override
+            public void close() {
+            }
+
+            @Override
+            public InputStream getBody() throws IOException {
+                return new ByteArrayInputStream("fallback".getBytes());
+            }
+
+            @Override
+            public HttpHeaders getHeaders() {
+                HttpHeaders headers = new HttpHeaders();
+                headers.setContentType(MediaType.APPLICATION_JSON);
+                return headers;
+            }
+        };
+    }
+}

And here is what the route configuration would look like.

zuul:
+  routes:
+    customers: /customers/**

If you would like to provide a default fallback for all routes than you can create a bean of +type FallbackProvider and have the getRoute method return * or null.

class MyFallbackProvider implements FallbackProvider {
+    @Override
+    public String getRoute() {
+        return "*";
+    }
+
+    @Override
+    public ClientHttpResponse fallbackResponse(String route, Throwable throwable) {
+        return new ClientHttpResponse() {
+            @Override
+            public HttpStatus getStatusCode() throws IOException {
+                return HttpStatus.OK;
+            }
+
+            @Override
+            public int getRawStatusCode() throws IOException {
+                return 200;
+            }
+
+            @Override
+            public String getStatusText() throws IOException {
+                return "OK";
+            }
+
+            @Override
+            public void close() {
+
+            }
+
+            @Override
+            public InputStream getBody() throws IOException {
+                return new ByteArrayInputStream("fallback".getBytes());
+            }
+
+            @Override
+            public HttpHeaders getHeaders() {
+                HttpHeaders headers = new HttpHeaders();
+                headers.setContentType(MediaType.APPLICATION_JSON);
+                return headers;
+            }
+        };
+    }
+}

8.13 Zuul Timeouts

If you want to configure the socket timeouts and read timeouts for requests proxied through +Zuul there are two options based on your configuration.

If Zuul is using service discovery then you need to configure these timeouts via Ribbon properties, +ribbon.ReadTimeout and ribbon.SocketTimeout.

If you have configured Zuul routes by specifying URLs then you will need to use +zuul.host.connect-timeout-millis and zuul.host.socket-timeout-millis.

8.14 Rewriting Location header

If Zuul is fronting a web application then there may be a need to re-write the Location header when the web application redirects through a http status code of 3XX, otherwise the browser will end up redirecting to the web application’s url instead of the Zuul url. +A LocationRewriteFilter Zuul filter can be configured to re-write the Location header to the Zuul’s url, it also adds back the stripped global and route specific prefixes. The filter can be added the following way via a Spring Configuration file:

import org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilter;
+...
+
+@Configuration
+@EnableZuulProxy
+public class ZuulConfig {
+    @Bean
+    public LocationRewriteFilter locationRewriteFilter() {
+        return new LocationRewriteFilter();
+    }
+}
[Warning]Warning

Use this filter with caution though, the filter acts on the Location header of ALL 3XX response codes which may not be appropriate in all scenarios, say if the user is redirecting to an external URL.

8.15 Zuul Developer Guide

For a general overview of how Zuul works, please see the Zuul Wiki.

8.15.1 The Zuul Servlet

Zuul is implemented as a Servlet. For the general cases, Zuul is embedded into the Spring Dispatch mechanism. This allows Spring MVC to be in control of the routing. In this case, Zuul is configured to buffer requests. If there is a need to go through Zuul without buffering requests (e.g. for large file uploads), the Servlet is also installed outside of the Spring Dispatcher. By default, this is located at /zuul. This path can be changed with the zuul.servlet-path property.

8.15.2 Zuul RequestContext

To pass information between filters, Zuul uses a RequestContext. Its data is held in a ThreadLocal specific to each request. Information about where to route requests, errors and the actual HttpServletRequest and HttpServletResponse are stored there. The RequestContext extends ConcurrentHashMap, so anything can be stored in the context. FilterConstants contains the keys that are used by the filters installed by Spring Cloud Netflix (more on these later).

8.15.3 @EnableZuulProxy vs. @EnableZuulServer

Spring Cloud Netflix installs a number of filters based on which annotation was used to enable Zuul. @EnableZuulProxy is a superset of @EnableZuulServer. In other words, @EnableZuulProxy contains all filters installed by @EnableZuulServer. The additional filters in the "proxy" enable routing functionality. If you want a "blank" Zuul, you should use @EnableZuulServer.

8.15.4 @EnableZuulServer Filters

Creates a SimpleRouteLocator that loads route definitions from Spring Boot configuration files.

The following filters are installed (as normal Spring Beans):

Pre filters:

  • ServletDetectionFilter: Detects if the request is through the Spring Dispatcher. Sets boolean with key FilterConstants.IS_DISPATCHER_SERVLET_REQUEST_KEY.
  • FormBodyWrapperFilter: Parses form data and reencodes it for downstream requests.
  • DebugFilter: if the debug request parameter is set, this filter sets RequestContext.setDebugRouting() and RequestContext.setDebugRequest() to true.

Route filters:

  • SendForwardFilter: This filter forwards requests using the Servlet RequestDispatcher. The forwarding location is stored in the RequestContext attribute FilterConstants.FORWARD_TO_KEY. This is useful for forwarding to endpoints in the current application.

Post filters:

  • SendResponseFilter: Writes responses from proxied requests to the current response.

Error filters:

  • SendErrorFilter: Forwards to /error (by default) if RequestContext.getThrowable() is not null. The default forwarding path (/error) can be changed by setting the error.path property.

8.15.5 @EnableZuulProxy Filters

Creates a DiscoveryClientRouteLocator that loads route definitions from a DiscoveryClient (like Eureka), as well as from properties. A route is created for each serviceId from the DiscoveryClient. As new services are added, the routes will be refreshed.

In addition to the filters described above, the following filters are installed (as normal Spring Beans):

Pre filters:

  • PreDecorationFilter: This filter determines where and how to route based on the supplied RouteLocator. It also sets various proxy-related headers for downstream requests.

Route filters:

  • RibbonRoutingFilter: This filter uses Ribbon, Hystrix and pluggable HTTP clients to send requests. Service ids are found in the RequestContext attribute FilterConstants.SERVICE_ID_KEY. This filter can use different HTTP clients. They are:

    • Apache HttpClient. This is the default client.
    • Squareup OkHttpClient v3. This is enabled by having the com.squareup.okhttp3:okhttp library on the classpath and setting ribbon.okhttp.enabled=true.
    • Netflix Ribbon HTTP client. This is enabled by setting ribbon.restclient.enabled=true. This client has limitations, such as it doesn’t support the PATCH method, but also has built-in retry.
  • SimpleHostRoutingFilter: This filter sends requests to predetermined URLs via an Apache HttpClient. URLs are found in RequestContext.getRouteHost().

8.15.6 Custom Zuul Filter examples

Most of the following "How to Write" examples below are included Sample Zuul Filters project. There are also examples of manipulating the request or response body in that repository.

8.15.7 How to Write a Pre Filter

Pre filters are used to set up data in the RequestContext for use in filters downstream. The main use case is to set information required for route filters.

public class QueryParamPreFilter extends ZuulFilter {
+	@Override
+	public int filterOrder() {
+		return PRE_DECORATION_FILTER_ORDER - 1; // run before PreDecoration
+	}
+
+	@Override
+	public String filterType() {
+		return PRE_TYPE;
+	}
+
+	@Override
+	public boolean shouldFilter() {
+		RequestContext ctx = RequestContext.getCurrentContext();
+		return !ctx.containsKey(FORWARD_TO_KEY) // a filter has already forwarded
+				&& !ctx.containsKey(SERVICE_ID_KEY); // a filter has already determined serviceId
+	}
+    @Override
+    public Object run() {
+        RequestContext ctx = RequestContext.getCurrentContext();
+		HttpServletRequest request = ctx.getRequest();
+		if (request.getParameter("foo") != null) {
+		    // put the serviceId in `RequestContext`
+    		ctx.put(SERVICE_ID_KEY, request.getParameter("foo"));
+    	}
+        return null;
+    }
+}

The filter above populates SERVICE_ID_KEY from the foo request parameter. In reality, it’s not a good idea to do that kind of direct mapping, but the service id should be looked up from the value of foo instead.

Now that SERVICE_ID_KEY is populated, PreDecorationFilter won’t run and RibbonRoutingFilter will. If you wanted to route to a full URL instead, call ctx.setRouteHost(url) instead.

To modify the path that routing filters will forward to, set the REQUEST_URI_KEY.

8.15.8 How to Write a Route Filter

Route filters are run after pre filters and are used to make requests to other services. Much of the work here is to translate request and response data to and from the client required model.

public class OkHttpRoutingFilter extends ZuulFilter {
+	@Autowired
+	private ProxyRequestHelper helper;
+
+	@Override
+	public String filterType() {
+		return ROUTE_TYPE;
+	}
+
+	@Override
+	public int filterOrder() {
+		return SIMPLE_HOST_ROUTING_FILTER_ORDER - 1;
+	}
+
+	@Override
+	public boolean shouldFilter() {
+		return RequestContext.getCurrentContext().getRouteHost() != null
+				&& RequestContext.getCurrentContext().sendZuulResponse();
+	}
+
+    @Override
+    public Object run() {
+		OkHttpClient httpClient = new OkHttpClient.Builder()
+				// customize
+				.build();
+
+		RequestContext context = RequestContext.getCurrentContext();
+		HttpServletRequest request = context.getRequest();
+
+		String method = request.getMethod();
+
+		String uri = this.helper.buildZuulRequestURI(request);
+
+		Headers.Builder headers = new Headers.Builder();
+		Enumeration<String> headerNames = request.getHeaderNames();
+		while (headerNames.hasMoreElements()) {
+			String name = headerNames.nextElement();
+			Enumeration<String> values = request.getHeaders(name);
+
+			while (values.hasMoreElements()) {
+				String value = values.nextElement();
+				headers.add(name, value);
+			}
+		}
+
+		InputStream inputStream = request.getInputStream();
+
+		RequestBody requestBody = null;
+		if (inputStream != null && HttpMethod.permitsRequestBody(method)) {
+			MediaType mediaType = null;
+			if (headers.get("Content-Type") != null) {
+				mediaType = MediaType.parse(headers.get("Content-Type"));
+			}
+			requestBody = RequestBody.create(mediaType, StreamUtils.copyToByteArray(inputStream));
+		}
+
+		Request.Builder builder = new Request.Builder()
+				.headers(headers.build())
+				.url(uri)
+				.method(method, requestBody);
+
+		Response response = httpClient.newCall(builder.build()).execute();
+
+		LinkedMultiValueMap<String, String> responseHeaders = new LinkedMultiValueMap<>();
+
+		for (Map.Entry<String, List<String>> entry : response.headers().toMultimap().entrySet()) {
+			responseHeaders.put(entry.getKey(), entry.getValue());
+		}
+
+		this.helper.setResponse(response.code(), response.body().byteStream(),
+				responseHeaders);
+		context.setRouteHost(null); // prevent SimpleHostRoutingFilter from running
+		return null;
+    }
+}

The above filter translates Servlet request information into OkHttp3 request information, executes an HTTP request, then translates OkHttp3 reponse information to the Servlet response. WARNING: this filter might have bugs and not function correctly.

8.15.9 How to Write a Post Filter

Post filters typically manipulate the response. In the filter below, we add a random UUID as the X-Foo header. Other manipulations, such as transforming the response body, are much more complex and compute-intensive.

public class AddResponseHeaderFilter extends ZuulFilter {
+	@Override
+	public String filterType() {
+		return POST_TYPE;
+	}
+
+	@Override
+	public int filterOrder() {
+		return SEND_RESPONSE_FILTER_ORDER - 1;
+	}
+
+	@Override
+	public boolean shouldFilter() {
+		return true;
+	}
+
+	@Override
+	public Object run() {
+		RequestContext context = RequestContext.getCurrentContext();
+    	HttpServletResponse servletResponse = context.getResponse();
+		servletResponse.addHeader("X-Foo", UUID.randomUUID().toString());
+		return null;
+	}
+}

8.15.10 How Zuul Errors Work

If an exception is thrown during any portion of the Zuul filter lifecycle, the error filters are executed. The SendErrorFilter is only run if RequestContext.getThrowable() is not null. It then sets specific javax.servlet.error.* attributes in the request and forwards the request to the Spring Boot error page.

8.15.11 Zuul Eager Application Context Loading

Zuul internally uses Ribbon for calling the remote url’s and Ribbon clients are by default lazily loaded up by Spring Cloud on first call. +This behavior can be changed for Zuul using the following configuration and will result in the child Ribbon related Application contexts being eagerly loaded up at application startup time.

application.yml.  +

zuul:
+  ribbon:
+    eager-load:
+      enabled: true

+

\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi__service_discovery_eureka_clients.html b/spring-cloud-netflix/2.0.0.M7/multi/multi__service_discovery_eureka_clients.html new file mode 100644 index 00000000..782cfd06 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi__service_discovery_eureka_clients.html @@ -0,0 +1,189 @@ + + + 1. Service Discovery: Eureka Clients

1. Service Discovery: Eureka Clients

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. Eureka is the Netflix Service Discovery Server and Client. The server can be configured and deployed to be highly available, with each server replicating state about the registered services to the others.

1.1 How to Include Eureka Client

To include Eureka Client in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-eureka-client. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train.

1.2 Registering with Eureka

When a client registers with Eureka, it provides meta-data about itself +such as host and port, health indicator URL, home page etc. Eureka +receives heartbeat messages from each instance belonging to a service. +If the heartbeat fails over a configurable timetable, the instance is +normally removed from the registry.

Example eureka client:

@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). By having spring-cloud-starter-netflix-eureka-client + on the classpath your application will automatically register with the Eureka Server. Configuration is required to +locate the Eureka server. Example:

application.yml.  +

eureka:
+  client:
+    serviceUrl:
+      defaultZone: http://localhost:8761/eureka/

+

where "defaultZone" is a magic string fallback value that provides the +service URL for any client that doesn’t express a preference +(i.e. it’s a useful default).

The default application name (service ID), virtual host and non-secure +port, taken from the Environment, are ${spring.application.name}, +${spring.application.name} and ${server.port} respectively.

Having spring-cloud-starter-netflix-eureka-client on the classpath +makes the app into both a Eureka "instance" +(i.e. it registers itself) and a "client" (i.e. it can query the +registry to locate other services). The instance behaviour is driven +by eureka.instance.* configuration keys, but the defaults will be +fine if you ensure that your application has a +spring.application.name (this is the default for the Eureka service +ID, or VIP).

See EurekaInstanceConfigBean and EurekaClientConfigBean for more details of the configurable options.

To disable the Eureka Discovery Client you can set eureka.client.enabled to false.

1.3 Authenticating with the Eureka Server

HTTP basic authentication will be automatically added to your eureka +client if one of the eureka.client.serviceUrl.defaultZone URLs has +credentials embedded in it (curl style, like +http://user:password@localhost:8761/eureka). For more complex needs +you can create a @Bean of type DiscoveryClientOptionalArgs and +inject ClientFilter instances into it, all of which will be applied +to the calls from the client to the server.

[Note]Note

Because of a limitation in Eureka it isn’t possible to support +per-server basic auth credentials, so only the first set that are +found will be used.

1.4 Status Page and Health Indicator

The status page and health indicators for a Eureka instance default to +"/info" and "/health" respectively, which are the default locations of +useful endpoints in a Spring Boot Actuator application. You need to +change these, 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.contextPath=/admin). Example:

application.yml.  +

eureka:
+  instance:
+    statusPageUrlPath: ${management.context-path}/info
+    healthCheckUrlPath: ${management.context-path}/health

+

These links show up in the metadata that is consumed by clients, and +used in some scenarios to decide whether to send requests to your +application, so it’s helpful if they are accurate.

1.5 Registering a Secure Application

If your app wants to be contacted over HTTPS you can set two flags in +the EurekaInstanceConfig, viz +eureka.instance.[nonSecurePortEnabled,securePortEnabled]=[false,true] +respectively. This will make Eureka publish instance information +showing an explicit preference for secure communication. The Spring +Cloud DiscoveryClient will always return a URI starting with https for a +service configured this way, and the Eureka (native) instance +information will have a secure health check URL.

Because of the way +Eureka works internally, it will still publish a non-secure URL for +status and home page unless you also override those explicitly. +You can use placeholders to configure the eureka instance urls, +e.g.

application.yml.  +

eureka:
+  instance:
+    statusPageUrl: https://${eureka.hostname}/info
+    healthCheckUrl: https://${eureka.hostname}/health
+    homePageUrl: https://${eureka.hostname}/

+

(Note that ${eureka.hostname} is a native placeholder only available +in later versions of Eureka. You could achieve the same thing with +Spring placeholders as well, e.g. using ${eureka.instance.hostName}.)

[Note]Note

If your app is running behind a proxy, and the SSL termination +is in the proxy (e.g. if you run in Cloud Foundry or other platforms +as a service) then you will need to ensure that the proxy "forwarded" +headers are intercepted and handled by the application. An embedded +Tomcat container in a Spring Boot app does this automatically if it +has explicit configuration for the 'X-Forwarded-\*` headers. A sign +that you got this wrong will be that the links rendered by your app to +itself will be wrong (the wrong host, port or protocol).

1.6 Eureka’s Health Checks

By default, Eureka uses the client heartbeat to determine if a client is up. +Unless specified otherwise the Discovery Client will not propagate the +current health check status of the application per the Spring Boot Actuator. Which means +that after successful registration Eureka will always announce that the +application is in 'UP' state. This behaviour can be altered by enabling +Eureka health checks, which results in propagating application status +to Eureka. As a consequence every other application won’t be sending +traffic to application in state other then 'UP'.

application.yml.  +

eureka:
+  client:
+    healthcheck:
+      enabled: true

+

[Warning]Warning

eureka.client.healthcheck.enabled=true should only be set in application.yml. Setting the value in bootstrap.yml will cause undesirable side effects like registering in eureka with an UNKNOWN status.

If you require more control over the health checks, you may consider +implementing your own com.netflix.appinfo.HealthCheckHandler.

1.7 Eureka Metadata for Instances and Clients

It’s worth spending a bit of time understanding how the Eureka metadata works, so you can use it in a way that makes sense in your platform. There is standard metadata for things like hostname, IP address, port numbers, status page and health check. These are published in the service registry and used by clients to contact the services in a straightforward way. Additional metadata can be added to the instance registration in the eureka.instance.metadataMap, and this will be accessible in the remote clients, but in general will not change the behaviour of the client, unless it is made aware of the meaning of the metadata. There are a couple of special cases described below where Spring Cloud already assigns meaning to the metadata map.

1.7.1 Using Eureka on Cloudfoundry

Cloudfoundry has a global router so that all instances of the same app have the same hostname (it’s the same in other PaaS solutions with a similar architecture). This isn’t necessarily a barrier to using Eureka, but if you use the router (recommended, or even mandatory depending on the way your platform was set up), you need to explicitly set the hostname and port numbers (secure or non-secure) so that they use the router. You might also want to use instance metadata so you can distinguish between the instances on the client (e.g. in a custom load balancer). By default, the eureka.instance.instanceId is vcap.application.instance_id. For example:

application.yml.  +

eureka:
+  instance:
+    hostname: ${vcap.application.uris[0]}
+    nonSecurePort: 80

+

Depending on the way the security rules are set up in your Cloudfoundry instance, you might be able to register and use the IP address of the host VM for direct service-to-service calls. This feature is not (yet) available on Pivotal Web Services (PWS).

1.7.2 Using Eureka on AWS

If the application is planned to be deployed to an AWS cloud, then the Eureka instance will have to be configured to be AWS aware and this can be done by customizing the EurekaInstanceConfigBean the following way:

@Bean
+@Profile("!default")
+public EurekaInstanceConfigBean eurekaInstanceConfig(InetUtils inetUtils) {
+  EurekaInstanceConfigBean b = new EurekaInstanceConfigBean(inetUtils);
+  AmazonInfo info = AmazonInfo.Builder.newBuilder().autoBuild("eureka");
+  b.setDataCenterInfo(info);
+  return b;
+}

1.7.3 Changing the Eureka Instance ID

A vanilla Netflix Eureka instance is registered with an ID that is equal to its host name (i.e. only one service per host). Spring Cloud Eureka provides a sensible default that looks like this: ${spring.cloud.client.hostname}:${spring.application.name}:${spring.application.instance_id:${server.port}}}. For example myhost:myappname:8080.

Using Spring Cloud you can override this by providing a unique identifier in eureka.instance.instanceId. For example:

application.yml.  +

eureka:
+  instance:
+    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.

1.8 Using the EurekaClient

Once you have an app that is a discovery client you can use it to +discover service instances from the Eureka Server. One way to do that is to use the native +com.netflix.discovery.EurekaClient (as opposed to the Spring +Cloud DiscoveryClient), e.g.

@Autowired
+private EurekaClient discoveryClient;
+
+public String serviceUrl() {
+    InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
+    return instance.getHomePageUrl();
+}
[Tip]Tip

Don’t use the EurekaClient in @PostConstruct method or in a +@Scheduled method (or anywhere where the ApplicationContext might +not be started yet). It is initialized in a SmartLifecycle (with +phase=0) so the earliest you can rely on it being available is in +another SmartLifecycle with higher phase.

1.8.1 EurekaClient without Jersey

By default, EurekaClient uses Jersey for HTTP communication. If you wish +to avoid dependencies from Jersey, you can exclude it from your dependencies. +Spring Cloud will auto configure a transport client based on Spring +RestTemplate.

<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
+    <exclusions>
+        <exclusion>
+            <groupId>com.sun.jersey</groupId>
+            <artifactId>jersey-client</artifactId>
+        </exclusion>
+        <exclusion>
+            <groupId>com.sun.jersey</groupId>
+            <artifactId>jersey-core</artifactId>
+        </exclusion>
+        <exclusion>
+            <groupId>com.sun.jersey.contribs</groupId>
+            <artifactId>jersey-apache-client4</artifactId>
+        </exclusion>
+    </exclusions>
+</dependency>

1.9 Alternatives to the native Netflix EurekaClient

You don’t have to use the raw Netflix EurekaClient and usually it +is more convenient to use it behind a wrapper of some sort. Spring +Cloud has support for Feign (a REST client +builder) and also Spring RestTemplate using +the logical Eureka service identifiers (VIPs) instead of physical +URLs. To configure Ribbon with a fixed list of physical servers you +can simply set <client>.ribbon.listOfServers to a comma-separated +list of physical addresses (or hostnames), where <client> is the ID +of the client.

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;
+}

1.10 Why is it so Slow to Register a Service?

Being an instance also involves a periodic heartbeat to the registry +(via the client’s serviceUrl) with default duration 30 seconds. A +service is not available for discovery by clients until the instance, +the server and the client all have the same metadata in their local +cache (so it could take 3 heartbeats). You can change the period using +eureka.instance.leaseRenewalIntervalInSeconds and this will speed up +the process of getting clients connected to other services. In +production it’s probably better to stick with the default because +there are some computations internally in the server that make +assumptions about the lease renewal period.

1.11 Zones

If you have deployed Eureka clients to multiple zones than you may prefer that +those clients leverage services within the same zone before trying services +in another zone. To do this you need to configure your Eureka clients correctly.

First, you need to make sure you have Eureka servers deployed to each zone and that +they are peers of each other. See the section on zones and regions +for more information.

Next you need to tell Eureka which zone your service is in. You can do this using +the metadataMap property. For example if service 1 is deployed to both zone 1 +and zone 2 you would need to set the following Eureka properties in service 1

Service 1 in Zone 1

eureka.instance.metadataMap.zone = zone1
+eureka.client.preferSameZoneEureka = true

Service 1 in Zone 2

eureka.instance.metadataMap.zone = zone2
+eureka.client.preferSameZoneEureka = true
\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi_netflix-metrics-atlas.html b/spring-cloud-netflix/2.0.0.M7/multi/multi_netflix-metrics-atlas.html new file mode 100644 index 00000000..6aad4321 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi_netflix-metrics-atlas.html @@ -0,0 +1,4 @@ + + + 10. Metrics Backend: Atlas

10. Metrics Backend: Atlas

Atlas was developed by Netflix to manage dimensional time series data for near real-time operational insight. Atlas features in-memory data storage, allowing it to gather and report very large numbers of metrics, very quickly.

Atlas captures operational intelligence. Whereas business intelligence is data gathered for analyzing trends over time, operational intelligence provides a picture of what is currently happening within a system.

Spring Cloud provides a spring-cloud-starter-netflix-atlas that has all the dependencies you need. Then just annotate your Spring Boot application with @EnableAtlas and provide a location for your running Atlas server with the netflix.atlas.uri property.

10.1 Using Atlas

To bootstrap a in-memory standalone Atlas instance:

$ curl -LO https://github.com/Netflix/atlas/releases/download/v1.4.2/atlas-1.4.2-standalone.jar
+$ java -jar atlas-1.4.2-standalone.jar
[Tip]Tip

An Atlas standalone node running on an r3.2xlarge (61GB RAM) can handle roughly 2 million metrics per minute for a given 6 hour window.

Once running and you have collected a handful of metrics, verify that your setup is correct by listing tags on the Atlas server:

$ curl http://ATLAS/api/v1/tags
[Tip]Tip

After executing several requests against your service, you can gather some very basic information on the request latency of every request by pasting the following url in your browser: http://ATLAS/api/v1/graph?q=name,rest,:eq,:avg

The Atlas wiki contains a compilation of sample queries for various scenarios.

Make sure to check out the alerting philosophy and docs on using double exponential smoothing to generate dynamic alert thresholds.

\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi_pr01.html b/spring-cloud-netflix/2.0.0.M7/multi/multi_pr01.html new file mode 100644 index 00000000..e5fbf5ed --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi_pr01.html @@ -0,0 +1,8 @@ + + +

2.0.0.M7

This project provides Netflix OSS integrations for Spring Boot apps through autoconfiguration +and binding to the Spring Environment and other Spring programming model idioms. With a few +simple annotations you can quickly enable and configure the common patterns inside your +application and build large distributed systems with battle-tested Netflix components. The +patterns provided include Service Discovery (Eureka), Circuit Breaker (Hystrix), +Intelligent Routing (Zuul) and Client Side Load Balancing (Ribbon).

\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi_retrying-failed-requests.html b/spring-cloud-netflix/2.0.0.M7/multi/multi_retrying-failed-requests.html new file mode 100644 index 00000000..d0089b29 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi_retrying-failed-requests.html @@ -0,0 +1,34 @@ + + + 11. Retrying Failed Requests

11. Retrying Failed Requests

Spring Cloud Netflix offers a variety of ways to make HTTP requests. You can use a load balanced +RestTemplate, Ribbon, or Feign. No matter how you choose to your HTTP requests, there is always +a chance the request may fail. When a request fails you may want to have the request retried +automatically. To accomplish this when using Sping Cloud Netflix you need to include +Spring Retry on your application’s classpath. +When Spring Retry is present load balanced RestTemplates, Feign, and Zuul will automatically +retry any failed requests (assuming you configuration allows it to).

11.1 BackOff Policies

By default no backoff policy is used when retrying requests. If you would like to configure +a backoff policy you will need to create a bean of type LoadBalancedBackOffPolicyFactory +which will be used to create a BackOffPolicy for a given service.

@Configuration
+public class MyConfiguration {
+    @Bean
+    LoadBalancedBackOffPolicyFactory backOffPolciyFactory() {
+        return new LoadBalancedBackOffPolicyFactory() {
+            @Override
+            public BackOffPolicy createBackOffPolicy(String service) {
+                return new ExponentialBackOffPolicy();
+            }
+        };
+    }
+}

11.2 Configuration

Anytime Ribbon is used with Spring Retry you can control the retry functionality by configuring +certain Ribbon properties. The properties you can use are +client.ribbon.MaxAutoRetries, client.ribbon.MaxAutoRetriesNextServer, and +client.ribbon.OkToRetryOnAllOperations. See the Ribbon documentation +for a description of what there properties do.

[Warning]Warning

Enabling client.ribbon.OkToRetryOnAllOperations includes retring POST requests wich can have a impact +on the server’s resources due to the buffering of the request’s body.

In addition you may want to retry requests when certain status codes are returned in the +response. You can list the response codes you would like the Ribbon client to retry using the + property clientName.ribbon.retryableStatusCodes. For example

clientName:
+  ribbon:
+    retryableStatusCodes: 404,502

You can also create a bean of type LoadBalancedRetryPolicy and implement the retryableStatusCode +method to determine whether you want to retry a request given the status code.

11.2.1 Zuul

You can turn off Zuul’s retry functionality by setting zuul.retryable to false. You +can also disable retry functionality on route by route basis by setting +zuul.routes.routename.retryable to false.

\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi_spring-cloud-eureka-server.html b/spring-cloud-netflix/2.0.0.M7/multi/multi_spring-cloud-eureka-server.html new file mode 100644 index 00000000..9a9cb595 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi_spring-cloud-eureka-server.html @@ -0,0 +1,94 @@ + + + 2. Service Discovery: Eureka Server

2. Service Discovery: Eureka Server

2.1 How to Include Eureka Server

To include Eureka Server in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-eureka-server. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train.

2.2 How to Run a Eureka Server

Example eureka server;

@SpringBootApplication
+@EnableEurekaServer
+public class Application {
+
+    public static void main(String[] args) {
+        new SpringApplicationBuilder(Application.class).web(true).run(args);
+    }
+
+}

The server has a home page with a UI, and HTTP API endpoints per the +normal Eureka functionality under /eureka/*.

Eureka background reading: see flux capacitor and google group discussion.

[Tip]Tip

Due to Gradle’s dependency resolution rules and the lack of a parent bom feature, simply depending on spring-cloud-starter-netflix-eureka-server can cause failures on application startup. To remedy this the Spring Boot Gradle plugin must be added and the Spring cloud starter parent bom must be imported like so:

build.gradle.  +

buildscript {
+  dependencies {
+    classpath("org.springframework.boot:spring-boot-gradle-plugin:{spring-boot-docs-version}")
+  }
+}
+
+apply plugin: "spring-boot"
+
+dependencyManagement {
+  imports {
+    mavenBom "org.springframework.cloud:spring-cloud-dependencies:{spring-cloud-version}"
+  }
+}

+

2.3 High Availability, Zones and Regions

The Eureka server does not have a backend store, but the service +instances in the registry all have to send heartbeats to keep their +registrations up to date (so this can be done in memory). Clients also +have an in-memory cache of eureka registrations (so they don’t have to +go to the registry for every single request to a service).

By default every Eureka server is also a Eureka client and requires +(at least one) service URL to locate a peer. If you don’t provide it +the service will run and work, but it will shower your logs with a lot +of noise about not being able to register with the peer.

See also below for details of Ribbon +support on the client side for Zones and Regions.

2.4 Standalone Mode

The combination of the two caches (client and server) and the +heartbeats make a standalone Eureka server fairly resilient to +failure, as long as there is some sort of monitor or elastic runtime +keeping it alive (e.g. Cloud Foundry). In standalone mode, you might +prefer to switch off the client side behaviour, so it doesn’t keep +trying and failing to reach its peers. Example:

application.yml (Standalone Eureka Server).  +

server:
+  port: 8761
+
+eureka:
+  instance:
+    hostname: localhost
+  client:
+    registerWithEureka: false
+    fetchRegistry: false
+    serviceUrl:
+      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

+

Notice that the serviceUrl is pointing to the same host as the local +instance.

2.5 Peer Awareness

Eureka can be made even more resilient and available by running +multiple instances and asking them to register with each other. In +fact, this is the default behaviour, so all you need to do to make it +work is add a valid serviceUrl to a peer, e.g.

application.yml (Two Peer Aware Eureka Servers).  +

---
+spring:
+  profiles: peer1
+eureka:
+  instance:
+    hostname: peer1
+  client:
+    serviceUrl:
+      defaultZone: http://peer2/eureka/
+
+---
+spring:
+  profiles: peer2
+eureka:
+  instance:
+    hostname: peer2
+  client:
+    serviceUrl:
+      defaultZone: http://peer1/eureka/

+

In this example we have a YAML file that can be used to run the same +server on 2 hosts (peer1 and peer2), by running it in different +Spring profiles. You could use this configuration to test the peer +awareness on a single host (there’s not much value in doing that in +production) by manipulating /etc/hosts to resolve the host names. In +fact, the eureka.instance.hostname is not needed if you are running +on a machine that knows its own hostname (it is looked up using +java.net.InetAddress by default).

You can add multiple peers to a system, and as long as they are all +connected to each other by at least one edge, they will synchronize +the registrations amongst themselves. If the peers are physically +separated (inside a data centre or between multiple data centres) then +the system can in principle survive split-brain type failures.

2.6 Prefer IP Address

In some cases, it is preferable for Eureka to advertise the IP Adresses +of services rather than the hostname. Set eureka.instance.preferIpAddress +to true and when the application registers with eureka, it will use its +IP Address rather than its hostname.

[Tip]Tip

If hostname can’t be determined by Java, then IP address is sent to Eureka. +Only explict way of setting hostname is by using eureka.instance.hostname. +You can set your hostname at the run time using environment variable, for +example eureka.instance.hostname=${HOST_NAME}.

\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi_spring-cloud-netflix.html b/spring-cloud-netflix/2.0.0.M7/multi/multi_spring-cloud-netflix.html new file mode 100644 index 00000000..624c2e45 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi_spring-cloud-netflix.html @@ -0,0 +1,3 @@ + + + Spring Cloud Netflix

Spring Cloud Netflix


Table of Contents

1. Service Discovery: Eureka Clients
1.1. How to Include Eureka Client
1.2. Registering with Eureka
1.3. Authenticating with the Eureka Server
1.4. Status Page and Health Indicator
1.5. Registering a Secure Application
1.6. Eureka’s Health Checks
1.7. Eureka Metadata for Instances and Clients
1.7.1. Using Eureka on Cloudfoundry
1.7.2. Using Eureka on AWS
1.7.3. Changing the Eureka Instance ID
1.8. Using the EurekaClient
1.8.1. EurekaClient without Jersey
1.9. Alternatives to the native Netflix EurekaClient
1.10. Why is it so Slow to Register a Service?
1.11. Zones
2. Service Discovery: Eureka Server
2.1. How to Include Eureka Server
2.2. How to Run a Eureka Server
2.3. High Availability, Zones and Regions
2.4. Standalone Mode
2.5. Peer Awareness
2.6. Prefer IP Address
3. Circuit Breaker: Hystrix Clients
3.1. How to Include Hystrix
3.2. Propagating the Security Context or using Spring Scopes
3.3. Health Indicator
3.4. Hystrix Metrics Stream
4. Circuit Breaker: Hystrix Dashboard
5. Hystrix Timeouts And Ribbon Clients
5.1. How to Include Hystrix Dashboard
5.2. Turbine
5.3. Turbine Stream
6. Client Side Load Balancer: Ribbon
6.1. How to Include Ribbon
6.2. Customizing the Ribbon Client
6.3. Customizing default for all Ribbon Clients
6.4. Customizing the Ribbon Client using properties
6.5. Using Ribbon with Eureka
6.6. Example: How to Use Ribbon Without Eureka
6.7. Example: Disable Eureka use in Ribbon
6.8. Using the Ribbon API Directly
6.9. Caching of Ribbon Configuration
6.10. How to Configure Hystrix thread pools
6.11. How to Provide a Key to Ribbon’s IRule
7. External Configuration: Archaius
8. Router and Filter: Zuul
8.1. How to Include Zuul
8.2. Embedded Zuul Reverse Proxy
8.3. Zuul Http Client
8.4. Cookies and Sensitive Headers
8.5. Ignored Headers
8.6. Management Endpoints
8.6.1. Routes Endpoint
8.6.2. Filters Endpoint
8.7. Strangulation Patterns and Local Forwards
8.8. Uploading Files through Zuul
8.9. Query String Encoding
8.10. Plain Embedded Zuul
8.11. Disable Zuul Filters
8.12. Providing Hystrix Fallbacks For Routes
8.13. Zuul Timeouts
8.14. Rewriting Location header
8.15. Zuul Developer Guide
8.15.1. The Zuul Servlet
8.15.2. Zuul RequestContext
8.15.3. @EnableZuulProxy vs. @EnableZuulServer
8.15.4. @EnableZuulServer Filters
8.15.5. @EnableZuulProxy Filters
8.15.6. Custom Zuul Filter examples
8.15.7. How to Write a Pre Filter
8.15.8. How to Write a Route Filter
8.15.9. How to Write a Post Filter
8.15.10. How Zuul Errors Work
8.15.11. Zuul Eager Application Context Loading
9. Polyglot support with Sidecar
10. Metrics Backend: Atlas
10.1. Using Atlas
11. Retrying Failed Requests
11.1. BackOff Policies
11.2. Configuration
11.2.1. Zuul
12. HTTP Clients
\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/multi/multi_spring-cloud-ribbon.html b/spring-cloud-netflix/2.0.0.M7/multi/multi_spring-cloud-ribbon.html new file mode 100644 index 00000000..bad29476 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/multi/multi_spring-cloud-ribbon.html @@ -0,0 +1,163 @@ + + + 6. Client Side Load Balancer: Ribbon

6. Client Side Load Balancer: Ribbon

Ribbon is a client side load balancer which gives you a lot of control +over the behaviour of HTTP and TCP clients. Feign already uses Ribbon, +so if you are using @FeignClient then this section also applies.

A central concept in Ribbon is that of the named client. Each load +balancer is part of an ensemble of components that work together to +contact a remote server on demand, and the ensemble has a name that +you give it as an application developer (e.g. using the @FeignClient +annotation). Spring Cloud creates a new ensemble as an +ApplicationContext on demand for each named client using +RibbonClientConfiguration. This contains (amongst other things) an +ILoadBalancer, a RestClient, and a ServerListFilter.

6.1 How to Include Ribbon

To include Ribbon in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-ribbon. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train.

6.2 Customizing the Ribbon Client

You can configure some bits of a Ribbon client using external +properties in <client>.ribbon.*, which is no different than using +the Netflix APIs natively, except that you can use Spring Boot +configuration files. The native options can +be inspected as static fields in CommonClientConfigKey (part of +ribbon-core).

Spring Cloud also lets you take full control of the client by +declaring additional configuration (on top of the +RibbonClientConfiguration) using @RibbonClient. Example:

@Configuration
+@RibbonClient(name = "foo", configuration = FooConfiguration.class)
+public class TestConfiguration {
+}

In this case the client is composed from the components already in +RibbonClientConfiguration together with any in FooConfiguration +(where the latter generally will override the former).

[Warning]Warning

The FooConfiguration has to be @Configuration but take +care that it is not in a @ComponentScan for the main application +context, otherwise it will be shared by all the @RibbonClients. If +you use @ComponentScan (or @SpringBootApplication) you need to +take steps to avoid it being included (for instance put it in a +separate, non-overlapping package, or specify the packages to scan +explicitly in the @ComponentScan).

Spring Cloud Netflix provides the following beans by default for ribbon +(BeanType beanName: ClassName):

  • IClientConfig ribbonClientConfig: DefaultClientConfigImpl
  • IRule ribbonRule: ZoneAvoidanceRule
  • IPing ribbonPing: DummyPing
  • ServerList<Server> ribbonServerList: ConfigurationBasedServerList
  • ServerListFilter<Server> ribbonServerListFilter: ZonePreferenceServerListFilter
  • ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer
  • ServerListUpdater ribbonServerListUpdater: PollingServerListUpdater

Creating a bean of one of those type and placing it in a @RibbonClient +configuration (such as FooConfiguration above) allows you to override each +one of the beans described. Example:

@Configuration
+protected static class FooConfiguration {
+	@Bean
+	public ZonePreferenceServerListFilter serverListFilter() {
+		ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter();
+		filter.setZone("myTestZone");
+		return filter;
+	}
+
+	@Bean
+	public IPing ribbonPing() {
+		return new PingUrl();
+	}
+}

This replaces the NoOpPing with PingUrl and provides a custom serverListFilter

6.3 Customizing default for all Ribbon Clients

A default configuration can be provided for all Ribbon Clients using the @RibbonClients annotation and registering a default configuration as shown in the following example:

@RibbonClients(defaultConfiguration = DefaultRibbonConfig.class)
+public class RibbonClientDefaultConfigurationTestsConfig {
+
+	public static class BazServiceList extends ConfigurationBasedServerList {
+		public BazServiceList(IClientConfig config) {
+			super.initWithNiwsConfig(config);
+		}
+	}
+}
+
+@Configuration
+class DefaultRibbonConfig {
+
+	@Bean
+	public IRule ribbonRule() {
+		return new BestAvailableRule();
+	}
+
+	@Bean
+	public IPing ribbonPing() {
+		return new PingUrl();
+	}
+
+	@Bean
+	public ServerList<Server> ribbonServerList(IClientConfig config) {
+		return new RibbonClientDefaultConfigurationTestsConfig.BazServiceList(config);
+	}
+
+	@Bean
+	public ServerListSubsetFilter serverListFilter() {
+		ServerListSubsetFilter filter = new ServerListSubsetFilter();
+		return filter;
+	}
+
+}

6.4 Customizing the Ribbon Client using properties

Starting with version 1.2.0, Spring Cloud Netflix now supports customizing Ribbon clients using properties to be compatible with the Ribbon documentation.

This allows you to change behavior at start up time in different environments.

The supported properties are listed below and should be prefixed by <clientName>.ribbon.:

  • NFLoadBalancerClassName: should implement ILoadBalancer
  • NFLoadBalancerRuleClassName: should implement IRule
  • NFLoadBalancerPingClassName: should implement IPing
  • NIWSServerListClassName: should implement ServerList
  • NIWSServerListFilterClassName should implement ServerListFilter
[Note]Note

Classes defined in these properties have precedence over beans defined using @RibbonClient(configuration=MyRibbonConfig.class) and the defaults provided by Spring Cloud Netflix.

To set the IRule for a service name users you could set the following:

application.yml.  +

users:
+  ribbon:
+    NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
+    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule

+

See the Ribbon documentation for implementations provided by Ribbon.

6.5 Using Ribbon with Eureka

When Eureka is used in conjunction with Ribbon (i.e., both are on the classpath) the ribbonServerList +is overridden with an extension of DiscoveryEnabledNIWSServerList +which populates the list of servers from Eureka. It also replaces the +IPing interface with NIWSDiscoveryPing which delegates to Eureka +to determine if a server is up. The ServerList that is installed by +default is a DomainExtractingServerList and the purpose of this is +to make physical metadata available to the load balancer without using +AWS AMI metadata (which is what Netflix relies on). By default the +server list will be constructed with "zone" information as provided in +the instance metadata (so on the remote clients set +eureka.instance.metadataMap.zone), and if that is missing it can use +the domain name from the server hostname as a proxy for zone (if the +flag approximateZoneFromHostname is set). Once the zone information +is available it can be used in a ServerListFilter. By default it +will be used to locate a server in the same zone as the client because +the default is a ZonePreferenceServerListFilter. The zone of the +client is determined the same way as the remote instances by default, +i.e. via eureka.instance.metadataMap.zone.

[Note]Note

The orthodox "archaius" way to set the client zone is via a +configuration property called "@zone", and Spring Cloud will use that +in preference to all other settings if it is available (note that the +key will have to be quoted in YAML configuration).

[Note]Note

If there is no other source of zone data then a guess is made +based on the client configuration (as opposed to the instance +configuration). We take eureka.client.availabilityZones, which is a +map from region name to a list of zones, and pull out the first zone +for the instance’s own region (i.e. the eureka.client.region, which +defaults to "us-east-1" for comatibility with native Netflix).

6.6 Example: How to Use Ribbon Without Eureka

Eureka is a convenient way to abstract the discovery of remote servers +so you don’t have to hard code their URLs in clients, but if you +prefer not to use it, Ribbon and Feign are still quite +amenable. Suppose you have declared a @RibbonClient for "stores", +and Eureka is not in use (and not even on the classpath). The Ribbon +client defaults to a configured server list, and you can supply the +configuration like this

application.yml.  +

stores:
+  ribbon:
+    listOfServers: example.com,google.com

+

6.7 Example: Disable Eureka use in Ribbon

Setting the property ribbon.eureka.enabled = false will explicitly +disable the use of Eureka in Ribbon.

application.yml.  +

ribbon:
+  eureka:
+   enabled: false

+

6.8 Using the Ribbon API Directly

You can also use the LoadBalancerClient directly. Example:

public class MyClass {
+    @Autowired
+    private LoadBalancerClient loadBalancer;
+
+    public void doStuff() {
+        ServiceInstance instance = loadBalancer.choose("stores");
+        URI storesUri = URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort()));
+        // ... do something with the URI
+    }
+}

6.9 Caching of Ribbon Configuration

Each Ribbon named client has a corresponding child Application Context that Spring Cloud maintains, this application context is lazily loaded up on the first request to the named client. +This lazy loading behavior can be changed to instead eagerly load up these child Application contexts at startup by specifying the names of the Ribbon clients.

application.yml.  +

ribbon:
+  eager-load:
+    enabled: true
+    clients: client1, client2, client3

+

6.10 How to Configure Hystrix thread pools

If you change zuul.ribbonIsolationStrategy to THREAD, the thread isolation strategy for Hystrix will be used for all routes. In this case, the HystrixThreadPoolKey is set to "RibbonCommand" as default. It means that HystrixCommands for all routes will be executed in the same Hystrix thread pool. This behavior can be changed using the following configuration and it will result in HystrixCommands being executed in the Hystrix thread pool for each route.

application.yml.  +

zuul:
+  threadPool:
+    useSeparateThreadPools: true

+

The default HystrixThreadPoolKey in this case is same with service ID for each route. To add a prefix to HystrixThreadPoolKey, set zuul.threadPool.threadPoolKeyPrefix to a value that you want to add. For example:

application.yml.  +

zuul:
+  threadPool:
+    useSeparateThreadPools: true
+    threadPoolKeyPrefix: zuulgw

+

6.11 How to Provide a Key to Ribbon’s IRule

If you need to provide your own IRule implementation to handle a special routing requirement like a canary test, +you probably want to pass some information to the choose method of IRule.

com.netflix.loadbalancer.IRule.java.  +

public interface IRule{
+    public Server choose(Object key);
+         :

+

You can provide some information that will be used to choose a target server by your IRule implementation like +the following:

RequestContext.getCurrentContext()
+              .set(FilterConstants.LOAD_BALANCER_KEY, "canary-test");

If you put any object into the RequestContext with a key FilterConstants.LOAD_BALANCER_KEY, it will +be passed to the choose method of IRule implementation. Above code must be executed before RibbonRoutingFilter +is executed and Zuul’s pre filter is the best place to do that. You can easily access HTTP headers and query parameters +via RequestContext in pre filter, so it can be used to determine LOAD_BALANCER_KEY that will be passed to Ribbon. +If you don’t put any value with LOAD_BALANCER_KEY in RequestContext, null will be passed as a parameter of choose +method.

\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/single/css/highlight.css b/spring-cloud-netflix/2.0.0.M7/single/css/highlight.css new file mode 100644 index 00000000..ffefef72 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/single/css/highlight.css @@ -0,0 +1,35 @@ +/* + code highlight CSS resemblign the Eclipse IDE default color schema + @author Costin Leau +*/ + +.hl-keyword { + color: #7F0055; + font-weight: bold; +} + +.hl-comment { + color: #3F5F5F; + font-style: italic; +} + +.hl-multiline-comment { + color: #3F5FBF; + font-style: italic; +} + +.hl-tag { + color: #3F7F7F; +} + +.hl-attribute { + color: #7F007F; +} + +.hl-value { + color: #2A00FF; +} + +.hl-string { + color: #2A00FF; +} \ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/single/css/manual-multipage.css b/spring-cloud-netflix/2.0.0.M7/single/css/manual-multipage.css new file mode 100644 index 00000000..0c484531 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/single/css/manual-multipage.css @@ -0,0 +1,9 @@ +@IMPORT url("manual.css"); + +body.firstpage { + background: url("../images/background.png") no-repeat center top; +} + +div.part h1 { + border-top: none; +} diff --git a/spring-cloud-netflix/2.0.0.M7/single/css/manual-singlepage.css b/spring-cloud-netflix/2.0.0.M7/single/css/manual-singlepage.css new file mode 100644 index 00000000..4a7fd140 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/single/css/manual-singlepage.css @@ -0,0 +1,6 @@ +@IMPORT url("manual.css"); + +body { + background: url("../images/background.png") no-repeat center top; +} + diff --git a/spring-cloud-netflix/2.0.0.M7/single/css/manual.css b/spring-cloud-netflix/2.0.0.M7/single/css/manual.css new file mode 100644 index 00000000..0ecbe2e8 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/single/css/manual.css @@ -0,0 +1,344 @@ +@IMPORT url("highlight.css"); + +html { + padding: 0pt; + margin: 0pt; +} + +body { + color: #333333; + margin: 15px 30px; + font-family: Helvetica, Arial, Freesans, Clean, Sans-serif; + line-height: 1.6; + -webkit-font-smoothing: antialiased; +} + +code { + font-size: 16px; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +:not(a)>code { + color: #6D180B; +} + +:not(pre)>code { + background-color: #F2F2F2; + border: 1px solid #CCCCCC; + border-radius: 4px; + padding: 1px 3px 0; + text-shadow: none; + white-space: nowrap; +} + +body>*:first-child { + margin-top: 0 !important; +} + +div { + margin: 0pt; +} + +hr { + border: 1px solid #CCCCCC; + background: #CCCCCC; +} + +h1,h2,h3,h4,h5,h6 { + color: #000000; + cursor: text; + font-weight: bold; + margin: 30px 0 10px; + padding: 0; +} + +h1,h2,h3 { + margin: 40px 0 10px; +} + +h1 { + margin: 70px 0 30px; + padding-top: 20px; +} + +div.part h1 { + border-top: 1px dotted #CCCCCC; +} + +h1,h1 code { + font-size: 32px; +} + +h2,h2 code { + font-size: 24px; +} + +h3,h3 code { + font-size: 20px; +} + +h4,h1 code,h5,h5 code,h6,h6 code { + font-size: 18px; +} + +div.book,div.chapter,div.appendix,div.part,div.preface { + min-width: 300px; + max-width: 1200px; + margin: 0 auto; +} + +p.releaseinfo { + font-weight: bold; + margin-bottom: 40px; + margin-top: 40px; +} + +div.authorgroup { + line-height: 1; +} + +p.copyright { + line-height: 1; + margin-bottom: -5px; +} + +.legalnotice p { + font-style: italic; + font-size: 14px; + line-height: 1; +} + +div.titlepage+p,div.titlepage+p { + margin-top: 0; +} + +pre { + line-height: 1.0; + color: black; +} + +a { + color: #4183C4; + text-decoration: none; +} + +p { + margin: 15px 0; + text-align: left; +} + +ul,ol { + padding-left: 30px; +} + +li p { + margin: 0; +} + +div.table { + margin: 1em; + padding: 0.5em; + text-align: center; +} + +div.table table,div.informaltable table { + display: table; + width: 100%; +} + +div.table td { + padding-left: 7px; + padding-right: 7px; +} + +.sidebar { + line-height: 1.4; + padding: 0 20px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; +} + +.sidebar p.title { + color: #6D180B; +} + +pre.programlisting,pre.screen { + font-size: 15px; + padding: 6px 10px; + background-color: #F8F8F8; + border: 1px solid #CCCCCC; + border-radius: 3px 3px 3px 3px; + clear: both; + overflow: auto; + line-height: 1.4; + font-family: Consolas, "Liberation Mono", Courier, monospace; +} + +table { + border-collapse: collapse; + border-spacing: 0; + border: 1px solid #DDDDDD !important; + border-radius: 4px !important; + border-collapse: separate !important; + line-height: 1.6; +} + +table thead { + background: #F5F5F5; +} + +table tr { + border: none; + border-bottom: none; +} + +table th { + font-weight: bold; +} + +table th,table td { + border: none !important; + padding: 6px 13px; +} + +table tr:nth-child(2n) { + background-color: #F8F8F8; +} + +td p { + margin: 0 0 15px 0; +} + +div.table-contents td p { + margin: 0; +} + +div.important *,div.note *,div.tip *,div.warning *,div.navheader *,div.navfooter *,div.calloutlist * + { + border: none !important; + background: none !important; + margin: 0; +} + +div.important p,div.note p,div.tip p,div.warning p { + color: #6F6F6F; + line-height: 1.6; +} + +div.important code,div.note code,div.tip code,div.warning code { + background-color: #F2F2F2 !important; + border: 1px solid #CCCCCC !important; + border-radius: 4px !important; + padding: 1px 3px 0 !important; + text-shadow: none !important; + white-space: nowrap !important; +} + +.note th,.tip th,.warning th { + display: none; +} + +.note tr:first-child td,.tip tr:first-child td,.warning tr:first-child td + { + border-right: 1px solid #CCCCCC !important; + padding-top: 10px; +} + +div.calloutlist p,div.calloutlist td { + padding: 0; + margin: 0; +} + +div.calloutlist>table>tbody>tr>td:first-child { + padding-left: 10px; + width: 30px !important; +} + +div.important,div.note,div.tip,div.warning { + margin-left: 0px !important; + margin-right: 20px !important; + margin-top: 20px; + margin-bottom: 20px; + padding-top: 10px; + padding-bottom: 10px; +} + +div.toc { + line-height: 1.2; +} + +dl,dt { + margin-top: 1px; + margin-bottom: 0; +} + +div.toc>dl>dt { + font-size: 32px; + font-weight: bold; + margin: 30px 0 10px 0; + display: block; +} + +div.toc>dl>dd>dl>dt { + font-size: 24px; + font-weight: bold; + margin: 20px 0 10px 0; + display: block; +} + +div.toc>dl>dd>dl>dd>dl>dt { + font-weight: bold; + font-size: 20px; + margin: 10px 0 0 0; +} + +tbody.footnotes * { + border: none !important; +} + +div.footnote p { + margin: 0; + line-height: 1; +} + +div.footnote p sup { + margin-right: 6px; + vertical-align: middle; +} + +div.navheader { + border-bottom: 1px solid #CCCCCC; +} + +div.navfooter { + border-top: 1px solid #CCCCCC; +} + +.title { + margin-left: -1em; + padding-left: 1em; +} + +.title>a { + position: absolute; + visibility: hidden; + display: block; + font-size: 0.85em; + margin-top: 0.05em; + margin-left: -1em; + vertical-align: text-top; + color: black; +} + +.title>a:before { + content: "\00A7"; +} + +.title:hover>a,.title>a:hover,.title:hover>a:hover { + visibility: visible; +} + +.title:focus>a,.title>a:focus,.title:focus>a:focus { + outline: 0; +} diff --git a/spring-cloud-netflix/2.0.0.M7/single/images/background.png b/spring-cloud-netflix/2.0.0.M7/single/images/background.png new file mode 100644 index 00000000..15dca6fb Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/single/images/background.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/single/images/caution.png b/spring-cloud-netflix/2.0.0.M7/single/images/caution.png new file mode 100644 index 00000000..8a5e4fca Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/single/images/caution.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/single/images/important.png b/spring-cloud-netflix/2.0.0.M7/single/images/important.png new file mode 100644 index 00000000..ec54df65 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/single/images/important.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/single/images/logo.png b/spring-cloud-netflix/2.0.0.M7/single/images/logo.png new file mode 100644 index 00000000..ade2ce6e Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/single/images/logo.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/single/images/note.png b/spring-cloud-netflix/2.0.0.M7/single/images/note.png new file mode 100644 index 00000000..88d997b1 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/single/images/note.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/single/images/sts_exception.png b/spring-cloud-netflix/2.0.0.M7/single/images/sts_exception.png new file mode 100644 index 00000000..8607c38a Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/single/images/sts_exception.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/single/images/tip.png b/spring-cloud-netflix/2.0.0.M7/single/images/tip.png new file mode 100644 index 00000000..6530abb4 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/single/images/tip.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/single/images/warning.png b/spring-cloud-netflix/2.0.0.M7/single/images/warning.png new file mode 100644 index 00000000..0d5b5244 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/single/images/warning.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/single/images/web-selected.png b/spring-cloud-netflix/2.0.0.M7/single/images/web-selected.png new file mode 100644 index 00000000..aa6b2da6 Binary files /dev/null and b/spring-cloud-netflix/2.0.0.M7/single/images/web-selected.png differ diff --git a/spring-cloud-netflix/2.0.0.M7/single/spring-cloud-netflix.html b/spring-cloud-netflix/2.0.0.M7/single/spring-cloud-netflix.html new file mode 100644 index 00000000..7a04bb27 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/single/spring-cloud-netflix.html @@ -0,0 +1,1161 @@ + + + Spring Cloud Netflix

Spring Cloud Netflix


Table of Contents

1. Service Discovery: Eureka Clients
1.1. How to Include Eureka Client
1.2. Registering with Eureka
1.3. Authenticating with the Eureka Server
1.4. Status Page and Health Indicator
1.5. Registering a Secure Application
1.6. Eureka’s Health Checks
1.7. Eureka Metadata for Instances and Clients
1.7.1. Using Eureka on Cloudfoundry
1.7.2. Using Eureka on AWS
1.7.3. Changing the Eureka Instance ID
1.8. Using the EurekaClient
1.8.1. EurekaClient without Jersey
1.9. Alternatives to the native Netflix EurekaClient
1.10. Why is it so Slow to Register a Service?
1.11. Zones
2. Service Discovery: Eureka Server
2.1. How to Include Eureka Server
2.2. How to Run a Eureka Server
2.3. High Availability, Zones and Regions
2.4. Standalone Mode
2.5. Peer Awareness
2.6. Prefer IP Address
3. Circuit Breaker: Hystrix Clients
3.1. How to Include Hystrix
3.2. Propagating the Security Context or using Spring Scopes
3.3. Health Indicator
3.4. Hystrix Metrics Stream
4. Circuit Breaker: Hystrix Dashboard
5. Hystrix Timeouts And Ribbon Clients
5.1. How to Include Hystrix Dashboard
5.2. Turbine
5.3. Turbine Stream
6. Client Side Load Balancer: Ribbon
6.1. How to Include Ribbon
6.2. Customizing the Ribbon Client
6.3. Customizing default for all Ribbon Clients
6.4. Customizing the Ribbon Client using properties
6.5. Using Ribbon with Eureka
6.6. Example: How to Use Ribbon Without Eureka
6.7. Example: Disable Eureka use in Ribbon
6.8. Using the Ribbon API Directly
6.9. Caching of Ribbon Configuration
6.10. How to Configure Hystrix thread pools
6.11. How to Provide a Key to Ribbon’s IRule
7. External Configuration: Archaius
8. Router and Filter: Zuul
8.1. How to Include Zuul
8.2. Embedded Zuul Reverse Proxy
8.3. Zuul Http Client
8.4. Cookies and Sensitive Headers
8.5. Ignored Headers
8.6. Management Endpoints
8.6.1. Routes Endpoint
8.6.2. Filters Endpoint
8.7. Strangulation Patterns and Local Forwards
8.8. Uploading Files through Zuul
8.9. Query String Encoding
8.10. Plain Embedded Zuul
8.11. Disable Zuul Filters
8.12. Providing Hystrix Fallbacks For Routes
8.13. Zuul Timeouts
8.14. Rewriting Location header
8.15. Zuul Developer Guide
8.15.1. The Zuul Servlet
8.15.2. Zuul RequestContext
8.15.3. @EnableZuulProxy vs. @EnableZuulServer
8.15.4. @EnableZuulServer Filters
8.15.5. @EnableZuulProxy Filters
8.15.6. Custom Zuul Filter examples
8.15.7. How to Write a Pre Filter
8.15.8. How to Write a Route Filter
8.15.9. How to Write a Post Filter
8.15.10. How Zuul Errors Work
8.15.11. Zuul Eager Application Context Loading
9. Polyglot support with Sidecar
10. Metrics Backend: Atlas
10.1. Using Atlas
11. Retrying Failed Requests
11.1. BackOff Policies
11.2. Configuration
11.2.1. Zuul
12. HTTP Clients

2.0.0.M7

This project provides Netflix OSS integrations for Spring Boot apps through autoconfiguration +and binding to the Spring Environment and other Spring programming model idioms. With a few +simple annotations you can quickly enable and configure the common patterns inside your +application and build large distributed systems with battle-tested Netflix components. The +patterns provided include Service Discovery (Eureka), Circuit Breaker (Hystrix), +Intelligent Routing (Zuul) and Client Side Load Balancing (Ribbon).

1. Service Discovery: Eureka Clients

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. Eureka is the Netflix Service Discovery Server and Client. The server can be configured and deployed to be highly available, with each server replicating state about the registered services to the others.

1.1 How to Include Eureka Client

To include Eureka Client in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-eureka-client. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train.

1.2 Registering with Eureka

When a client registers with Eureka, it provides meta-data about itself +such as host and port, health indicator URL, home page etc. Eureka +receives heartbeat messages from each instance belonging to a service. +If the heartbeat fails over a configurable timetable, the instance is +normally removed from the registry.

Example eureka client:

@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). By having spring-cloud-starter-netflix-eureka-client + on the classpath your application will automatically register with the Eureka Server. Configuration is required to +locate the Eureka server. Example:

application.yml.  +

eureka:
+  client:
+    serviceUrl:
+      defaultZone: http://localhost:8761/eureka/

+

where "defaultZone" is a magic string fallback value that provides the +service URL for any client that doesn’t express a preference +(i.e. it’s a useful default).

The default application name (service ID), virtual host and non-secure +port, taken from the Environment, are ${spring.application.name}, +${spring.application.name} and ${server.port} respectively.

Having spring-cloud-starter-netflix-eureka-client on the classpath +makes the app into both a Eureka "instance" +(i.e. it registers itself) and a "client" (i.e. it can query the +registry to locate other services). The instance behaviour is driven +by eureka.instance.* configuration keys, but the defaults will be +fine if you ensure that your application has a +spring.application.name (this is the default for the Eureka service +ID, or VIP).

See EurekaInstanceConfigBean and EurekaClientConfigBean for more details of the configurable options.

To disable the Eureka Discovery Client you can set eureka.client.enabled to false.

1.3 Authenticating with the Eureka Server

HTTP basic authentication will be automatically added to your eureka +client if one of the eureka.client.serviceUrl.defaultZone URLs has +credentials embedded in it (curl style, like +http://user:password@localhost:8761/eureka). For more complex needs +you can create a @Bean of type DiscoveryClientOptionalArgs and +inject ClientFilter instances into it, all of which will be applied +to the calls from the client to the server.

[Note]Note

Because of a limitation in Eureka it isn’t possible to support +per-server basic auth credentials, so only the first set that are +found will be used.

1.4 Status Page and Health Indicator

The status page and health indicators for a Eureka instance default to +"/info" and "/health" respectively, which are the default locations of +useful endpoints in a Spring Boot Actuator application. You need to +change these, 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.contextPath=/admin). Example:

application.yml.  +

eureka:
+  instance:
+    statusPageUrlPath: ${management.context-path}/info
+    healthCheckUrlPath: ${management.context-path}/health

+

These links show up in the metadata that is consumed by clients, and +used in some scenarios to decide whether to send requests to your +application, so it’s helpful if they are accurate.

1.5 Registering a Secure Application

If your app wants to be contacted over HTTPS you can set two flags in +the EurekaInstanceConfig, viz +eureka.instance.[nonSecurePortEnabled,securePortEnabled]=[false,true] +respectively. This will make Eureka publish instance information +showing an explicit preference for secure communication. The Spring +Cloud DiscoveryClient will always return a URI starting with https for a +service configured this way, and the Eureka (native) instance +information will have a secure health check URL.

Because of the way +Eureka works internally, it will still publish a non-secure URL for +status and home page unless you also override those explicitly. +You can use placeholders to configure the eureka instance urls, +e.g.

application.yml.  +

eureka:
+  instance:
+    statusPageUrl: https://${eureka.hostname}/info
+    healthCheckUrl: https://${eureka.hostname}/health
+    homePageUrl: https://${eureka.hostname}/

+

(Note that ${eureka.hostname} is a native placeholder only available +in later versions of Eureka. You could achieve the same thing with +Spring placeholders as well, e.g. using ${eureka.instance.hostName}.)

[Note]Note

If your app is running behind a proxy, and the SSL termination +is in the proxy (e.g. if you run in Cloud Foundry or other platforms +as a service) then you will need to ensure that the proxy "forwarded" +headers are intercepted and handled by the application. An embedded +Tomcat container in a Spring Boot app does this automatically if it +has explicit configuration for the 'X-Forwarded-\*` headers. A sign +that you got this wrong will be that the links rendered by your app to +itself will be wrong (the wrong host, port or protocol).

1.6 Eureka’s Health Checks

By default, Eureka uses the client heartbeat to determine if a client is up. +Unless specified otherwise the Discovery Client will not propagate the +current health check status of the application per the Spring Boot Actuator. Which means +that after successful registration Eureka will always announce that the +application is in 'UP' state. This behaviour can be altered by enabling +Eureka health checks, which results in propagating application status +to Eureka. As a consequence every other application won’t be sending +traffic to application in state other then 'UP'.

application.yml.  +

eureka:
+  client:
+    healthcheck:
+      enabled: true

+

[Warning]Warning

eureka.client.healthcheck.enabled=true should only be set in application.yml. Setting the value in bootstrap.yml will cause undesirable side effects like registering in eureka with an UNKNOWN status.

If you require more control over the health checks, you may consider +implementing your own com.netflix.appinfo.HealthCheckHandler.

1.7 Eureka Metadata for Instances and Clients

It’s worth spending a bit of time understanding how the Eureka metadata works, so you can use it in a way that makes sense in your platform. There is standard metadata for things like hostname, IP address, port numbers, status page and health check. These are published in the service registry and used by clients to contact the services in a straightforward way. Additional metadata can be added to the instance registration in the eureka.instance.metadataMap, and this will be accessible in the remote clients, but in general will not change the behaviour of the client, unless it is made aware of the meaning of the metadata. There are a couple of special cases described below where Spring Cloud already assigns meaning to the metadata map.

1.7.1 Using Eureka on Cloudfoundry

Cloudfoundry has a global router so that all instances of the same app have the same hostname (it’s the same in other PaaS solutions with a similar architecture). This isn’t necessarily a barrier to using Eureka, but if you use the router (recommended, or even mandatory depending on the way your platform was set up), you need to explicitly set the hostname and port numbers (secure or non-secure) so that they use the router. You might also want to use instance metadata so you can distinguish between the instances on the client (e.g. in a custom load balancer). By default, the eureka.instance.instanceId is vcap.application.instance_id. For example:

application.yml.  +

eureka:
+  instance:
+    hostname: ${vcap.application.uris[0]}
+    nonSecurePort: 80

+

Depending on the way the security rules are set up in your Cloudfoundry instance, you might be able to register and use the IP address of the host VM for direct service-to-service calls. This feature is not (yet) available on Pivotal Web Services (PWS).

1.7.2 Using Eureka on AWS

If the application is planned to be deployed to an AWS cloud, then the Eureka instance will have to be configured to be AWS aware and this can be done by customizing the EurekaInstanceConfigBean the following way:

@Bean
+@Profile("!default")
+public EurekaInstanceConfigBean eurekaInstanceConfig(InetUtils inetUtils) {
+  EurekaInstanceConfigBean b = new EurekaInstanceConfigBean(inetUtils);
+  AmazonInfo info = AmazonInfo.Builder.newBuilder().autoBuild("eureka");
+  b.setDataCenterInfo(info);
+  return b;
+}

1.7.3 Changing the Eureka Instance ID

A vanilla Netflix Eureka instance is registered with an ID that is equal to its host name (i.e. only one service per host). Spring Cloud Eureka provides a sensible default that looks like this: ${spring.cloud.client.hostname}:${spring.application.name}:${spring.application.instance_id:${server.port}}}. For example myhost:myappname:8080.

Using Spring Cloud you can override this by providing a unique identifier in eureka.instance.instanceId. For example:

application.yml.  +

eureka:
+  instance:
+    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.

1.8 Using the EurekaClient

Once you have an app that is a discovery client you can use it to +discover service instances from the Eureka Server. One way to do that is to use the native +com.netflix.discovery.EurekaClient (as opposed to the Spring +Cloud DiscoveryClient), e.g.

@Autowired
+private EurekaClient discoveryClient;
+
+public String serviceUrl() {
+    InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
+    return instance.getHomePageUrl();
+}
[Tip]Tip

Don’t use the EurekaClient in @PostConstruct method or in a +@Scheduled method (or anywhere where the ApplicationContext might +not be started yet). It is initialized in a SmartLifecycle (with +phase=0) so the earliest you can rely on it being available is in +another SmartLifecycle with higher phase.

1.8.1 EurekaClient without Jersey

By default, EurekaClient uses Jersey for HTTP communication. If you wish +to avoid dependencies from Jersey, you can exclude it from your dependencies. +Spring Cloud will auto configure a transport client based on Spring +RestTemplate.

<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
+    <exclusions>
+        <exclusion>
+            <groupId>com.sun.jersey</groupId>
+            <artifactId>jersey-client</artifactId>
+        </exclusion>
+        <exclusion>
+            <groupId>com.sun.jersey</groupId>
+            <artifactId>jersey-core</artifactId>
+        </exclusion>
+        <exclusion>
+            <groupId>com.sun.jersey.contribs</groupId>
+            <artifactId>jersey-apache-client4</artifactId>
+        </exclusion>
+    </exclusions>
+</dependency>

1.9 Alternatives to the native Netflix EurekaClient

You don’t have to use the raw Netflix EurekaClient and usually it +is more convenient to use it behind a wrapper of some sort. Spring +Cloud has support for Feign (a REST client +builder) and also Spring RestTemplate using +the logical Eureka service identifiers (VIPs) instead of physical +URLs. To configure Ribbon with a fixed list of physical servers you +can simply set <client>.ribbon.listOfServers to a comma-separated +list of physical addresses (or hostnames), where <client> is the ID +of the client.

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;
+}

1.10 Why is it so Slow to Register a Service?

Being an instance also involves a periodic heartbeat to the registry +(via the client’s serviceUrl) with default duration 30 seconds. A +service is not available for discovery by clients until the instance, +the server and the client all have the same metadata in their local +cache (so it could take 3 heartbeats). You can change the period using +eureka.instance.leaseRenewalIntervalInSeconds and this will speed up +the process of getting clients connected to other services. In +production it’s probably better to stick with the default because +there are some computations internally in the server that make +assumptions about the lease renewal period.

1.11 Zones

If you have deployed Eureka clients to multiple zones than you may prefer that +those clients leverage services within the same zone before trying services +in another zone. To do this you need to configure your Eureka clients correctly.

First, you need to make sure you have Eureka servers deployed to each zone and that +they are peers of each other. See the section on zones and regions +for more information.

Next you need to tell Eureka which zone your service is in. You can do this using +the metadataMap property. For example if service 1 is deployed to both zone 1 +and zone 2 you would need to set the following Eureka properties in service 1

Service 1 in Zone 1

eureka.instance.metadataMap.zone = zone1
+eureka.client.preferSameZoneEureka = true

Service 1 in Zone 2

eureka.instance.metadataMap.zone = zone2
+eureka.client.preferSameZoneEureka = true

2. Service Discovery: Eureka Server

2.1 How to Include Eureka Server

To include Eureka Server in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-eureka-server. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train.

2.2 How to Run a Eureka Server

Example eureka server;

@SpringBootApplication
+@EnableEurekaServer
+public class Application {
+
+    public static void main(String[] args) {
+        new SpringApplicationBuilder(Application.class).web(true).run(args);
+    }
+
+}

The server has a home page with a UI, and HTTP API endpoints per the +normal Eureka functionality under /eureka/*.

Eureka background reading: see flux capacitor and google group discussion.

[Tip]Tip

Due to Gradle’s dependency resolution rules and the lack of a parent bom feature, simply depending on spring-cloud-starter-netflix-eureka-server can cause failures on application startup. To remedy this the Spring Boot Gradle plugin must be added and the Spring cloud starter parent bom must be imported like so:

build.gradle.  +

buildscript {
+  dependencies {
+    classpath("org.springframework.boot:spring-boot-gradle-plugin:{spring-boot-docs-version}")
+  }
+}
+
+apply plugin: "spring-boot"
+
+dependencyManagement {
+  imports {
+    mavenBom "org.springframework.cloud:spring-cloud-dependencies:{spring-cloud-version}"
+  }
+}

+

2.3 High Availability, Zones and Regions

The Eureka server does not have a backend store, but the service +instances in the registry all have to send heartbeats to keep their +registrations up to date (so this can be done in memory). Clients also +have an in-memory cache of eureka registrations (so they don’t have to +go to the registry for every single request to a service).

By default every Eureka server is also a Eureka client and requires +(at least one) service URL to locate a peer. If you don’t provide it +the service will run and work, but it will shower your logs with a lot +of noise about not being able to register with the peer.

See also below for details of Ribbon +support on the client side for Zones and Regions.

2.4 Standalone Mode

The combination of the two caches (client and server) and the +heartbeats make a standalone Eureka server fairly resilient to +failure, as long as there is some sort of monitor or elastic runtime +keeping it alive (e.g. Cloud Foundry). In standalone mode, you might +prefer to switch off the client side behaviour, so it doesn’t keep +trying and failing to reach its peers. Example:

application.yml (Standalone Eureka Server).  +

server:
+  port: 8761
+
+eureka:
+  instance:
+    hostname: localhost
+  client:
+    registerWithEureka: false
+    fetchRegistry: false
+    serviceUrl:
+      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

+

Notice that the serviceUrl is pointing to the same host as the local +instance.

2.5 Peer Awareness

Eureka can be made even more resilient and available by running +multiple instances and asking them to register with each other. In +fact, this is the default behaviour, so all you need to do to make it +work is add a valid serviceUrl to a peer, e.g.

application.yml (Two Peer Aware Eureka Servers).  +

---
+spring:
+  profiles: peer1
+eureka:
+  instance:
+    hostname: peer1
+  client:
+    serviceUrl:
+      defaultZone: http://peer2/eureka/
+
+---
+spring:
+  profiles: peer2
+eureka:
+  instance:
+    hostname: peer2
+  client:
+    serviceUrl:
+      defaultZone: http://peer1/eureka/

+

In this example we have a YAML file that can be used to run the same +server on 2 hosts (peer1 and peer2), by running it in different +Spring profiles. You could use this configuration to test the peer +awareness on a single host (there’s not much value in doing that in +production) by manipulating /etc/hosts to resolve the host names. In +fact, the eureka.instance.hostname is not needed if you are running +on a machine that knows its own hostname (it is looked up using +java.net.InetAddress by default).

You can add multiple peers to a system, and as long as they are all +connected to each other by at least one edge, they will synchronize +the registrations amongst themselves. If the peers are physically +separated (inside a data centre or between multiple data centres) then +the system can in principle survive split-brain type failures.

2.6 Prefer IP Address

In some cases, it is preferable for Eureka to advertise the IP Adresses +of services rather than the hostname. Set eureka.instance.preferIpAddress +to true and when the application registers with eureka, it will use its +IP Address rather than its hostname.

[Tip]Tip

If hostname can’t be determined by Java, then IP address is sent to Eureka. +Only explict way of setting hostname is by using eureka.instance.hostname. +You can set your hostname at the run time using environment variable, for +example eureka.instance.hostname=${HOST_NAME}.

3. Circuit Breaker: Hystrix Clients

Netflix has created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture it is common to have multiple layers of service calls.

Figure 3.1. Microservice Graph

Hystrix

A service failure in the lower level of services can cause cascading failure all the way up to the user. When calls to a particular service is greater than circuitBreaker.requestVolumeThreshold (default: 20 requests) and failue percentage is greater than circuitBreaker.errorThresholdPercentage (default: >50%) in a rolling window defined by metrics.rollingStats.timeInMilliseconds (default: 10 seconds), the circuit opens and the call is not made. In cases of error and an open circuit a fallback can be provided by the developer.

Figure 3.2. Hystrix fallback prevents cascading failures

HystrixFallback

Having an open circuit stops cascading failures and allows overwhelmed or failing services time to heal. The fallback can be another Hystrix protected call, static data or a sane empty value. Fallbacks may be chained so the first fallback makes some other business call which in turn falls back to static data.

3.1 How to Include Hystrix

To include Hystrix in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-hystrix. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train.

Example boot app:

@SpringBootApplication
+@EnableCircuitBreaker
+public class Application {
+
+    public static void main(String[] args) {
+        new SpringApplicationBuilder(Application.class).web(true).run(args);
+    }
+
+}
+
+@Component
+public class StoreIntegration {
+
+    @HystrixCommand(fallbackMethod = "defaultStores")
+    public Object getStores(Map<String, Object> parameters) {
+        //do stuff that might fail
+    }
+
+    public Object defaultStores(Map<String, Object> parameters) {
+        return /* something useful */;
+    }
+}

The @HystrixCommand is provided by a Netflix contrib library called +"javanica". +Spring Cloud automatically wraps Spring beans with that +annotation in a proxy that is connected to the Hystrix circuit +breaker. The circuit breaker calculates when to open and close the +circuit, and what to do in case of a failure.

To configure the @HystrixCommand you can use the commandProperties +attribute with a list of @HystrixProperty annotations. See +here +for more details. See the Hystrix wiki +for details on the properties available.

3.2 Propagating the Security Context or using Spring Scopes

If you want some thread local context to propagate into a @HystrixCommand the default declaration will not work because it executes the command in a thread pool (in case of timeouts). You can switch Hystrix to use the same thread as the caller using some configuration, or directly in the annotation, by asking it to use a different "Isolation Strategy". For example:

@HystrixCommand(fallbackMethod = "stubMyService",
+    commandProperties = {
+      @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
+    }
+)
+...

The same thing applies if you are using @SessionScope or @RequestScope. You will know when you need to do this because of a runtime exception that says it can’t find the scoped context.

You also have the option to set the hystrix.shareSecurityContext property to true. Doing so will auto configure an Hystrix concurrency strategy plugin hook who will transfer the SecurityContext from your main thread to the one used by the Hystrix command. Hystrix does not allow multiple hystrix concurrency strategy to be registered so an extension mechanism is available by declaring your own HystrixConcurrencyStrategy as a Spring bean. Spring Cloud will lookup for your implementation within the Spring context and wrap it inside its own plugin.

3.3 Health Indicator

The state of the connected circuit breakers are also exposed in the +/health endpoint of the calling application.

{
+    "hystrix": {
+        "openCircuitBreakers": [
+            "StoreIntegration::getStoresByLocationLink"
+        ],
+        "status": "CIRCUIT_OPEN"
+    },
+    "status": "UP"
+}

3.4 Hystrix Metrics Stream

To enable the Hystrix metrics stream include a dependency on spring-boot-starter-actuator. This will expose the /hystrix.stream as a management endpoint.

    <dependency>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-actuator</artifactId>
+    </dependency>

4. Circuit Breaker: Hystrix Dashboard

One of the main benefits of Hystrix is the set of metrics it gathers about each HystrixCommand. The Hystrix Dashboard displays the health of each circuit breaker in an efficient manner.

Figure 4.1. Hystrix Dashboard

Hystrix

5. Hystrix Timeouts And Ribbon Clients

When using Hystrix commands that wrap Ribbon clients you want to make sure your Hystrix timeout +is configured to be longer than the configured Ribbon timeout, including any potential +retries that might be made. For example, if your Ribbon connection timeout is one second and +the Ribbon client might retry the request three times, than your Hystrix timeout should +be slightly more than three seconds.

5.1 How to Include Hystrix Dashboard

To include the Hystrix Dashboard in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-hystrix-dashboard. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train.

To run the Hystrix Dashboard annotate your Spring Boot main class with @EnableHystrixDashboard. You then visit /hystrix and point the dashboard to an individual instances /hystrix.stream endpoint in a Hystrix client application.

[Note]Note

When connecting to a /hystrix.stream endpoint which uses HTTPS the certificate used by the server +must be trusted by the JVM. If the certificate is not trusted you must import the certificate into the JVM +in order for the Hystrix Dashboard to make a successful connection to the stream endpoint.

5.2 Turbine

Looking at an individual instances Hystrix data is not very useful in terms of the overall health of the system. Turbine is an application that aggregates all of the relevant /hystrix.stream endpoints into a combined /turbine.stream for use in the Hystrix Dashboard. Individual instances are located via Eureka. Running Turbine is as simple as annotating your main class with the @EnableTurbine annotation (e.g. using spring-cloud-starter-netflix-turbine to set up the classpath). All of the documented configuration properties from the Turbine 1 wiki apply. The only difference is that the turbine.instanceUrlSuffix does not need the port prepended as this is handled automatically unless turbine.instanceInsertPort=false.

[Note]Note

By default, Turbine looks for the /hystrix.stream endpoint on a registered instance by looking up its hostName and port entries in Eureka, then appending /hystrix.stream to it. +If the instance’s metadata contains management.port, it will be used instead of the port value for the /hystrix.stream endpoint. +By default, metadata entry management.port is equal to the management.port configuration property, it can be overridden though with following configuration:

eureka:
+  instance:
+    metadata-map:
+      management.port: ${management.port:8081}

The configuration key turbine.appConfig is a list of eureka serviceIds that turbine will use to lookup instances. The turbine stream is then used in the Hystrix dashboard using a url that looks like: http://my.turbine.server:8080/turbine.stream?cluster=CLUSTERNAME (the cluster parameter can be omitted if the name is "default"). The cluster parameter must match an entry in turbine.aggregator.clusterConfig. Values returned from eureka are uppercase, thus we expect this example to work if there is an app registered with Eureka called "customers":

turbine:
+  aggregator:
+    clusterConfig: CUSTOMERS
+  appConfig: customers

If you need to customize which cluster names should be used by Turbine (you don’t want to store cluster names in +turbine.aggregator.clusterConfig configuration) provide a bean of type TurbineClustersProvider.

The clusterName can be customized by a SPEL expression in turbine.clusterNameExpression with root an instance of InstanceInfo. The default value is appName, which means that the Eureka serviceId ends up as the cluster key (i.e. the InstanceInfo for customers has an appName of "CUSTOMERS"). A different example would be turbine.clusterNameExpression=aSGName, which would get the cluster name from the AWS ASG name. Another example:

turbine:
+  aggregator:
+    clusterConfig: SYSTEM,USER
+  appConfig: customers,stores,ui,admin
+  clusterNameExpression: metadata['cluster']

In this case, the cluster name from 4 services is pulled from their metadata map, and is expected to have values that include "SYSTEM" and "USER".

To use the "default" cluster for all apps you need a string literal expression (with single quotes, and escaped with double quotes if it is in YAML as well):

turbine:
+  appConfig: customers,stores
+  clusterNameExpression: "'default'"

Spring Cloud provides a spring-cloud-starter-netflix-turbine that has all the dependencies you need to get a Turbine server running. Just create a Spring Boot application and annotate it with @EnableTurbine.

[Note]Note

by default Spring Cloud allows Turbine to use the host and port to allow multiple processes per host, per cluster. If you want the native Netflix behaviour built into Turbine that does not allow multiple processes per host, per cluster (the key to the instance id is the hostname), then set the property turbine.combineHostPort=false.

5.3 Turbine Stream

In some environments (e.g. in a PaaS setting), the classic Turbine model of pulling metrics from all the distributed Hystrix commands doesn’t work. In that case you might want to have your Hystrix commands push metrics to Turbine, and Spring Cloud enables that with messaging. All you need to do on the client is add a dependency to spring-cloud-netflix-hystrix-stream and the spring-cloud-starter-stream-* of your choice (see Spring Cloud Stream documentation for details on the brokers, and how to configure the client credentials, but it should work out of the box for a local broker).

On the server side Just create a Spring Boot application and annotate it with @EnableTurbineStream and by default it will come up on port 8989 (point your Hystrix dashboard to that port, any path). You can customize the port using either server.port or turbine.stream.port. If you have spring-boot-starter-web and spring-boot-starter-actuator on the classpath as well, then you can open up the Actuator endpoints on a separate port (with Tomcat by default) by providing a management.port which is different.

You can then point the Hystrix Dashboard to the Turbine Stream Server instead of individual Hystrix streams. If Turbine Stream is running on port 8989 on myhost, then put http://myhost:8989 in the stream input field in the Hystrix Dashboard. Circuits will be prefixed by their respective serviceId, followed by a dot, then the circuit name.

Spring Cloud provides a spring-cloud-starter-netflix-turbine-stream that has all the dependencies you need to get a Turbine Stream server running - just add the Stream binder of your choice, e.g. spring-cloud-starter-stream-rabbit. You need Java 8 to run the app because it is Netty-based.

6. Client Side Load Balancer: Ribbon

Ribbon is a client side load balancer which gives you a lot of control +over the behaviour of HTTP and TCP clients. Feign already uses Ribbon, +so if you are using @FeignClient then this section also applies.

A central concept in Ribbon is that of the named client. Each load +balancer is part of an ensemble of components that work together to +contact a remote server on demand, and the ensemble has a name that +you give it as an application developer (e.g. using the @FeignClient +annotation). Spring Cloud creates a new ensemble as an +ApplicationContext on demand for each named client using +RibbonClientConfiguration. This contains (amongst other things) an +ILoadBalancer, a RestClient, and a ServerListFilter.

6.1 How to Include Ribbon

To include Ribbon in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-ribbon. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train.

6.2 Customizing the Ribbon Client

You can configure some bits of a Ribbon client using external +properties in <client>.ribbon.*, which is no different than using +the Netflix APIs natively, except that you can use Spring Boot +configuration files. The native options can +be inspected as static fields in CommonClientConfigKey (part of +ribbon-core).

Spring Cloud also lets you take full control of the client by +declaring additional configuration (on top of the +RibbonClientConfiguration) using @RibbonClient. Example:

@Configuration
+@RibbonClient(name = "foo", configuration = FooConfiguration.class)
+public class TestConfiguration {
+}

In this case the client is composed from the components already in +RibbonClientConfiguration together with any in FooConfiguration +(where the latter generally will override the former).

[Warning]Warning

The FooConfiguration has to be @Configuration but take +care that it is not in a @ComponentScan for the main application +context, otherwise it will be shared by all the @RibbonClients. If +you use @ComponentScan (or @SpringBootApplication) you need to +take steps to avoid it being included (for instance put it in a +separate, non-overlapping package, or specify the packages to scan +explicitly in the @ComponentScan).

Spring Cloud Netflix provides the following beans by default for ribbon +(BeanType beanName: ClassName):

  • IClientConfig ribbonClientConfig: DefaultClientConfigImpl
  • IRule ribbonRule: ZoneAvoidanceRule
  • IPing ribbonPing: DummyPing
  • ServerList<Server> ribbonServerList: ConfigurationBasedServerList
  • ServerListFilter<Server> ribbonServerListFilter: ZonePreferenceServerListFilter
  • ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer
  • ServerListUpdater ribbonServerListUpdater: PollingServerListUpdater

Creating a bean of one of those type and placing it in a @RibbonClient +configuration (such as FooConfiguration above) allows you to override each +one of the beans described. Example:

@Configuration
+protected static class FooConfiguration {
+	@Bean
+	public ZonePreferenceServerListFilter serverListFilter() {
+		ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter();
+		filter.setZone("myTestZone");
+		return filter;
+	}
+
+	@Bean
+	public IPing ribbonPing() {
+		return new PingUrl();
+	}
+}

This replaces the NoOpPing with PingUrl and provides a custom serverListFilter

6.3 Customizing default for all Ribbon Clients

A default configuration can be provided for all Ribbon Clients using the @RibbonClients annotation and registering a default configuration as shown in the following example:

@RibbonClients(defaultConfiguration = DefaultRibbonConfig.class)
+public class RibbonClientDefaultConfigurationTestsConfig {
+
+	public static class BazServiceList extends ConfigurationBasedServerList {
+		public BazServiceList(IClientConfig config) {
+			super.initWithNiwsConfig(config);
+		}
+	}
+}
+
+@Configuration
+class DefaultRibbonConfig {
+
+	@Bean
+	public IRule ribbonRule() {
+		return new BestAvailableRule();
+	}
+
+	@Bean
+	public IPing ribbonPing() {
+		return new PingUrl();
+	}
+
+	@Bean
+	public ServerList<Server> ribbonServerList(IClientConfig config) {
+		return new RibbonClientDefaultConfigurationTestsConfig.BazServiceList(config);
+	}
+
+	@Bean
+	public ServerListSubsetFilter serverListFilter() {
+		ServerListSubsetFilter filter = new ServerListSubsetFilter();
+		return filter;
+	}
+
+}

6.4 Customizing the Ribbon Client using properties

Starting with version 1.2.0, Spring Cloud Netflix now supports customizing Ribbon clients using properties to be compatible with the Ribbon documentation.

This allows you to change behavior at start up time in different environments.

The supported properties are listed below and should be prefixed by <clientName>.ribbon.:

  • NFLoadBalancerClassName: should implement ILoadBalancer
  • NFLoadBalancerRuleClassName: should implement IRule
  • NFLoadBalancerPingClassName: should implement IPing
  • NIWSServerListClassName: should implement ServerList
  • NIWSServerListFilterClassName should implement ServerListFilter
[Note]Note

Classes defined in these properties have precedence over beans defined using @RibbonClient(configuration=MyRibbonConfig.class) and the defaults provided by Spring Cloud Netflix.

To set the IRule for a service name users you could set the following:

application.yml.  +

users:
+  ribbon:
+    NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
+    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule

+

See the Ribbon documentation for implementations provided by Ribbon.

6.5 Using Ribbon with Eureka

When Eureka is used in conjunction with Ribbon (i.e., both are on the classpath) the ribbonServerList +is overridden with an extension of DiscoveryEnabledNIWSServerList +which populates the list of servers from Eureka. It also replaces the +IPing interface with NIWSDiscoveryPing which delegates to Eureka +to determine if a server is up. The ServerList that is installed by +default is a DomainExtractingServerList and the purpose of this is +to make physical metadata available to the load balancer without using +AWS AMI metadata (which is what Netflix relies on). By default the +server list will be constructed with "zone" information as provided in +the instance metadata (so on the remote clients set +eureka.instance.metadataMap.zone), and if that is missing it can use +the domain name from the server hostname as a proxy for zone (if the +flag approximateZoneFromHostname is set). Once the zone information +is available it can be used in a ServerListFilter. By default it +will be used to locate a server in the same zone as the client because +the default is a ZonePreferenceServerListFilter. The zone of the +client is determined the same way as the remote instances by default, +i.e. via eureka.instance.metadataMap.zone.

[Note]Note

The orthodox "archaius" way to set the client zone is via a +configuration property called "@zone", and Spring Cloud will use that +in preference to all other settings if it is available (note that the +key will have to be quoted in YAML configuration).

[Note]Note

If there is no other source of zone data then a guess is made +based on the client configuration (as opposed to the instance +configuration). We take eureka.client.availabilityZones, which is a +map from region name to a list of zones, and pull out the first zone +for the instance’s own region (i.e. the eureka.client.region, which +defaults to "us-east-1" for comatibility with native Netflix).

6.6 Example: How to Use Ribbon Without Eureka

Eureka is a convenient way to abstract the discovery of remote servers +so you don’t have to hard code their URLs in clients, but if you +prefer not to use it, Ribbon and Feign are still quite +amenable. Suppose you have declared a @RibbonClient for "stores", +and Eureka is not in use (and not even on the classpath). The Ribbon +client defaults to a configured server list, and you can supply the +configuration like this

application.yml.  +

stores:
+  ribbon:
+    listOfServers: example.com,google.com

+

6.7 Example: Disable Eureka use in Ribbon

Setting the property ribbon.eureka.enabled = false will explicitly +disable the use of Eureka in Ribbon.

application.yml.  +

ribbon:
+  eureka:
+   enabled: false

+

6.8 Using the Ribbon API Directly

You can also use the LoadBalancerClient directly. Example:

public class MyClass {
+    @Autowired
+    private LoadBalancerClient loadBalancer;
+
+    public void doStuff() {
+        ServiceInstance instance = loadBalancer.choose("stores");
+        URI storesUri = URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort()));
+        // ... do something with the URI
+    }
+}

6.9 Caching of Ribbon Configuration

Each Ribbon named client has a corresponding child Application Context that Spring Cloud maintains, this application context is lazily loaded up on the first request to the named client. +This lazy loading behavior can be changed to instead eagerly load up these child Application contexts at startup by specifying the names of the Ribbon clients.

application.yml.  +

ribbon:
+  eager-load:
+    enabled: true
+    clients: client1, client2, client3

+

6.10 How to Configure Hystrix thread pools

If you change zuul.ribbonIsolationStrategy to THREAD, the thread isolation strategy for Hystrix will be used for all routes. In this case, the HystrixThreadPoolKey is set to "RibbonCommand" as default. It means that HystrixCommands for all routes will be executed in the same Hystrix thread pool. This behavior can be changed using the following configuration and it will result in HystrixCommands being executed in the Hystrix thread pool for each route.

application.yml.  +

zuul:
+  threadPool:
+    useSeparateThreadPools: true

+

The default HystrixThreadPoolKey in this case is same with service ID for each route. To add a prefix to HystrixThreadPoolKey, set zuul.threadPool.threadPoolKeyPrefix to a value that you want to add. For example:

application.yml.  +

zuul:
+  threadPool:
+    useSeparateThreadPools: true
+    threadPoolKeyPrefix: zuulgw

+

6.11 How to Provide a Key to Ribbon’s IRule

If you need to provide your own IRule implementation to handle a special routing requirement like a canary test, +you probably want to pass some information to the choose method of IRule.

com.netflix.loadbalancer.IRule.java.  +

public interface IRule{
+    public Server choose(Object key);
+         :

+

You can provide some information that will be used to choose a target server by your IRule implementation like +the following:

RequestContext.getCurrentContext()
+              .set(FilterConstants.LOAD_BALANCER_KEY, "canary-test");

If you put any object into the RequestContext with a key FilterConstants.LOAD_BALANCER_KEY, it will +be passed to the choose method of IRule implementation. Above code must be executed before RibbonRoutingFilter +is executed and Zuul’s pre filter is the best place to do that. You can easily access HTTP headers and query parameters +via RequestContext in pre filter, so it can be used to determine LOAD_BALANCER_KEY that will be passed to Ribbon. +If you don’t put any value with LOAD_BALANCER_KEY in RequestContext, null will be passed as a parameter of choose +method.

7. External Configuration: Archaius

Archaius is the Netflix client side configuration library. It is the library used by all of the Netflix OSS components for configuration. Archaius is an extension of the Apache Commons Configuration project. It allows updates to configuration by either polling a source for changes or for a source to push changes to the client. Archaius uses Dynamic<Type>Property classes as handles to properties.

Archaius Example.  +

class ArchaiusTest {
+    DynamicStringProperty myprop = DynamicPropertyFactory
+            .getInstance()
+            .getStringProperty("my.prop");
+
+    void doSomething() {
+        OtherClass.someMethod(myprop.get());
+    }
+}

+

Archaius has its own set of configuration files and loading priorities. Spring applications should generally not use Archaius directly, but the need to configure the Netflix tools natively remains. Spring Cloud has a Spring Environment Bridge so Archaius can read properties from the Spring Environment. This allows Spring Boot projects to use the normal configuration toolchain, while allowing them to configure the Netflix tools, for the most part, as documented.

8. Router and Filter: Zuul

Routing is an integral part of a microservice architecture. For example, / may be mapped to your web application, /api/users is mapped to the user service and /api/shop is mapped to the shop service. Zuul is a JVM based router and server side load balancer by Netflix.

Netflix uses Zuul for the following:

  • Authentication
  • Insights
  • Stress Testing
  • Canary Testing
  • Dynamic Routing
  • Service Migration
  • Load Shedding
  • Security
  • Static Response handling
  • Active/Active traffic management

Zuul’s rule engine allows rules and filters to be written in essentially any JVM language, with built in support for Java and Groovy.

[Note]Note

The configuration property zuul.max.host.connections has been replaced by two new properties, zuul.host.maxTotalConnections and zuul.host.maxPerRouteConnections which default to 200 and 20 respectively.

[Note]Note

Default Hystrix isolation pattern (ExecutionIsolationStrategy) for all routes is SEMAPHORE. zuul.ribbonIsolationStrategy can be changed to THREAD if this isolation pattern is preferred.

8.1 How to Include Zuul

To include Zuul in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-zuul. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train.

8.2 Embedded Zuul Reverse Proxy

Spring Cloud has created an embedded Zuul proxy to ease the +development of a very common use case where a UI application wants to +proxy calls to one or more back end services. This feature is useful +for a user interface to proxy to the backend services it requires, +avoiding the need to manage CORS and authentication concerns +independently for all the backends.

To enable it, annotate a Spring Boot main class with +@EnableZuulProxy, and this forwards local calls to the appropriate +service. By convention, a service with the ID "users", will +receive requests from the proxy located at /users (with the prefix +stripped). The proxy uses Ribbon to locate an instance to forward to +via discovery, and all requests are executed in a +hystrix command, so +failures will show up in Hystrix metrics, and once the circuit is open +the proxy will not try to contact the service.

[Note]Note

the Zuul starter does not include a discovery client, so for +routes based on service IDs you need to provide one of those +on the classpath as well (e.g. Eureka is one choice).

To skip having a service automatically added, set +zuul.ignored-services to a list of service id patterns. If a service +matches a pattern that is ignored, but also included in the explicitly +configured routes map, then it will be unignored. Example:

application.yml.  +

 zuul:
+  ignoredServices: '*'
+  routes:
+    users: /myusers/**

+

In this example, all services are ignored except "users".

To augment or change +the proxy routes, you can add external configuration like the +following:

application.yml.  +

 zuul:
+  routes:
+    users: /myusers/**

+

This means that http calls to "/myusers" get forwarded to the "users" +service (for example "/myusers/101" is forwarded to "/101").

To get more fine-grained control over a route you can specify the path +and the serviceId independently:

application.yml.  +

 zuul:
+  routes:
+    users:
+      path: /myusers/**
+      serviceId: users_service

+

This means that http calls to "/myusers" get forwarded to the +"users_service" service. The route has to have a "path" which can be +specified as an ant-style pattern, so "/myusers/*" only matches one +level, but "/myusers/**" matches hierarchically.

The location of the backend can be specified as either a "serviceId" +(for a service from discovery) or a "url" (for a physical location), e.g.

application.yml.  +

 zuul:
+  routes:
+    users:
+      path: /myusers/**
+      url: http://example.com/users_service

+

These simple url-routes don’t get executed as a HystrixCommand nor do they loadbalance multiple URLs with Ribbon. +To achieve this, you can specify a serviceId with a static list of servers:

application.yml.  +

zuul:
+  routes:
+    echo:
+      path: /myusers/**
+      serviceId: myusers-service
+      stripPrefix: true
+
+hystrix:
+  command:
+    myusers-service:
+      execution:
+        isolation:
+          thread:
+            timeoutInMilliseconds: ...
+
+myusers-service:
+  ribbon:
+    NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
+    ListOfServers: http://example1.com,http://example2.com
+    ConnectTimeout: 1000
+    ReadTimeout: 3000
+    MaxTotalHttpConnections: 500
+    MaxConnectionsPerHost: 100

+

Another method is specifiying a service-route and configure a Ribbon client for the +serviceId (this requires disabling Eureka support in Ribbon: +see above for more information), e.g.

application.yml.  +

zuul:
+  routes:
+    users:
+      path: /myusers/**
+      serviceId: users
+
+ribbon:
+  eureka:
+    enabled: false
+
+users:
+  ribbon:
+    listOfServers: example.com,google.com

+

You can provide convention between serviceId and routes using +regexmapper. It uses regular expression named groups to extract +variables from serviceId and inject them into a route pattern.

ApplicationConfiguration.java.  +

@Bean
+public PatternServiceRouteMapper serviceRouteMapper() {
+    return new PatternServiceRouteMapper(
+        "(?<name>^.+)-(?<version>v.+$)",
+        "${version}/${name}");
+}

+

This means that a serviceId "myusers-v1" will be mapped to route +"/v1/myusers/**". Any regular expression is accepted but all named +groups must be present in both servicePattern and routePattern. If +servicePattern does not match a serviceId, the default behavior is +used. In the example above, a serviceId "myusers" will be mapped to route +"/myusers/**" (no version detected) This feature is disabled by +default and only applies to discovered services.

To add a prefix to all mappings, set zuul.prefix to a value, such as +/api. The proxy prefix is stripped from the request before the +request is forwarded by default (switch this behaviour off with +zuul.stripPrefix=false). You can also switch off the stripping of +the service-specific prefix from individual routes, e.g.

application.yml.  +

 zuul:
+  routes:
+    users:
+      path: /myusers/**
+      stripPrefix: false

+

[Note]Note

zuul.stripPrefix only applies to the prefix set in zuul.prefix. It does not have any effect on prefixes +defined within a given route’s path.

In this example, requests to "/myusers/101" will be forwarded to "/myusers/101" on the "users" service.

The zuul.routes entries actually bind to an object of type ZuulProperties. If you +look at the properties of that object you will see that it also has a "retryable" flag. +Set that flag to "true" to have the Ribbon client automatically retry failed requests +(and if you need to you can modify the parameters of the retry operations using +the Ribbon client configuration).

The X-Forwarded-Host header is added to the forwarded requests by +default. To turn it off set zuul.addProxyHeaders = false. The +prefix path is stripped by default, and the request to the backend +picks up a header "X-Forwarded-Prefix" ("/myusers" in the examples +above).

An application with @EnableZuulProxy could act as a standalone +server if you set a default route ("/"), for example zuul.route.home: +/ would route all traffic (i.e. "/**") to the "home" service.

If more fine-grained ignoring is needed, you can specify specific patterns to ignore. +These patterns are evaluated at the start of the route location process, which +means prefixes should be included in the pattern to warrant a match. Ignored patterns +span all services and supersede any other route specification.

application.yml.  +

 zuul:
+  ignoredPatterns: /**/admin/**
+  routes:
+    users: /myusers/**

+

This means that all calls such as "/myusers/101" will be forwarded to "/101" on the "users" service. +But calls including "/admin/" will not resolve.

[Warning]Warning

If you need your routes to have their order preserved you need to use a YAML +file as the ordering will be lost using a properties file. For example:

application.yml.  +

 zuul:
+  routes:
+    users:
+      path: /myusers/**
+    legacy:
+      path: /**

+

If you were to use a properties file, the legacy path may end up in front of the users +path rendering the users path unreachable.

8.3 Zuul Http Client

The default HTTP client used by zuul is now backed by the Apache HTTP Client instead of the +deprecated Ribbon RestClient. To use RestClient or to use the okhttp3.OkHttpClient set +ribbon.restclient.enabled=true or ribbon.okhttp.enabled=true respectively. If you would +like to customize the Apache HTTP client or the OK HTTP client provide a bean of type +ClosableHttpClient or OkHttpClient.

8.4 Cookies and Sensitive Headers

It’s OK to share headers between services in the same system, but you +probably don’t want sensitive headers leaking downstream into external +servers. You can specify a list of ignored headers as part of the +route configuration. Cookies play a special role because they have +well-defined semantics in browsers, and they are always to be treated +as sensitive. If the consumer of your proxy is a browser, then cookies +for downstream services also cause problems for the user because they +all get jumbled up (all downstream services look like they come from +the same place).

If you are careful with the design of your services, for example if +only one of the downstream services sets cookies, then you might be +able to let them flow from the backend all the way up to the +caller. Also, if your proxy sets cookies and all your back end +services are part of the same system, it can be natural to simply +share them (and for instance use Spring Session to link them up to some +shared state). Other than that, any cookies that get set by downstream +services are likely to be not very useful to the caller, so it is +recommended that you make (at least) "Set-Cookie" and "Cookie" into +sensitive headers for routes that are not part of your domain. Even +for routes that are part of your domain, try to think carefully +about what it means before allowing cookies to flow between them and +the proxy.

The sensitive headers can be configured as a comma-separated list per +route, e.g.

application.yml.  +

 zuul:
+  routes:
+    users:
+      path: /myusers/**
+      sensitiveHeaders: Cookie,Set-Cookie,Authorization
+      url: https://downstream

+

[Note]Note

this is the default value for sensitiveHeaders, so you don’t +need to set it unless you want it to be different. N.B. this is new in +Spring Cloud Netflix 1.1 (in 1.0 the user had no control over headers +and all cookies flow in both directions).

The sensitiveHeaders are a blacklist and the default is not empty, +so to make Zuul send all headers (except the "ignored" ones) you would +have to explicitly set it to the empty list. This is necessary if you +want to pass cookie or authorization headers to your back end. Example:

application.yml.  +

 zuul:
+  routes:
+    users:
+      path: /myusers/**
+      sensitiveHeaders:
+      url: https://downstream

+

Sensitive headers can also be set globally by setting zuul.sensitiveHeaders. If sensitiveHeaders is set on a route, this will override the global sensitiveHeaders setting.

8.5 Ignored Headers

In addition to the per-route sensitive headers, you can set a global +value for zuul.ignoredHeaders for values that should be discarded +(both request and response) during interactions with downstream +services. By default these are empty, if Spring Security is not on the +classpath, and otherwise they are initialized to a set of well-known +"security" headers (e.g. involving caching) as specified by Spring +Security. The assumption in this case is that the downstream services +might add these headers too, and we want the values from the proxy. +To not discard these well known security headers in case Spring Security is on the classpath you can set zuul.ignoreSecurityHeaders to false. This can be useful if you disabled the HTTP Security response headers in Spring Security and want the values provided by downstream services

8.6 Management Endpoints

If you are using @EnableZuulProxy with the Spring Boot Actuator you +will enable (by default) two additional endpoints:

  • Routes
  • Filters

8.6.1 Routes Endpoint

A GET to the routes endpoint at /routes will return a list of the mapped +routes:

GET /routes.  +

{
+  /stores/**: "http://localhost:8081"
+}

+

Additional route details can be requested through the /routes/details endpoint. This will produce the following output:

GET /routes/details.  +

{
+  "/stores/**": {
+    "id": "stores",
+    "fullPath": "/stores/**",
+    "location": "http://localhost:8081",
+    "path": "/**",
+    "prefix": "/stores",
+    "retryable": false,
+    "customSensitiveHeaders": false,
+    "prefixStripped": true
+  }
+}

+

A POST to /routes will force a refresh of the existing routes (e.g. in +case there have been changes in the service catalog). You can disable +this endpoint by setting endpoints.routes.enabled to false.

[Note]Note

the routes should respond automatically to changes in the +service catalog, but the POST to /routes is a way to force the change +to happen immediately.

8.6.2 Filters Endpoint

A GET to the filters endpoint at /filters will return a map of Zuul +filters by type. For each filter type in the map, you will find a list +of all the filters of that type, along with their details.

8.7 Strangulation Patterns and Local Forwards

A common pattern when migrating an existing application or API is to +"strangle" old endpoints, slowly replacing them with different +implementations. The Zuul proxy is a useful tool for this because you +can use it to handle all traffic from clients of the old endpoints, +but redirect some of the requests to new ones.

Example configuration:

application.yml.  +

 zuul:
+  routes:
+    first:
+      path: /first/**
+      url: http://first.example.com
+    second:
+      path: /second/**
+      url: forward:/second
+    third:
+      path: /third/**
+      url: forward:/3rd
+    legacy:
+      path: /**
+      url: http://legacy.example.com

+

In this example we are strangling the "legacy" app which is mapped to +all requests that do not match one of the other patterns. Paths in +/first/** have been extracted into a new service with an external +URL. And paths in /second/** are forwarded so they can be handled +locally, e.g. with a normal Spring @RequestMapping. Paths in +/third/** are also forwarded, but with a different prefix +(i.e. /third/foo is forwarded to /3rd/foo).

[Note]Note

The ignored patterns aren’t completely ignored, they just +aren’t handled by the proxy (so they are also effectively forwarded +locally).

8.8 Uploading Files through Zuul

If you use @EnableZuulProxy, you can use the proxy paths to +upload files and it should just work as long as the files +are small. For large files there is an alternative path +which bypasses the Spring DispatcherServlet (to +avoid multipart processing) in "/zuul/*". I.e. if +zuul.routes.customers=/customers/** then you can +POST large files to "/zuul/customers/*". The servlet +path is externalized via zuul.servletPath. Extremely +large files will also require elevated timeout settings +if the proxy route takes you through a Ribbon load +balancer, e.g.

application.yml.  +

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000
+ribbon:
+  ConnectTimeout: 3000
+  ReadTimeout: 60000

+

Note that for streaming to work with large files, you need to use chunked encoding in the request (which some browsers +do not do by default). E.g. on the command line:

$ curl -v -H "Transfer-Encoding: chunked" \
+    -F "file=@mylarge.iso" localhost:9999/zuul/simple/file

8.9 Query String Encoding

When processing the incoming request, query params are decoded so they can be available for possible modifications in +Zuul filters. They are then re-encoded when building the backend request in the route filters. The result +can be different than the original input if it was encoded using Javascript’s encodeURIComponent() method for example. +While this causes no issues in most cases, some web servers can be picky with the encoding of complex query string.

To force the original encoding of the query string, it is possible to pass a special flag to ZuulProperties so +that the query string is taken as is with the HttpServletRequest::getQueryString method :

application.yml.  +

 zuul:
+  forceOriginalQueryStringEncoding: true

+

Note: This special flag only works with SimpleHostRoutingFilter and you loose the ability to easily override +query parameters with RequestContext.getCurrentContext().setRequestQueryParams(someOverriddenParameters) since +the query string is now fetched directly on the original HttpServletRequest.

8.10 Plain Embedded Zuul

You can also run a Zuul server without the proxying, or switch on parts of the proxying platform selectively, if you +use @EnableZuulServer (instead of @EnableZuulProxy). Any beans that you add to the application of type ZuulFilter +will be installed automatically, as they are with @EnableZuulProxy, but without any of the proxy filters being added +automatically.

In this case the routes into the Zuul server are still specified by +configuring "zuul.routes.*", but there is no service +discovery and no proxying, so the "serviceId" and "url" settings are +ignored. For example:

application.yml.  +

 zuul:
+  routes:
+    api: /api/**

+

maps all paths in "/api/**" to the Zuul filter chain.

8.11 Disable Zuul Filters

Zuul for Spring Cloud comes with a number of ZuulFilter beans enabled by default +in both proxy and server mode. See the zuul filters package for the +possible filters that are enabled. If you want to disable one, simply set +zuul.<SimpleClassName>.<filterType>.disable=true. By convention, the package after +filters is the Zuul filter type. For example to disable +org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter set +zuul.SendResponseFilter.post.disable=true.

8.12 Providing Hystrix Fallbacks For Routes

When a circuit for a given route in Zuul is tripped you can provide a fallback response +by creating a bean of type FallbackProvider. Within this bean you need to specify +the route ID the fallback is for and provide a ClientHttpResponse to return +as a fallback. Here is a very simple FallbackProvider implementation.

class MyFallbackProvider implements FallbackProvider {
+
+    @Override
+    public String getRoute() {
+        return "customers";
+    }
+
+    @Override
+    public ClientHttpResponse fallbackResponse(String route, final Throwable cause) {
+        if (cause instanceof HystrixTimeoutException) {
+            return response(HttpStatus.GATEWAY_TIMEOUT);
+        } else {
+            return response(HttpStatus.INTERNAL_SERVER_ERROR);
+        }
+    }
+
+    private ClientHttpResponse response(final HttpStatus status) {
+        return new ClientHttpResponse() {
+            @Override
+            public HttpStatus getStatusCode() throws IOException {
+                return status;
+            }
+
+            @Override
+            public int getRawStatusCode() throws IOException {
+                return status.value();
+            }
+
+            @Override
+            public String getStatusText() throws IOException {
+                return status.getReasonPhrase();
+            }
+
+            @Override
+            public void close() {
+            }
+
+            @Override
+            public InputStream getBody() throws IOException {
+                return new ByteArrayInputStream("fallback".getBytes());
+            }
+
+            @Override
+            public HttpHeaders getHeaders() {
+                HttpHeaders headers = new HttpHeaders();
+                headers.setContentType(MediaType.APPLICATION_JSON);
+                return headers;
+            }
+        };
+    }
+}

And here is what the route configuration would look like.

zuul:
+  routes:
+    customers: /customers/**

If you would like to provide a default fallback for all routes than you can create a bean of +type FallbackProvider and have the getRoute method return * or null.

class MyFallbackProvider implements FallbackProvider {
+    @Override
+    public String getRoute() {
+        return "*";
+    }
+
+    @Override
+    public ClientHttpResponse fallbackResponse(String route, Throwable throwable) {
+        return new ClientHttpResponse() {
+            @Override
+            public HttpStatus getStatusCode() throws IOException {
+                return HttpStatus.OK;
+            }
+
+            @Override
+            public int getRawStatusCode() throws IOException {
+                return 200;
+            }
+
+            @Override
+            public String getStatusText() throws IOException {
+                return "OK";
+            }
+
+            @Override
+            public void close() {
+
+            }
+
+            @Override
+            public InputStream getBody() throws IOException {
+                return new ByteArrayInputStream("fallback".getBytes());
+            }
+
+            @Override
+            public HttpHeaders getHeaders() {
+                HttpHeaders headers = new HttpHeaders();
+                headers.setContentType(MediaType.APPLICATION_JSON);
+                return headers;
+            }
+        };
+    }
+}

8.13 Zuul Timeouts

If you want to configure the socket timeouts and read timeouts for requests proxied through +Zuul there are two options based on your configuration.

If Zuul is using service discovery then you need to configure these timeouts via Ribbon properties, +ribbon.ReadTimeout and ribbon.SocketTimeout.

If you have configured Zuul routes by specifying URLs then you will need to use +zuul.host.connect-timeout-millis and zuul.host.socket-timeout-millis.

8.14 Rewriting Location header

If Zuul is fronting a web application then there may be a need to re-write the Location header when the web application redirects through a http status code of 3XX, otherwise the browser will end up redirecting to the web application’s url instead of the Zuul url. +A LocationRewriteFilter Zuul filter can be configured to re-write the Location header to the Zuul’s url, it also adds back the stripped global and route specific prefixes. The filter can be added the following way via a Spring Configuration file:

import org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilter;
+...
+
+@Configuration
+@EnableZuulProxy
+public class ZuulConfig {
+    @Bean
+    public LocationRewriteFilter locationRewriteFilter() {
+        return new LocationRewriteFilter();
+    }
+}
[Warning]Warning

Use this filter with caution though, the filter acts on the Location header of ALL 3XX response codes which may not be appropriate in all scenarios, say if the user is redirecting to an external URL.

8.15 Zuul Developer Guide

For a general overview of how Zuul works, please see the Zuul Wiki.

8.15.1 The Zuul Servlet

Zuul is implemented as a Servlet. For the general cases, Zuul is embedded into the Spring Dispatch mechanism. This allows Spring MVC to be in control of the routing. In this case, Zuul is configured to buffer requests. If there is a need to go through Zuul without buffering requests (e.g. for large file uploads), the Servlet is also installed outside of the Spring Dispatcher. By default, this is located at /zuul. This path can be changed with the zuul.servlet-path property.

8.15.2 Zuul RequestContext

To pass information between filters, Zuul uses a RequestContext. Its data is held in a ThreadLocal specific to each request. Information about where to route requests, errors and the actual HttpServletRequest and HttpServletResponse are stored there. The RequestContext extends ConcurrentHashMap, so anything can be stored in the context. FilterConstants contains the keys that are used by the filters installed by Spring Cloud Netflix (more on these later).

8.15.3 @EnableZuulProxy vs. @EnableZuulServer

Spring Cloud Netflix installs a number of filters based on which annotation was used to enable Zuul. @EnableZuulProxy is a superset of @EnableZuulServer. In other words, @EnableZuulProxy contains all filters installed by @EnableZuulServer. The additional filters in the "proxy" enable routing functionality. If you want a "blank" Zuul, you should use @EnableZuulServer.

8.15.4 @EnableZuulServer Filters

Creates a SimpleRouteLocator that loads route definitions from Spring Boot configuration files.

The following filters are installed (as normal Spring Beans):

Pre filters:

  • ServletDetectionFilter: Detects if the request is through the Spring Dispatcher. Sets boolean with key FilterConstants.IS_DISPATCHER_SERVLET_REQUEST_KEY.
  • FormBodyWrapperFilter: Parses form data and reencodes it for downstream requests.
  • DebugFilter: if the debug request parameter is set, this filter sets RequestContext.setDebugRouting() and RequestContext.setDebugRequest() to true.

Route filters:

  • SendForwardFilter: This filter forwards requests using the Servlet RequestDispatcher. The forwarding location is stored in the RequestContext attribute FilterConstants.FORWARD_TO_KEY. This is useful for forwarding to endpoints in the current application.

Post filters:

  • SendResponseFilter: Writes responses from proxied requests to the current response.

Error filters:

  • SendErrorFilter: Forwards to /error (by default) if RequestContext.getThrowable() is not null. The default forwarding path (/error) can be changed by setting the error.path property.

8.15.5 @EnableZuulProxy Filters

Creates a DiscoveryClientRouteLocator that loads route definitions from a DiscoveryClient (like Eureka), as well as from properties. A route is created for each serviceId from the DiscoveryClient. As new services are added, the routes will be refreshed.

In addition to the filters described above, the following filters are installed (as normal Spring Beans):

Pre filters:

  • PreDecorationFilter: This filter determines where and how to route based on the supplied RouteLocator. It also sets various proxy-related headers for downstream requests.

Route filters:

  • RibbonRoutingFilter: This filter uses Ribbon, Hystrix and pluggable HTTP clients to send requests. Service ids are found in the RequestContext attribute FilterConstants.SERVICE_ID_KEY. This filter can use different HTTP clients. They are:

    • Apache HttpClient. This is the default client.
    • Squareup OkHttpClient v3. This is enabled by having the com.squareup.okhttp3:okhttp library on the classpath and setting ribbon.okhttp.enabled=true.
    • Netflix Ribbon HTTP client. This is enabled by setting ribbon.restclient.enabled=true. This client has limitations, such as it doesn’t support the PATCH method, but also has built-in retry.
  • SimpleHostRoutingFilter: This filter sends requests to predetermined URLs via an Apache HttpClient. URLs are found in RequestContext.getRouteHost().

8.15.6 Custom Zuul Filter examples

Most of the following "How to Write" examples below are included Sample Zuul Filters project. There are also examples of manipulating the request or response body in that repository.

8.15.7 How to Write a Pre Filter

Pre filters are used to set up data in the RequestContext for use in filters downstream. The main use case is to set information required for route filters.

public class QueryParamPreFilter extends ZuulFilter {
+	@Override
+	public int filterOrder() {
+		return PRE_DECORATION_FILTER_ORDER - 1; // run before PreDecoration
+	}
+
+	@Override
+	public String filterType() {
+		return PRE_TYPE;
+	}
+
+	@Override
+	public boolean shouldFilter() {
+		RequestContext ctx = RequestContext.getCurrentContext();
+		return !ctx.containsKey(FORWARD_TO_KEY) // a filter has already forwarded
+				&& !ctx.containsKey(SERVICE_ID_KEY); // a filter has already determined serviceId
+	}
+    @Override
+    public Object run() {
+        RequestContext ctx = RequestContext.getCurrentContext();
+		HttpServletRequest request = ctx.getRequest();
+		if (request.getParameter("foo") != null) {
+		    // put the serviceId in `RequestContext`
+    		ctx.put(SERVICE_ID_KEY, request.getParameter("foo"));
+    	}
+        return null;
+    }
+}

The filter above populates SERVICE_ID_KEY from the foo request parameter. In reality, it’s not a good idea to do that kind of direct mapping, but the service id should be looked up from the value of foo instead.

Now that SERVICE_ID_KEY is populated, PreDecorationFilter won’t run and RibbonRoutingFilter will. If you wanted to route to a full URL instead, call ctx.setRouteHost(url) instead.

To modify the path that routing filters will forward to, set the REQUEST_URI_KEY.

8.15.8 How to Write a Route Filter

Route filters are run after pre filters and are used to make requests to other services. Much of the work here is to translate request and response data to and from the client required model.

public class OkHttpRoutingFilter extends ZuulFilter {
+	@Autowired
+	private ProxyRequestHelper helper;
+
+	@Override
+	public String filterType() {
+		return ROUTE_TYPE;
+	}
+
+	@Override
+	public int filterOrder() {
+		return SIMPLE_HOST_ROUTING_FILTER_ORDER - 1;
+	}
+
+	@Override
+	public boolean shouldFilter() {
+		return RequestContext.getCurrentContext().getRouteHost() != null
+				&& RequestContext.getCurrentContext().sendZuulResponse();
+	}
+
+    @Override
+    public Object run() {
+		OkHttpClient httpClient = new OkHttpClient.Builder()
+				// customize
+				.build();
+
+		RequestContext context = RequestContext.getCurrentContext();
+		HttpServletRequest request = context.getRequest();
+
+		String method = request.getMethod();
+
+		String uri = this.helper.buildZuulRequestURI(request);
+
+		Headers.Builder headers = new Headers.Builder();
+		Enumeration<String> headerNames = request.getHeaderNames();
+		while (headerNames.hasMoreElements()) {
+			String name = headerNames.nextElement();
+			Enumeration<String> values = request.getHeaders(name);
+
+			while (values.hasMoreElements()) {
+				String value = values.nextElement();
+				headers.add(name, value);
+			}
+		}
+
+		InputStream inputStream = request.getInputStream();
+
+		RequestBody requestBody = null;
+		if (inputStream != null && HttpMethod.permitsRequestBody(method)) {
+			MediaType mediaType = null;
+			if (headers.get("Content-Type") != null) {
+				mediaType = MediaType.parse(headers.get("Content-Type"));
+			}
+			requestBody = RequestBody.create(mediaType, StreamUtils.copyToByteArray(inputStream));
+		}
+
+		Request.Builder builder = new Request.Builder()
+				.headers(headers.build())
+				.url(uri)
+				.method(method, requestBody);
+
+		Response response = httpClient.newCall(builder.build()).execute();
+
+		LinkedMultiValueMap<String, String> responseHeaders = new LinkedMultiValueMap<>();
+
+		for (Map.Entry<String, List<String>> entry : response.headers().toMultimap().entrySet()) {
+			responseHeaders.put(entry.getKey(), entry.getValue());
+		}
+
+		this.helper.setResponse(response.code(), response.body().byteStream(),
+				responseHeaders);
+		context.setRouteHost(null); // prevent SimpleHostRoutingFilter from running
+		return null;
+    }
+}

The above filter translates Servlet request information into OkHttp3 request information, executes an HTTP request, then translates OkHttp3 reponse information to the Servlet response. WARNING: this filter might have bugs and not function correctly.

8.15.9 How to Write a Post Filter

Post filters typically manipulate the response. In the filter below, we add a random UUID as the X-Foo header. Other manipulations, such as transforming the response body, are much more complex and compute-intensive.

public class AddResponseHeaderFilter extends ZuulFilter {
+	@Override
+	public String filterType() {
+		return POST_TYPE;
+	}
+
+	@Override
+	public int filterOrder() {
+		return SEND_RESPONSE_FILTER_ORDER - 1;
+	}
+
+	@Override
+	public boolean shouldFilter() {
+		return true;
+	}
+
+	@Override
+	public Object run() {
+		RequestContext context = RequestContext.getCurrentContext();
+    	HttpServletResponse servletResponse = context.getResponse();
+		servletResponse.addHeader("X-Foo", UUID.randomUUID().toString());
+		return null;
+	}
+}

8.15.10 How Zuul Errors Work

If an exception is thrown during any portion of the Zuul filter lifecycle, the error filters are executed. The SendErrorFilter is only run if RequestContext.getThrowable() is not null. It then sets specific javax.servlet.error.* attributes in the request and forwards the request to the Spring Boot error page.

8.15.11 Zuul Eager Application Context Loading

Zuul internally uses Ribbon for calling the remote url’s and Ribbon clients are by default lazily loaded up by Spring Cloud on first call. +This behavior can be changed for Zuul using the following configuration and will result in the child Ribbon related Application contexts being eagerly loaded up at application startup time.

application.yml.  +

zuul:
+  ribbon:
+    eager-load:
+      enabled: true

+

9. Polyglot support with Sidecar

Do you have non-jvm languages you want to take advantage of Eureka, Ribbon and +Config Server? The Spring Cloud Netflix Sidecar was inspired by +Netflix Prana. It includes a simple http api +to get all of the instances (ie host and port) for a given service. You can +also proxy service calls through an embedded Zuul proxy which gets its route +entries from Eureka. The Spring Cloud Config Server can be accessed directly +via host lookup or through the Zuul Proxy. The non-jvm app should implement +a health check so the Sidecar can report to eureka if the app is up or down.

To include Sidecar in your project use the dependency with group org.springframework.cloud +and artifact id spring-cloud-netflix-sidecar.

To enable the Sidecar, create a Spring Boot application with @EnableSidecar. +This annotation includes @EnableCircuitBreaker, @EnableDiscoveryClient, +and @EnableZuulProxy. Run the resulting application on the same host as the +non-jvm application.

To configure the side car add sidecar.port and sidecar.health-uri to application.yml. +The sidecar.port property is the port the non-jvm app is listening on. This +is so the Sidecar can properly register the app with Eureka. The sidecar.health-uri +is a uri accessible on the non-jvm app that mimicks a Spring Boot health +indicator. It should return a json document like the following:

health-uri-document.  +

{
+  "status":"UP"
+}

+

Here is an example application.yml for a Sidecar application:

application.yml.  +

server:
+  port: 5678
+spring:
+  application:
+    name: sidecar
+
+sidecar:
+  port: 8000
+  health-uri: http://localhost:8000/health.json

+

The api for the DiscoveryClient.getInstances() method is /hosts/{serviceId}. +Here is an example response for /hosts/customers that returns two instances on +different hosts. This api is accessible to the non-jvm app (if the sidecar is +on port 5678) at http://localhost:5678/hosts/{serviceId}.

/hosts/customers.  +

[
+    {
+        "host": "myhost",
+        "port": 9000,
+        "uri": "http://myhost:9000",
+        "serviceId": "CUSTOMERS",
+        "secure": false
+    },
+    {
+        "host": "myhost2",
+        "port": 9000,
+        "uri": "http://myhost2:9000",
+        "serviceId": "CUSTOMERS",
+        "secure": false
+    }
+]

+

The Zuul proxy automatically adds routes for each service known in eureka to +/<serviceId>, so the customers service is available at /customers. The +Non-jvm app can access the customer service via http://localhost:5678/customers +(assuming the sidecar is listening on port 5678).

If the Config Server is registered with Eureka, non-jvm application can access +it via the Zuul proxy. If the serviceId of the ConfigServer is configserver +and the Sidecar is on port 5678, then it can be accessed at +http://localhost:5678/configserver

Non-jvm app can take advantage of the Config Server’s ability to return YAML +documents. For example, a call to http://sidecar.local.spring.io:5678/configserver/default-master.yml +might result in a YAML document like the following

eureka:
+  client:
+    serviceUrl:
+      defaultZone: http://localhost:8761/eureka/
+  password: password
+info:
+  description: Spring Cloud Samples
+  url: https://github.com/spring-cloud-samples

10. Metrics Backend: Atlas

Atlas was developed by Netflix to manage dimensional time series data for near real-time operational insight. Atlas features in-memory data storage, allowing it to gather and report very large numbers of metrics, very quickly.

Atlas captures operational intelligence. Whereas business intelligence is data gathered for analyzing trends over time, operational intelligence provides a picture of what is currently happening within a system.

Spring Cloud provides a spring-cloud-starter-netflix-atlas that has all the dependencies you need. Then just annotate your Spring Boot application with @EnableAtlas and provide a location for your running Atlas server with the netflix.atlas.uri property.

10.1 Using Atlas

To bootstrap a in-memory standalone Atlas instance:

$ curl -LO https://github.com/Netflix/atlas/releases/download/v1.4.2/atlas-1.4.2-standalone.jar
+$ java -jar atlas-1.4.2-standalone.jar
[Tip]Tip

An Atlas standalone node running on an r3.2xlarge (61GB RAM) can handle roughly 2 million metrics per minute for a given 6 hour window.

Once running and you have collected a handful of metrics, verify that your setup is correct by listing tags on the Atlas server:

$ curl http://ATLAS/api/v1/tags
[Tip]Tip

After executing several requests against your service, you can gather some very basic information on the request latency of every request by pasting the following url in your browser: http://ATLAS/api/v1/graph?q=name,rest,:eq,:avg

The Atlas wiki contains a compilation of sample queries for various scenarios.

Make sure to check out the alerting philosophy and docs on using double exponential smoothing to generate dynamic alert thresholds.

11. Retrying Failed Requests

Spring Cloud Netflix offers a variety of ways to make HTTP requests. You can use a load balanced +RestTemplate, Ribbon, or Feign. No matter how you choose to your HTTP requests, there is always +a chance the request may fail. When a request fails you may want to have the request retried +automatically. To accomplish this when using Sping Cloud Netflix you need to include +Spring Retry on your application’s classpath. +When Spring Retry is present load balanced RestTemplates, Feign, and Zuul will automatically +retry any failed requests (assuming you configuration allows it to).

11.1 BackOff Policies

By default no backoff policy is used when retrying requests. If you would like to configure +a backoff policy you will need to create a bean of type LoadBalancedBackOffPolicyFactory +which will be used to create a BackOffPolicy for a given service.

@Configuration
+public class MyConfiguration {
+    @Bean
+    LoadBalancedBackOffPolicyFactory backOffPolciyFactory() {
+        return new LoadBalancedBackOffPolicyFactory() {
+            @Override
+            public BackOffPolicy createBackOffPolicy(String service) {
+                return new ExponentialBackOffPolicy();
+            }
+        };
+    }
+}

11.2 Configuration

Anytime Ribbon is used with Spring Retry you can control the retry functionality by configuring +certain Ribbon properties. The properties you can use are +client.ribbon.MaxAutoRetries, client.ribbon.MaxAutoRetriesNextServer, and +client.ribbon.OkToRetryOnAllOperations. See the Ribbon documentation +for a description of what there properties do.

[Warning]Warning

Enabling client.ribbon.OkToRetryOnAllOperations includes retring POST requests wich can have a impact +on the server’s resources due to the buffering of the request’s body.

In addition you may want to retry requests when certain status codes are returned in the +response. You can list the response codes you would like the Ribbon client to retry using the + property clientName.ribbon.retryableStatusCodes. For example

clientName:
+  ribbon:
+    retryableStatusCodes: 404,502

You can also create a bean of type LoadBalancedRetryPolicy and implement the retryableStatusCode +method to determine whether you want to retry a request given the status code.

11.2.1 Zuul

You can turn off Zuul’s retry functionality by setting zuul.retryable to false. You +can also disable retry functionality on route by route basis by setting +zuul.routes.routename.retryable to false.

12. HTTP Clients

Spring Cloud Netflix will automatically create the HTTP client used by Ribbon, Feign, and +Zuul for you. However you can also provide your own HTTP clients customized how you please +yourself. To do this you can either create a bean of type ClosableHttpClient if you +are using the Apache Http Cient, or OkHttpClient if you are using OK HTTP.

[Note]Note

When you create your own HTTP client you are also responsible for implementing +the correct connection management strategies for these clients. Doing this improperly +can result in resource management issues.

\ No newline at end of file diff --git a/spring-cloud-netflix/2.0.0.M7/spring-cloud-netflix.xml b/spring-cloud-netflix/2.0.0.M7/spring-cloud-netflix.xml new file mode 100644 index 00000000..c49d3993 --- /dev/null +++ b/spring-cloud-netflix/2.0.0.M7/spring-cloud-netflix.xml @@ -0,0 +1,2051 @@ + + + + + +Spring Cloud Netflix +2018-02-26 + + + +2.0.0.M7 +This project provides Netflix OSS integrations for Spring Boot apps through autoconfiguration +and binding to the Spring Environment and other Spring programming model idioms. With a few +simple annotations you can quickly enable and configure the common patterns inside your +application and build large distributed systems with battle-tested Netflix components. The +patterns provided include Service Discovery (Eureka), Circuit Breaker (Hystrix), +Intelligent Routing (Zuul) and Client Side Load Balancing (Ribbon). + + +Service Discovery: Eureka Clients +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. Eureka is the Netflix Service Discovery Server and Client. The server can be configured and deployed to be highly available, with each server replicating state about the registered services to the others. +
+How to Include Eureka Client +To include Eureka Client in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-eureka-client. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train. +
+
+Registering with Eureka +When a client registers with Eureka, it provides meta-data about itself +such as host and port, health indicator URL, home page etc. Eureka +receives heartbeat messages from each instance belonging to a service. +If the heartbeat fails over a configurable timetable, the instance is +normally removed from the registry. +Example eureka client: +@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). By having spring-cloud-starter-netflix-eureka-client + on the classpath your application will automatically register with the Eureka Server. Configuration is required to +locate the Eureka server. Example: + +application.yml + +eureka: + client: + serviceUrl: + defaultZone: http://localhost:8761/eureka/ + + +where "defaultZone" is a magic string fallback value that provides the +service URL for any client that doesn’t express a preference +(i.e. it’s a useful default). +The default application name (service ID), virtual host and non-secure +port, taken from the Environment, are ${spring.application.name}, +${spring.application.name} and ${server.port} respectively. +Having spring-cloud-starter-netflix-eureka-client on the classpath +makes the app into both a Eureka "instance" +(i.e. it registers itself) and a "client" (i.e. it can query the +registry to locate other services). The instance behaviour is driven +by eureka.instance.* configuration keys, but the defaults will be +fine if you ensure that your application has a +spring.application.name (this is the default for the Eureka service +ID, or VIP). +See EurekaInstanceConfigBean and EurekaClientConfigBean for more details of the configurable options. +To disable the Eureka Discovery Client you can set eureka.client.enabled to false. +
+
+Authenticating with the Eureka Server +HTTP basic authentication will be automatically added to your eureka +client if one of the eureka.client.serviceUrl.defaultZone URLs has +credentials embedded in it (curl style, like +http://user:password@localhost:8761/eureka). For more complex needs +you can create a @Bean of type DiscoveryClientOptionalArgs and +inject ClientFilter instances into it, all of which will be applied +to the calls from the client to the server. + +Because of a limitation in Eureka it isn’t possible to support +per-server basic auth credentials, so only the first set that are +found will be used. + +
+
+Status Page and Health Indicator +The status page and health indicators for a Eureka instance default to +"/info" and "/health" respectively, which are the default locations of +useful endpoints in a Spring Boot Actuator application. You need to +change these, 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.contextPath=/admin). Example: + +application.yml + +eureka: + instance: + statusPageUrlPath: ${management.context-path}/info + healthCheckUrlPath: ${management.context-path}/health + + +These links show up in the metadata that is consumed by clients, and +used in some scenarios to decide whether to send requests to your +application, so it’s helpful if they are accurate. +
+
+Registering a Secure Application +If your app wants to be contacted over HTTPS you can set two flags in +the EurekaInstanceConfig, viz +eureka.instance.[nonSecurePortEnabled,securePortEnabled]=[false,true] +respectively. This will make Eureka publish instance information +showing an explicit preference for secure communication. The Spring +Cloud DiscoveryClient will always return a URI starting with https for a +service configured this way, and the Eureka (native) instance +information will have a secure health check URL. +Because of the way +Eureka works internally, it will still publish a non-secure URL for +status and home page unless you also override those explicitly. +You can use placeholders to configure the eureka instance urls, +e.g. + +application.yml + +eureka: + instance: + statusPageUrl: https://${eureka.hostname}/info + healthCheckUrl: https://${eureka.hostname}/health + homePageUrl: https://${eureka.hostname}/ + + +(Note that ${eureka.hostname} is a native placeholder only available +in later versions of Eureka. You could achieve the same thing with +Spring placeholders as well, e.g. using ${eureka.instance.hostName}.) + +If your app is running behind a proxy, and the SSL termination +is in the proxy (e.g. if you run in Cloud Foundry or other platforms +as a service) then you will need to ensure that the proxy "forwarded" +headers are intercepted and handled by the application. An embedded +Tomcat container in a Spring Boot app does this automatically if it +has explicit configuration for the 'X-Forwarded-\*` headers. A sign +that you got this wrong will be that the links rendered by your app to +itself will be wrong (the wrong host, port or protocol). + +
+
+Eureka’s Health Checks +By default, Eureka uses the client heartbeat to determine if a client is up. +Unless specified otherwise the Discovery Client will not propagate the +current health check status of the application per the Spring Boot Actuator. Which means +that after successful registration Eureka will always announce that the +application is in 'UP' state. This behaviour can be altered by enabling +Eureka health checks, which results in propagating application status +to Eureka. As a consequence every other application won’t be sending +traffic to application in state other then 'UP'. + +application.yml + +eureka: + client: + healthcheck: + enabled: true + + + +eureka.client.healthcheck.enabled=true should only be set in application.yml. Setting the value in bootstrap.yml will cause undesirable side effects like registering in eureka with an UNKNOWN status. + +If you require more control over the health checks, you may consider +implementing your own com.netflix.appinfo.HealthCheckHandler. +
+
+Eureka Metadata for Instances and Clients +It’s worth spending a bit of time understanding how the Eureka metadata works, so you can use it in a way that makes sense in your platform. There is standard metadata for things like hostname, IP address, port numbers, status page and health check. These are published in the service registry and used by clients to contact the services in a straightforward way. Additional metadata can be added to the instance registration in the eureka.instance.metadataMap, and this will be accessible in the remote clients, but in general will not change the behaviour of the client, unless it is made aware of the meaning of the metadata. There are a couple of special cases described below where Spring Cloud already assigns meaning to the metadata map. +
+Using Eureka on Cloudfoundry +Cloudfoundry has a global router so that all instances of the same app have the same hostname (it’s the same in other PaaS solutions with a similar architecture). This isn’t necessarily a barrier to using Eureka, but if you use the router (recommended, or even mandatory depending on the way your platform was set up), you need to explicitly set the hostname and port numbers (secure or non-secure) so that they use the router. You might also want to use instance metadata so you can distinguish between the instances on the client (e.g. in a custom load balancer). By default, the eureka.instance.instanceId is vcap.application.instance_id. For example: + +application.yml + +eureka: + instance: + hostname: ${vcap.application.uris[0]} + nonSecurePort: 80 + + +Depending on the way the security rules are set up in your Cloudfoundry instance, you might be able to register and use the IP address of the host VM for direct service-to-service calls. This feature is not (yet) available on Pivotal Web Services (PWS). +
+
+Using Eureka on AWS +If the application is planned to be deployed to an AWS cloud, then the Eureka instance will have to be configured to be AWS aware and this can be done by customizing the EurekaInstanceConfigBean the following way: +@Bean +@Profile("!default") +public EurekaInstanceConfigBean eurekaInstanceConfig(InetUtils inetUtils) { + EurekaInstanceConfigBean b = new EurekaInstanceConfigBean(inetUtils); + AmazonInfo info = AmazonInfo.Builder.newBuilder().autoBuild("eureka"); + b.setDataCenterInfo(info); + return b; +} +
+
+Changing the Eureka Instance ID +A vanilla Netflix Eureka instance is registered with an ID that is equal to its host name (i.e. only one service per host). Spring Cloud Eureka provides a sensible default that looks like this: ${spring.cloud.client.hostname}:${spring.application.name}:${spring.application.instance_id:${server.port}}}. For example myhost:myappname:8080. +Using Spring Cloud you can override this by providing a unique identifier in eureka.instance.instanceId. For example: + +application.yml + +eureka: + instance: + 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. +
+
+
+Using the EurekaClient +Once you have an app that is a discovery client you can use it to +discover service instances from the Eureka Server. One way to do that is to use the native +com.netflix.discovery.EurekaClient (as opposed to the Spring +Cloud DiscoveryClient), e.g. +@Autowired +private EurekaClient discoveryClient; + +public String serviceUrl() { + InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false); + return instance.getHomePageUrl(); +} + +Don’t use the EurekaClient in @PostConstruct method or in a +@Scheduled method (or anywhere where the ApplicationContext might +not be started yet). It is initialized in a SmartLifecycle (with +phase=0) so the earliest you can rely on it being available is in +another SmartLifecycle with higher phase. + +
+EurekaClient without Jersey +By default, EurekaClient uses Jersey for HTTP communication. If you wish +to avoid dependencies from Jersey, you can exclude it from your dependencies. +Spring Cloud will auto configure a transport client based on Spring +RestTemplate. +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> + <exclusions> + <exclusion> + <groupId>com.sun.jersey</groupId> + <artifactId>jersey-client</artifactId> + </exclusion> + <exclusion> + <groupId>com.sun.jersey</groupId> + <artifactId>jersey-core</artifactId> + </exclusion> + <exclusion> + <groupId>com.sun.jersey.contribs</groupId> + <artifactId>jersey-apache-client4</artifactId> + </exclusion> + </exclusions> +</dependency> +
+
+
+Alternatives to the native Netflix EurekaClient +You don’t have to use the raw Netflix EurekaClient and usually it +is more convenient to use it behind a wrapper of some sort. Spring +Cloud has support for Feign (a REST client +builder) and also Spring RestTemplate using +the logical Eureka service identifiers (VIPs) instead of physical +URLs. To configure Ribbon with a fixed list of physical servers you +can simply set <client>.ribbon.listOfServers to a comma-separated +list of physical addresses (or hostnames), where <client> is the ID +of the client. +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; +} +
+
+Why is it so Slow to Register a Service? +Being an instance also involves a periodic heartbeat to the registry +(via the client’s serviceUrl) with default duration 30 seconds. A +service is not available for discovery by clients until the instance, +the server and the client all have the same metadata in their local +cache (so it could take 3 heartbeats). You can change the period using +eureka.instance.leaseRenewalIntervalInSeconds and this will speed up +the process of getting clients connected to other services. In +production it’s probably better to stick with the default because +there are some computations internally in the server that make +assumptions about the lease renewal period. +
+
+Zones +If you have deployed Eureka clients to multiple zones than you may prefer that +those clients leverage services within the same zone before trying services +in another zone. To do this you need to configure your Eureka clients correctly. +First, you need to make sure you have Eureka servers deployed to each zone and that +they are peers of each other. See the section on zones and regions +for more information. +Next you need to tell Eureka which zone your service is in. You can do this using +the metadataMap property. For example if service 1 is deployed to both zone 1 +and zone 2 you would need to set the following Eureka properties in service 1 +Service 1 in Zone 1 +eureka.instance.metadataMap.zone = zone1 +eureka.client.preferSameZoneEureka = true +Service 1 in Zone 2 +eureka.instance.metadataMap.zone = zone2 +eureka.client.preferSameZoneEureka = true +
+
+ +Service Discovery: Eureka Server +
+How to Include Eureka Server +To include Eureka Server in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-eureka-server. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train. +
+
+How to Run a Eureka Server +Example eureka server; +@SpringBootApplication +@EnableEurekaServer +public class Application { + + public static void main(String[] args) { + new SpringApplicationBuilder(Application.class).web(true).run(args); + } + +} +The server has a home page with a UI, and HTTP API endpoints per the +normal Eureka functionality under /eureka/*. +Eureka background reading: see flux capacitor and google group discussion. + +Due to Gradle’s dependency resolution rules and the lack of a parent bom feature, simply depending on spring-cloud-starter-netflix-eureka-server can cause failures on application startup. To remedy this the Spring Boot Gradle plugin must be added and the Spring cloud starter parent bom must be imported like so: + +build.gradle + +buildscript { + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:{spring-boot-docs-version}") + } +} + +apply plugin: "spring-boot" + +dependencyManagement { + imports { + mavenBom "org.springframework.cloud:spring-cloud-dependencies:{spring-cloud-version}" + } +} + + + +
+
+High Availability, Zones and Regions +The Eureka server does not have a backend store, but the service +instances in the registry all have to send heartbeats to keep their +registrations up to date (so this can be done in memory). Clients also +have an in-memory cache of eureka registrations (so they don’t have to +go to the registry for every single request to a service). +By default every Eureka server is also a Eureka client and requires +(at least one) service URL to locate a peer. If you don’t provide it +the service will run and work, but it will shower your logs with a lot +of noise about not being able to register with the peer. +See also below for details of Ribbon +support on the client side for Zones and Regions. +
+
+Standalone Mode +The combination of the two caches (client and server) and the +heartbeats make a standalone Eureka server fairly resilient to +failure, as long as there is some sort of monitor or elastic runtime +keeping it alive (e.g. Cloud Foundry). In standalone mode, you might +prefer to switch off the client side behaviour, so it doesn’t keep +trying and failing to reach its peers. Example: + +application.yml (Standalone Eureka Server) + +server: + port: 8761 + +eureka: + instance: + hostname: localhost + client: + registerWithEureka: false + fetchRegistry: false + serviceUrl: + defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ + + +Notice that the serviceUrl is pointing to the same host as the local +instance. +
+
+Peer Awareness +Eureka can be made even more resilient and available by running +multiple instances and asking them to register with each other. In +fact, this is the default behaviour, so all you need to do to make it +work is add a valid serviceUrl to a peer, e.g. + +application.yml (Two Peer Aware Eureka Servers) + +--- +spring: + profiles: peer1 +eureka: + instance: + hostname: peer1 + client: + serviceUrl: + defaultZone: http://peer2/eureka/ + +--- +spring: + profiles: peer2 +eureka: + instance: + hostname: peer2 + client: + serviceUrl: + defaultZone: http://peer1/eureka/ + + +In this example we have a YAML file that can be used to run the same +server on 2 hosts (peer1 and peer2), by running it in different +Spring profiles. You could use this configuration to test the peer +awareness on a single host (there’s not much value in doing that in +production) by manipulating /etc/hosts to resolve the host names. In +fact, the eureka.instance.hostname is not needed if you are running +on a machine that knows its own hostname (it is looked up using +java.net.InetAddress by default). +You can add multiple peers to a system, and as long as they are all +connected to each other by at least one edge, they will synchronize +the registrations amongst themselves. If the peers are physically +separated (inside a data centre or between multiple data centres) then +the system can in principle survive split-brain type failures. +
+
+Prefer IP Address +In some cases, it is preferable for Eureka to advertise the IP Adresses +of services rather than the hostname. Set eureka.instance.preferIpAddress +to true and when the application registers with eureka, it will use its +IP Address rather than its hostname. + +If hostname can’t be determined by Java, then IP address is sent to Eureka. +Only explict way of setting hostname is by using eureka.instance.hostname. +You can set your hostname at the run time using environment variable, for +example eureka.instance.hostname=${HOST_NAME}. + +
+
+ +Circuit Breaker: Hystrix Clients +Netflix has created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture it is common to have multiple layers of service calls. +
+Microservice Graph + + + + +Hystrix + +
+A service failure in the lower level of services can cause cascading failure all the way up to the user. When calls to a particular service is greater than circuitBreaker.requestVolumeThreshold (default: 20 requests) and failue percentage is greater than circuitBreaker.errorThresholdPercentage (default: >50%) in a rolling window defined by metrics.rollingStats.timeInMilliseconds (default: 10 seconds), the circuit opens and the call is not made. In cases of error and an open circuit a fallback can be provided by the developer. +
+Hystrix fallback prevents cascading failures + + + + +HystrixFallback + +
+Having an open circuit stops cascading failures and allows overwhelmed or failing services time to heal. The fallback can be another Hystrix protected call, static data or a sane empty value. Fallbacks may be chained so the first fallback makes some other business call which in turn falls back to static data. +
+How to Include Hystrix +To include Hystrix in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-hystrix. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train. +Example boot app: +@SpringBootApplication +@EnableCircuitBreaker +public class Application { + + public static void main(String[] args) { + new SpringApplicationBuilder(Application.class).web(true).run(args); + } + +} + +@Component +public class StoreIntegration { + + @HystrixCommand(fallbackMethod = "defaultStores") + public Object getStores(Map<String, Object> parameters) { + //do stuff that might fail + } + + public Object defaultStores(Map<String, Object> parameters) { + return /* something useful */; + } +} +The @HystrixCommand is provided by a Netflix contrib library called +"javanica". +Spring Cloud automatically wraps Spring beans with that +annotation in a proxy that is connected to the Hystrix circuit +breaker. The circuit breaker calculates when to open and close the +circuit, and what to do in case of a failure. +To configure the @HystrixCommand you can use the commandProperties +attribute with a list of @HystrixProperty annotations. See +here +for more details. See the Hystrix wiki +for details on the properties available. +
+
+Propagating the Security Context or using Spring Scopes +If you want some thread local context to propagate into a @HystrixCommand the default declaration will not work because it executes the command in a thread pool (in case of timeouts). You can switch Hystrix to use the same thread as the caller using some configuration, or directly in the annotation, by asking it to use a different "Isolation Strategy". For example: +@HystrixCommand(fallbackMethod = "stubMyService", + commandProperties = { + @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE") + } +) +... +The same thing applies if you are using @SessionScope or @RequestScope. You will know when you need to do this because of a runtime exception that says it can’t find the scoped context. +You also have the option to set the hystrix.shareSecurityContext property to true. Doing so will auto configure an Hystrix concurrency strategy plugin hook who will transfer the SecurityContext from your main thread to the one used by the Hystrix command. Hystrix does not allow multiple hystrix concurrency strategy to be registered so an extension mechanism is available by declaring your own HystrixConcurrencyStrategy as a Spring bean. Spring Cloud will lookup for your implementation within the Spring context and wrap it inside its own plugin. +
+
+Health Indicator +The state of the connected circuit breakers are also exposed in the +/health endpoint of the calling application. +{ + "hystrix": { + "openCircuitBreakers": [ + "StoreIntegration::getStoresByLocationLink" + ], + "status": "CIRCUIT_OPEN" + }, + "status": "UP" +} +
+
+Hystrix Metrics Stream +To enable the Hystrix metrics stream include a dependency on spring-boot-starter-actuator. This will expose the /hystrix.stream as a management endpoint. + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-actuator</artifactId> + </dependency> +
+
+ +Circuit Breaker: Hystrix Dashboard +One of the main benefits of Hystrix is the set of metrics it gathers about each HystrixCommand. The Hystrix Dashboard displays the health of each circuit breaker in an efficient manner. +
+Hystrix Dashboard + + + + +Hystrix + +
+
+ +Hystrix Timeouts And Ribbon Clients +When using Hystrix commands that wrap Ribbon clients you want to make sure your Hystrix timeout +is configured to be longer than the configured Ribbon timeout, including any potential +retries that might be made. For example, if your Ribbon connection timeout is one second and +the Ribbon client might retry the request three times, than your Hystrix timeout should +be slightly more than three seconds. +
+How to Include Hystrix Dashboard +To include the Hystrix Dashboard in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-hystrix-dashboard. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train. +To run the Hystrix Dashboard annotate your Spring Boot main class with @EnableHystrixDashboard. You then visit /hystrix and point the dashboard to an individual instances /hystrix.stream endpoint in a Hystrix client application. + +When connecting to a /hystrix.stream endpoint which uses HTTPS the certificate used by the server +must be trusted by the JVM. If the certificate is not trusted you must import the certificate into the JVM +in order for the Hystrix Dashboard to make a successful connection to the stream endpoint. + +
+
+Turbine +Looking at an individual instances Hystrix data is not very useful in terms of the overall health of the system. Turbine is an application that aggregates all of the relevant /hystrix.stream endpoints into a combined /turbine.stream for use in the Hystrix Dashboard. Individual instances are located via Eureka. Running Turbine is as simple as annotating your main class with the @EnableTurbine annotation (e.g. using spring-cloud-starter-netflix-turbine to set up the classpath). All of the documented configuration properties from the Turbine 1 wiki apply. The only difference is that the turbine.instanceUrlSuffix does not need the port prepended as this is handled automatically unless turbine.instanceInsertPort=false. + +By default, Turbine looks for the /hystrix.stream endpoint on a registered instance by looking up its hostName and port entries in Eureka, then appending /hystrix.stream to it. +If the instance’s metadata contains management.port, it will be used instead of the port value for the /hystrix.stream endpoint. +By default, metadata entry management.port is equal to the management.port configuration property, it can be overridden though with following configuration: + +eureka: + instance: + metadata-map: + management.port: ${management.port:8081} +The configuration key turbine.appConfig is a list of eureka serviceIds that turbine will use to lookup instances. The turbine stream is then used in the Hystrix dashboard using a url that looks like: http://my.turbine.server:8080/turbine.stream?cluster=CLUSTERNAME (the cluster parameter can be omitted if the name is "default"). The cluster parameter must match an entry in turbine.aggregator.clusterConfig. Values returned from eureka are uppercase, thus we expect this example to work if there is an app registered with Eureka called "customers": +turbine: + aggregator: + clusterConfig: CUSTOMERS + appConfig: customers +If you need to customize which cluster names should be used by Turbine (you don’t want to store cluster names in +turbine.aggregator.clusterConfig configuration) provide a bean of type TurbineClustersProvider. +The clusterName can be customized by a SPEL expression in turbine.clusterNameExpression with root an instance of InstanceInfo. The default value is appName, which means that the Eureka serviceId ends up as the cluster key (i.e. the InstanceInfo for customers has an appName of "CUSTOMERS"). A different example would be turbine.clusterNameExpression=aSGName, which would get the cluster name from the AWS ASG name. Another example: +turbine: + aggregator: + clusterConfig: SYSTEM,USER + appConfig: customers,stores,ui,admin + clusterNameExpression: metadata['cluster'] +In this case, the cluster name from 4 services is pulled from their metadata map, and is expected to have values that include "SYSTEM" and "USER". +To use the "default" cluster for all apps you need a string literal expression (with single quotes, and escaped with double quotes if it is in YAML as well): +turbine: + appConfig: customers,stores + clusterNameExpression: "'default'" +Spring Cloud provides a spring-cloud-starter-netflix-turbine that has all the dependencies you need to get a Turbine server running. Just create a Spring Boot application and annotate it with @EnableTurbine. + +by default Spring Cloud allows Turbine to use the host and port to allow multiple processes per host, per cluster. If you want the native Netflix behaviour built into Turbine that does not allow multiple processes per host, per cluster (the key to the instance id is the hostname), then set the property turbine.combineHostPort=false. + +
+
+Turbine Stream +In some environments (e.g. in a PaaS setting), the classic Turbine model of pulling metrics from all the distributed Hystrix commands doesn’t work. In that case you might want to have your Hystrix commands push metrics to Turbine, and Spring Cloud enables that with messaging. All you need to do on the client is add a dependency to spring-cloud-netflix-hystrix-stream and the spring-cloud-starter-stream-* of your choice (see Spring Cloud Stream documentation for details on the brokers, and how to configure the client credentials, but it should work out of the box for a local broker). +On the server side Just create a Spring Boot application and annotate it with @EnableTurbineStream and by default it will come up on port 8989 (point your Hystrix dashboard to that port, any path). You can customize the port using either server.port or turbine.stream.port. If you have spring-boot-starter-web and spring-boot-starter-actuator on the classpath as well, then you can open up the Actuator endpoints on a separate port (with Tomcat by default) by providing a management.port which is different. +You can then point the Hystrix Dashboard to the Turbine Stream Server instead of individual Hystrix streams. If Turbine Stream is running on port 8989 on myhost, then put http://myhost:8989 in the stream input field in the Hystrix Dashboard. Circuits will be prefixed by their respective serviceId, followed by a dot, then the circuit name. +Spring Cloud provides a spring-cloud-starter-netflix-turbine-stream that has all the dependencies you need to get a Turbine Stream server running - just add the Stream binder of your choice, e.g. spring-cloud-starter-stream-rabbit. You need Java 8 to run the app because it is Netty-based. +
+
+ +Client Side Load Balancer: Ribbon +Ribbon is a client side load balancer which gives you a lot of control +over the behaviour of HTTP and TCP clients. Feign already uses Ribbon, +so if you are using @FeignClient then this section also applies. +A central concept in Ribbon is that of the named client. Each load +balancer is part of an ensemble of components that work together to +contact a remote server on demand, and the ensemble has a name that +you give it as an application developer (e.g. using the @FeignClient +annotation). Spring Cloud creates a new ensemble as an +ApplicationContext on demand for each named client using +RibbonClientConfiguration. This contains (amongst other things) an +ILoadBalancer, a RestClient, and a ServerListFilter. +
+How to Include Ribbon +To include Ribbon in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-ribbon. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train. +
+
+Customizing the Ribbon Client +You can configure some bits of a Ribbon client using external +properties in <client>.ribbon.*, which is no different than using +the Netflix APIs natively, except that you can use Spring Boot +configuration files. The native options can +be inspected as static fields in CommonClientConfigKey (part of +ribbon-core). +Spring Cloud also lets you take full control of the client by +declaring additional configuration (on top of the +RibbonClientConfiguration) using @RibbonClient. Example: +@Configuration +@RibbonClient(name = "foo", configuration = FooConfiguration.class) +public class TestConfiguration { +} +In this case the client is composed from the components already in +RibbonClientConfiguration together with any in FooConfiguration +(where the latter generally will override the former). + +The FooConfiguration has to be @Configuration but take +care that it is not in a @ComponentScan for the main application +context, otherwise it will be shared by all the @RibbonClients. If +you use @ComponentScan (or @SpringBootApplication) you need to +take steps to avoid it being included (for instance put it in a +separate, non-overlapping package, or specify the packages to scan +explicitly in the @ComponentScan). + +Spring Cloud Netflix provides the following beans by default for ribbon +(BeanType beanName: ClassName): + + +IClientConfig ribbonClientConfig: DefaultClientConfigImpl + + +IRule ribbonRule: ZoneAvoidanceRule + + +IPing ribbonPing: DummyPing + + +ServerList<Server> ribbonServerList: ConfigurationBasedServerList + + +ServerListFilter<Server> ribbonServerListFilter: ZonePreferenceServerListFilter + + +ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer + + +ServerListUpdater ribbonServerListUpdater: PollingServerListUpdater + + +Creating a bean of one of those type and placing it in a @RibbonClient +configuration (such as FooConfiguration above) allows you to override each +one of the beans described. Example: +@Configuration +protected static class FooConfiguration { + @Bean + public ZonePreferenceServerListFilter serverListFilter() { + ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter(); + filter.setZone("myTestZone"); + return filter; + } + + @Bean + public IPing ribbonPing() { + return new PingUrl(); + } +} +This replaces the NoOpPing with PingUrl and provides a custom serverListFilter +
+
+Customizing default for all Ribbon Clients +A default configuration can be provided for all Ribbon Clients using the @RibbonClients annotation and registering a default configuration as shown in the following example: +@RibbonClients(defaultConfiguration = DefaultRibbonConfig.class) +public class RibbonClientDefaultConfigurationTestsConfig { + + public static class BazServiceList extends ConfigurationBasedServerList { + public BazServiceList(IClientConfig config) { + super.initWithNiwsConfig(config); + } + } +} + +@Configuration +class DefaultRibbonConfig { + + @Bean + public IRule ribbonRule() { + return new BestAvailableRule(); + } + + @Bean + public IPing ribbonPing() { + return new PingUrl(); + } + + @Bean + public ServerList<Server> ribbonServerList(IClientConfig config) { + return new RibbonClientDefaultConfigurationTestsConfig.BazServiceList(config); + } + + @Bean + public ServerListSubsetFilter serverListFilter() { + ServerListSubsetFilter filter = new ServerListSubsetFilter(); + return filter; + } + +} +
+
+Customizing the Ribbon Client using properties +Starting with version 1.2.0, Spring Cloud Netflix now supports customizing Ribbon clients using properties to be compatible with the Ribbon documentation. +This allows you to change behavior at start up time in different environments. +The supported properties are listed below and should be prefixed by <clientName>.ribbon.: + + +NFLoadBalancerClassName: should implement ILoadBalancer + + +NFLoadBalancerRuleClassName: should implement IRule + + +NFLoadBalancerPingClassName: should implement IPing + + +NIWSServerListClassName: should implement ServerList + + +NIWSServerListFilterClassName should implement ServerListFilter + + + +Classes defined in these properties have precedence over beans defined using @RibbonClient(configuration=MyRibbonConfig.class) and the defaults provided by Spring Cloud Netflix. + +To set the IRule for a service name users you could set the following: + +application.yml + +users: + ribbon: + NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList + NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule + + +See the Ribbon documentation for implementations provided by Ribbon. +
+
+Using Ribbon with Eureka +When Eureka is used in conjunction with Ribbon (i.e., both are on the classpath) the ribbonServerList +is overridden with an extension of DiscoveryEnabledNIWSServerList +which populates the list of servers from Eureka. It also replaces the +IPing interface with NIWSDiscoveryPing which delegates to Eureka +to determine if a server is up. The ServerList that is installed by +default is a DomainExtractingServerList and the purpose of this is +to make physical metadata available to the load balancer without using +AWS AMI metadata (which is what Netflix relies on). By default the +server list will be constructed with "zone" information as provided in +the instance metadata (so on the remote clients set +eureka.instance.metadataMap.zone), and if that is missing it can use +the domain name from the server hostname as a proxy for zone (if the +flag approximateZoneFromHostname is set). Once the zone information +is available it can be used in a ServerListFilter. By default it +will be used to locate a server in the same zone as the client because +the default is a ZonePreferenceServerListFilter. The zone of the +client is determined the same way as the remote instances by default, +i.e. via eureka.instance.metadataMap.zone. + +The orthodox "archaius" way to set the client zone is via a +configuration property called "@zone", and Spring Cloud will use that +in preference to all other settings if it is available (note that the +key will have to be quoted in YAML configuration). + + +If there is no other source of zone data then a guess is made +based on the client configuration (as opposed to the instance +configuration). We take eureka.client.availabilityZones, which is a +map from region name to a list of zones, and pull out the first zone +for the instance’s own region (i.e. the eureka.client.region, which +defaults to "us-east-1" for comatibility with native Netflix). + +
+
+Example: How to Use Ribbon Without Eureka +Eureka is a convenient way to abstract the discovery of remote servers +so you don’t have to hard code their URLs in clients, but if you +prefer not to use it, Ribbon and Feign are still quite +amenable. Suppose you have declared a @RibbonClient for "stores", +and Eureka is not in use (and not even on the classpath). The Ribbon +client defaults to a configured server list, and you can supply the +configuration like this + +application.yml + +stores: + ribbon: + listOfServers: example.com,google.com + + +
+
+Example: Disable Eureka use in Ribbon +Setting the property ribbon.eureka.enabled = false will explicitly +disable the use of Eureka in Ribbon. + +application.yml + +ribbon: + eureka: + enabled: false + + +
+
+Using the Ribbon API Directly +You can also use the LoadBalancerClient directly. Example: +public class MyClass { + @Autowired + private LoadBalancerClient loadBalancer; + + public void doStuff() { + ServiceInstance instance = loadBalancer.choose("stores"); + URI storesUri = URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort())); + // ... do something with the URI + } +} +
+
+Caching of Ribbon Configuration +Each Ribbon named client has a corresponding child Application Context that Spring Cloud maintains, this application context is lazily loaded up on the first request to the named client. +This lazy loading behavior can be changed to instead eagerly load up these child Application contexts at startup by specifying the names of the Ribbon clients. + +application.yml + +ribbon: + eager-load: + enabled: true + clients: client1, client2, client3 + + +
+
+How to Configure Hystrix thread pools +If you change zuul.ribbonIsolationStrategy to THREAD, the thread isolation strategy for Hystrix will be used for all routes. In this case, the HystrixThreadPoolKey is set to "RibbonCommand" as default. It means that HystrixCommands for all routes will be executed in the same Hystrix thread pool. This behavior can be changed using the following configuration and it will result in HystrixCommands being executed in the Hystrix thread pool for each route. + +application.yml + +zuul: + threadPool: + useSeparateThreadPools: true + + +The default HystrixThreadPoolKey in this case is same with service ID for each route. To add a prefix to HystrixThreadPoolKey, set zuul.threadPool.threadPoolKeyPrefix to a value that you want to add. For example: + +application.yml + +zuul: + threadPool: + useSeparateThreadPools: true + threadPoolKeyPrefix: zuulgw + + +
+
+How to Provide a Key to Ribbon’s <literal>IRule</literal> +If you need to provide your own IRule implementation to handle a special routing requirement like a canary test, +you probably want to pass some information to the choose method of IRule. + +com.netflix.loadbalancer.IRule.java + +public interface IRule{ + public Server choose(Object key); + : + + +You can provide some information that will be used to choose a target server by your IRule implementation like +the following: +RequestContext.getCurrentContext() + .set(FilterConstants.LOAD_BALANCER_KEY, "canary-test"); +If you put any object into the RequestContext with a key FilterConstants.LOAD_BALANCER_KEY, it will +be passed to the choose method of IRule implementation. Above code must be executed before RibbonRoutingFilter +is executed and Zuul’s pre filter is the best place to do that. You can easily access HTTP headers and query parameters +via RequestContext in pre filter, so it can be used to determine LOAD_BALANCER_KEY that will be passed to Ribbon. +If you don’t put any value with LOAD_BALANCER_KEY in RequestContext, null will be passed as a parameter of choose +method. +
+
+ +External Configuration: Archaius +Archaius is the Netflix client side configuration library. It is the library used by all of the Netflix OSS components for configuration. Archaius is an extension of the Apache Commons Configuration project. It allows updates to configuration by either polling a source for changes or for a source to push changes to the client. Archaius uses Dynamic<Type>Property classes as handles to properties. + +Archaius Example + +class ArchaiusTest { + DynamicStringProperty myprop = DynamicPropertyFactory + .getInstance() + .getStringProperty("my.prop"); + + void doSomething() { + OtherClass.someMethod(myprop.get()); + } +} + + +Archaius has its own set of configuration files and loading priorities. Spring applications should generally not use Archaius directly, but the need to configure the Netflix tools natively remains. Spring Cloud has a Spring Environment Bridge so Archaius can read properties from the Spring Environment. This allows Spring Boot projects to use the normal configuration toolchain, while allowing them to configure the Netflix tools, for the most part, as documented. + + +Router and Filter: Zuul +Routing is an integral part of a microservice architecture. For example, / may be mapped to your web application, /api/users is mapped to the user service and /api/shop is mapped to the shop service. Zuul is a JVM based router and server side load balancer by Netflix. +Netflix uses Zuul for the following: + + +Authentication + + +Insights + + +Stress Testing + + +Canary Testing + + +Dynamic Routing + + +Service Migration + + +Load Shedding + + +Security + + +Static Response handling + + +Active/Active traffic management + + +Zuul’s rule engine allows rules and filters to be written in essentially any JVM language, with built in support for Java and Groovy. + +The configuration property zuul.max.host.connections has been replaced by two new properties, zuul.host.maxTotalConnections and zuul.host.maxPerRouteConnections which default to 200 and 20 respectively. + + +Default Hystrix isolation pattern (ExecutionIsolationStrategy) for all routes is SEMAPHORE. zuul.ribbonIsolationStrategy can be changed to THREAD if this isolation pattern is preferred. + +
+How to Include Zuul +To include Zuul in your project use the starter with group org.springframework.cloud +and artifact id spring-cloud-starter-netflix-zuul. See the Spring Cloud Project page +for details on setting up your build system with the current Spring Cloud Release Train. +
+
+Embedded Zuul Reverse Proxy +Spring Cloud has created an embedded Zuul proxy to ease the +development of a very common use case where a UI application wants to +proxy calls to one or more back end services. This feature is useful +for a user interface to proxy to the backend services it requires, +avoiding the need to manage CORS and authentication concerns +independently for all the backends. +To enable it, annotate a Spring Boot main class with +@EnableZuulProxy, and this forwards local calls to the appropriate +service. By convention, a service with the ID "users", will +receive requests from the proxy located at /users (with the prefix +stripped). The proxy uses Ribbon to locate an instance to forward to +via discovery, and all requests are executed in a +hystrix command, so +failures will show up in Hystrix metrics, and once the circuit is open +the proxy will not try to contact the service. + +the Zuul starter does not include a discovery client, so for +routes based on service IDs you need to provide one of those +on the classpath as well (e.g. Eureka is one choice). + +To skip having a service automatically added, set +zuul.ignored-services to a list of service id patterns. If a service +matches a pattern that is ignored, but also included in the explicitly +configured routes map, then it will be unignored. Example: + +application.yml + + zuul: + ignoredServices: '*' + routes: + users: /myusers/** + + +In this example, all services are ignored except "users". +To augment or change +the proxy routes, you can add external configuration like the +following: + +application.yml + + zuul: + routes: + users: /myusers/** + + +This means that http calls to "/myusers" get forwarded to the "users" +service (for example "/myusers/101" is forwarded to "/101"). +To get more fine-grained control over a route you can specify the path +and the serviceId independently: + +application.yml + + zuul: + routes: + users: + path: /myusers/** + serviceId: users_service + + +This means that http calls to "/myusers" get forwarded to the +"users_service" service. The route has to have a "path" which can be +specified as an ant-style pattern, so "/myusers/*" only matches one +level, but "/myusers/**" matches hierarchically. +The location of the backend can be specified as either a "serviceId" +(for a service from discovery) or a "url" (for a physical location), e.g. + +application.yml + + zuul: + routes: + users: + path: /myusers/** + url: http://example.com/users_service + + +These simple url-routes don’t get executed as a HystrixCommand nor do they loadbalance multiple URLs with Ribbon. +To achieve this, you can specify a serviceId with a static list of servers: + +application.yml + +zuul: + routes: + echo: + path: /myusers/** + serviceId: myusers-service + stripPrefix: true + +hystrix: + command: + myusers-service: + execution: + isolation: + thread: + timeoutInMilliseconds: ... + +myusers-service: + ribbon: + NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList + ListOfServers: http://example1.com,http://example2.com + ConnectTimeout: 1000 + ReadTimeout: 3000 + MaxTotalHttpConnections: 500 + MaxConnectionsPerHost: 100 + + +Another method is specifiying a service-route and configure a Ribbon client for the +serviceId (this requires disabling Eureka support in Ribbon: +see above for more information), e.g. + +application.yml + +zuul: + routes: + users: + path: /myusers/** + serviceId: users + +ribbon: + eureka: + enabled: false + +users: + ribbon: + listOfServers: example.com,google.com + + +You can provide convention between serviceId and routes using +regexmapper. It uses regular expression named groups to extract +variables from serviceId and inject them into a route pattern. + +ApplicationConfiguration.java + +@Bean +public PatternServiceRouteMapper serviceRouteMapper() { + return new PatternServiceRouteMapper( + "(?<name>^.+)-(?<version>v.+$)", + "${version}/${name}"); +} + + +This means that a serviceId "myusers-v1" will be mapped to route +"/v1/myusers/**". Any regular expression is accepted but all named +groups must be present in both servicePattern and routePattern. If +servicePattern does not match a serviceId, the default behavior is +used. In the example above, a serviceId "myusers" will be mapped to route +"/myusers/**" (no version detected) This feature is disabled by +default and only applies to discovered services. +To add a prefix to all mappings, set zuul.prefix to a value, such as +/api. The proxy prefix is stripped from the request before the +request is forwarded by default (switch this behaviour off with +zuul.stripPrefix=false). You can also switch off the stripping of +the service-specific prefix from individual routes, e.g. + +application.yml + + zuul: + routes: + users: + path: /myusers/** + stripPrefix: false + + + +zuul.stripPrefix only applies to the prefix set in zuul.prefix. It does not have any effect on prefixes +defined within a given route’s path. + +In this example, requests to "/myusers/101" will be forwarded to "/myusers/101" on the "users" service. +The zuul.routes entries actually bind to an object of type ZuulProperties. If you +look at the properties of that object you will see that it also has a "retryable" flag. +Set that flag to "true" to have the Ribbon client automatically retry failed requests +(and if you need to you can modify the parameters of the retry operations using +the Ribbon client configuration). +The X-Forwarded-Host header is added to the forwarded requests by +default. To turn it off set zuul.addProxyHeaders = false. The +prefix path is stripped by default, and the request to the backend +picks up a header "X-Forwarded-Prefix" ("/myusers" in the examples +above). +An application with @EnableZuulProxy could act as a standalone +server if you set a default route ("/"), for example zuul.route.home: +/ would route all traffic (i.e. "/**") to the "home" service. +If more fine-grained ignoring is needed, you can specify specific patterns to ignore. +These patterns are evaluated at the start of the route location process, which +means prefixes should be included in the pattern to warrant a match. Ignored patterns +span all services and supersede any other route specification. + +application.yml + + zuul: + ignoredPatterns: /**/admin/** + routes: + users: /myusers/** + + +This means that all calls such as "/myusers/101" will be forwarded to "/101" on the "users" service. +But calls including "/admin/" will not resolve. + +If you need your routes to have their order preserved you need to use a YAML +file as the ordering will be lost using a properties file. For example: + + +application.yml + + zuul: + routes: + users: + path: /myusers/** + legacy: + path: /** + + +If you were to use a properties file, the legacy path may end up in front of the users +path rendering the users path unreachable. +
+
+Zuul Http Client +The default HTTP client used by zuul is now backed by the Apache HTTP Client instead of the +deprecated Ribbon RestClient. To use RestClient or to use the okhttp3.OkHttpClient set +ribbon.restclient.enabled=true or ribbon.okhttp.enabled=true respectively. If you would +like to customize the Apache HTTP client or the OK HTTP client provide a bean of type +ClosableHttpClient or OkHttpClient. +
+
+Cookies and Sensitive Headers +It’s OK to share headers between services in the same system, but you +probably don’t want sensitive headers leaking downstream into external +servers. You can specify a list of ignored headers as part of the +route configuration. Cookies play a special role because they have +well-defined semantics in browsers, and they are always to be treated +as sensitive. If the consumer of your proxy is a browser, then cookies +for downstream services also cause problems for the user because they +all get jumbled up (all downstream services look like they come from +the same place). +If you are careful with the design of your services, for example if +only one of the downstream services sets cookies, then you might be +able to let them flow from the backend all the way up to the +caller. Also, if your proxy sets cookies and all your back end +services are part of the same system, it can be natural to simply +share them (and for instance use Spring Session to link them up to some +shared state). Other than that, any cookies that get set by downstream +services are likely to be not very useful to the caller, so it is +recommended that you make (at least) "Set-Cookie" and "Cookie" into +sensitive headers for routes that are not part of your domain. Even +for routes that are part of your domain, try to think carefully +about what it means before allowing cookies to flow between them and +the proxy. +The sensitive headers can be configured as a comma-separated list per +route, e.g. + +application.yml + + zuul: + routes: + users: + path: /myusers/** + sensitiveHeaders: Cookie,Set-Cookie,Authorization + url: https://downstream + + + +this is the default value for sensitiveHeaders, so you don’t +need to set it unless you want it to be different. N.B. this is new in +Spring Cloud Netflix 1.1 (in 1.0 the user had no control over headers +and all cookies flow in both directions). + +The sensitiveHeaders are a blacklist and the default is not empty, +so to make Zuul send all headers (except the "ignored" ones) you would +have to explicitly set it to the empty list. This is necessary if you +want to pass cookie or authorization headers to your back end. Example: + +application.yml + + zuul: + routes: + users: + path: /myusers/** + sensitiveHeaders: + url: https://downstream + + +Sensitive headers can also be set globally by setting zuul.sensitiveHeaders. If sensitiveHeaders is set on a route, this will override the global sensitiveHeaders setting. +
+
+Ignored Headers +In addition to the per-route sensitive headers, you can set a global +value for zuul.ignoredHeaders for values that should be discarded +(both request and response) during interactions with downstream +services. By default these are empty, if Spring Security is not on the +classpath, and otherwise they are initialized to a set of well-known +"security" headers (e.g. involving caching) as specified by Spring +Security. The assumption in this case is that the downstream services +might add these headers too, and we want the values from the proxy. +To not discard these well known security headers in case Spring Security is on the classpath you can set zuul.ignoreSecurityHeaders to false. This can be useful if you disabled the HTTP Security response headers in Spring Security and want the values provided by downstream services +
+
+Management Endpoints +If you are using @EnableZuulProxy with the Spring Boot Actuator you +will enable (by default) two additional endpoints: + + +Routes + + +Filters + + +
+Routes Endpoint +A GET to the routes endpoint at /routes will return a list of the mapped +routes: + +GET /routes + +{ + /stores/**: "http://localhost:8081" +} + + +Additional route details can be requested through the /routes/details endpoint. This will produce the following output: + +GET /routes/details + +{ + "/stores/**": { + "id": "stores", + "fullPath": "/stores/**", + "location": "http://localhost:8081", + "path": "/**", + "prefix": "/stores", + "retryable": false, + "customSensitiveHeaders": false, + "prefixStripped": true + } +} + + +A POST to /routes will force a refresh of the existing routes (e.g. in +case there have been changes in the service catalog). You can disable +this endpoint by setting endpoints.routes.enabled to false. + +the routes should respond automatically to changes in the +service catalog, but the POST to /routes is a way to force the change +to happen immediately. + +
+
+Filters Endpoint +A GET to the filters endpoint at /filters will return a map of Zuul +filters by type. For each filter type in the map, you will find a list +of all the filters of that type, along with their details. +
+
+
+Strangulation Patterns and Local Forwards +A common pattern when migrating an existing application or API is to +"strangle" old endpoints, slowly replacing them with different +implementations. The Zuul proxy is a useful tool for this because you +can use it to handle all traffic from clients of the old endpoints, +but redirect some of the requests to new ones. +Example configuration: + +application.yml + + zuul: + routes: + first: + path: /first/** + url: http://first.example.com + second: + path: /second/** + url: forward:/second + third: + path: /third/** + url: forward:/3rd + legacy: + path: /** + url: http://legacy.example.com + + +In this example we are strangling the "legacy" app which is mapped to +all requests that do not match one of the other patterns. Paths in +/first/** have been extracted into a new service with an external +URL. And paths in /second/** are forwarded so they can be handled +locally, e.g. with a normal Spring @RequestMapping. Paths in +/third/** are also forwarded, but with a different prefix +(i.e. /third/foo is forwarded to /3rd/foo). + +The ignored patterns aren’t completely ignored, they just +aren’t handled by the proxy (so they are also effectively forwarded +locally). + +
+
+Uploading Files through Zuul +If you use @EnableZuulProxy, you can use the proxy paths to +upload files and it should just work as long as the files +are small. For large files there is an alternative path +which bypasses the Spring DispatcherServlet (to +avoid multipart processing) in "/zuul/*". I.e. if +zuul.routes.customers=/customers/** then you can +POST large files to "/zuul/customers/*". The servlet +path is externalized via zuul.servletPath. Extremely +large files will also require elevated timeout settings +if the proxy route takes you through a Ribbon load +balancer, e.g. + +application.yml + +hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000 +ribbon: + ConnectTimeout: 3000 + ReadTimeout: 60000 + + +Note that for streaming to work with large files, you need to use chunked encoding in the request (which some browsers +do not do by default). E.g. on the command line: +$ curl -v -H "Transfer-Encoding: chunked" \ + -F "file=@mylarge.iso" localhost:9999/zuul/simple/file +
+
+Query String Encoding +When processing the incoming request, query params are decoded so they can be available for possible modifications in +Zuul filters. They are then re-encoded when building the backend request in the route filters. The result +can be different than the original input if it was encoded using Javascript’s encodeURIComponent() method for example. +While this causes no issues in most cases, some web servers can be picky with the encoding of complex query string. +To force the original encoding of the query string, it is possible to pass a special flag to ZuulProperties so +that the query string is taken as is with the HttpServletRequest::getQueryString method : + +application.yml + + zuul: + forceOriginalQueryStringEncoding: true + + +Note: This special flag only works with SimpleHostRoutingFilter and you loose the ability to easily override +query parameters with RequestContext.getCurrentContext().setRequestQueryParams(someOverriddenParameters) since +the query string is now fetched directly on the original HttpServletRequest. +
+
+Plain Embedded Zuul +You can also run a Zuul server without the proxying, or switch on parts of the proxying platform selectively, if you +use @EnableZuulServer (instead of @EnableZuulProxy). Any beans that you add to the application of type ZuulFilter +will be installed automatically, as they are with @EnableZuulProxy, but without any of the proxy filters being added +automatically. +In this case the routes into the Zuul server are still specified by +configuring "zuul.routes.*", but there is no service +discovery and no proxying, so the "serviceId" and "url" settings are +ignored. For example: + +application.yml + + zuul: + routes: + api: /api/** + + +maps all paths in "/api/**" to the Zuul filter chain. +
+
+Disable Zuul Filters +Zuul for Spring Cloud comes with a number of ZuulFilter beans enabled by default +in both proxy and server mode. See the zuul filters package for the +possible filters that are enabled. If you want to disable one, simply set +zuul.<SimpleClassName>.<filterType>.disable=true. By convention, the package after +filters is the Zuul filter type. For example to disable +org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter set +zuul.SendResponseFilter.post.disable=true. +
+
+Providing Hystrix Fallbacks For Routes +When a circuit for a given route in Zuul is tripped you can provide a fallback response +by creating a bean of type FallbackProvider. Within this bean you need to specify +the route ID the fallback is for and provide a ClientHttpResponse to return +as a fallback. Here is a very simple FallbackProvider implementation. +class MyFallbackProvider implements FallbackProvider { + + @Override + public String getRoute() { + return "customers"; + } + + @Override + public ClientHttpResponse fallbackResponse(String route, final Throwable cause) { + if (cause instanceof HystrixTimeoutException) { + return response(HttpStatus.GATEWAY_TIMEOUT); + } else { + return response(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + private ClientHttpResponse response(final HttpStatus status) { + return new ClientHttpResponse() { + @Override + public HttpStatus getStatusCode() throws IOException { + return status; + } + + @Override + public int getRawStatusCode() throws IOException { + return status.value(); + } + + @Override + public String getStatusText() throws IOException { + return status.getReasonPhrase(); + } + + @Override + public void close() { + } + + @Override + public InputStream getBody() throws IOException { + return new ByteArrayInputStream("fallback".getBytes()); + } + + @Override + public HttpHeaders getHeaders() { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + return headers; + } + }; + } +} +And here is what the route configuration would look like. +zuul: + routes: + customers: /customers/** +If you would like to provide a default fallback for all routes than you can create a bean of +type FallbackProvider and have the getRoute method return * or null. +class MyFallbackProvider implements FallbackProvider { + @Override + public String getRoute() { + return "*"; + } + + @Override + public ClientHttpResponse fallbackResponse(String route, Throwable throwable) { + return new ClientHttpResponse() { + @Override + public HttpStatus getStatusCode() throws IOException { + return HttpStatus.OK; + } + + @Override + public int getRawStatusCode() throws IOException { + return 200; + } + + @Override + public String getStatusText() throws IOException { + return "OK"; + } + + @Override + public void close() { + + } + + @Override + public InputStream getBody() throws IOException { + return new ByteArrayInputStream("fallback".getBytes()); + } + + @Override + public HttpHeaders getHeaders() { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + return headers; + } + }; + } +} +
+
+Zuul Timeouts +If you want to configure the socket timeouts and read timeouts for requests proxied through +Zuul there are two options based on your configuration. +If Zuul is using service discovery then you need to configure these timeouts via Ribbon properties, +ribbon.ReadTimeout and ribbon.SocketTimeout. +If you have configured Zuul routes by specifying URLs then you will need to use +zuul.host.connect-timeout-millis and zuul.host.socket-timeout-millis. +
+
+Rewriting <literal>Location</literal> header +If Zuul is fronting a web application then there may be a need to re-write the Location header when the web application redirects through a http status code of 3XX, otherwise the browser will end up redirecting to the web application’s url instead of the Zuul url. +A LocationRewriteFilter Zuul filter can be configured to re-write the Location header to the Zuul’s url, it also adds back the stripped global and route specific prefixes. The filter can be added the following way via a Spring Configuration file: +import org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilter; +... + +@Configuration +@EnableZuulProxy +public class ZuulConfig { + @Bean + public LocationRewriteFilter locationRewriteFilter() { + return new LocationRewriteFilter(); + } +} + +Use this filter with caution though, the filter acts on the Location header of ALL 3XX response codes which may not be appropriate in all scenarios, say if the user is redirecting to an external URL. + +
+
+Zuul Developer Guide +For a general overview of how Zuul works, please see the Zuul Wiki. +
+The Zuul Servlet +Zuul is implemented as a Servlet. For the general cases, Zuul is embedded into the Spring Dispatch mechanism. This allows Spring MVC to be in control of the routing. In this case, Zuul is configured to buffer requests. If there is a need to go through Zuul without buffering requests (e.g. for large file uploads), the Servlet is also installed outside of the Spring Dispatcher. By default, this is located at /zuul. This path can be changed with the zuul.servlet-path property. +
+
+Zuul RequestContext +To pass information between filters, Zuul uses a RequestContext. Its data is held in a ThreadLocal specific to each request. Information about where to route requests, errors and the actual HttpServletRequest and HttpServletResponse are stored there. The RequestContext extends ConcurrentHashMap, so anything can be stored in the context. FilterConstants contains the keys that are used by the filters installed by Spring Cloud Netflix (more on these later). +
+
+<literal>@EnableZuulProxy</literal> vs. <literal>@EnableZuulServer</literal> +Spring Cloud Netflix installs a number of filters based on which annotation was used to enable Zuul. @EnableZuulProxy is a superset of @EnableZuulServer. In other words, @EnableZuulProxy contains all filters installed by @EnableZuulServer. The additional filters in the "proxy" enable routing functionality. If you want a "blank" Zuul, you should use @EnableZuulServer. +
+
+<literal>@EnableZuulServer</literal> Filters +Creates a SimpleRouteLocator that loads route definitions from Spring Boot configuration files. +The following filters are installed (as normal Spring Beans): +Pre filters: + + +ServletDetectionFilter: Detects if the request is through the Spring Dispatcher. Sets boolean with key FilterConstants.IS_DISPATCHER_SERVLET_REQUEST_KEY. + + +FormBodyWrapperFilter: Parses form data and reencodes it for downstream requests. + + +DebugFilter: if the debug request parameter is set, this filter sets RequestContext.setDebugRouting() and RequestContext.setDebugRequest() to true. + + +Route filters: + + +SendForwardFilter: This filter forwards requests using the Servlet RequestDispatcher. The forwarding location is stored in the RequestContext attribute FilterConstants.FORWARD_TO_KEY. This is useful for forwarding to endpoints in the current application. + + +Post filters: + + +SendResponseFilter: Writes responses from proxied requests to the current response. + + +Error filters: + + +SendErrorFilter: Forwards to /error (by default) if RequestContext.getThrowable() is not null. The default forwarding path (/error) can be changed by setting the error.path property. + + +
+
+<literal>@EnableZuulProxy</literal> Filters +Creates a DiscoveryClientRouteLocator that loads route definitions from a DiscoveryClient (like Eureka), as well as from properties. A route is created for each serviceId from the DiscoveryClient. As new services are added, the routes will be refreshed. +In addition to the filters described above, the following filters are installed (as normal Spring Beans): +Pre filters: + + +PreDecorationFilter: This filter determines where and how to route based on the supplied RouteLocator. It also sets various proxy-related headers for downstream requests. + + +Route filters: + + +RibbonRoutingFilter: This filter uses Ribbon, Hystrix and pluggable HTTP clients to send requests. Service ids are found in the RequestContext attribute FilterConstants.SERVICE_ID_KEY. This filter can use different HTTP clients. They are: + + +Apache HttpClient. This is the default client. + + +Squareup OkHttpClient v3. This is enabled by having the com.squareup.okhttp3:okhttp library on the classpath and setting ribbon.okhttp.enabled=true. + + +Netflix Ribbon HTTP client. This is enabled by setting ribbon.restclient.enabled=true. This client has limitations, such as it doesn’t support the PATCH method, but also has built-in retry. + + + + +SimpleHostRoutingFilter: This filter sends requests to predetermined URLs via an Apache HttpClient. URLs are found in RequestContext.getRouteHost(). + + +
+
+Custom Zuul Filter examples +Most of the following "How to Write" examples below are included Sample Zuul Filters project. There are also examples of manipulating the request or response body in that repository. +
+
+How to Write a Pre Filter +Pre filters are used to set up data in the RequestContext for use in filters downstream. The main use case is to set information required for route filters. +public class QueryParamPreFilter extends ZuulFilter { + @Override + public int filterOrder() { + return PRE_DECORATION_FILTER_ORDER - 1; // run before PreDecoration + } + + @Override + public String filterType() { + return PRE_TYPE; + } + + @Override + public boolean shouldFilter() { + RequestContext ctx = RequestContext.getCurrentContext(); + return !ctx.containsKey(FORWARD_TO_KEY) // a filter has already forwarded + && !ctx.containsKey(SERVICE_ID_KEY); // a filter has already determined serviceId + } + @Override + public Object run() { + RequestContext ctx = RequestContext.getCurrentContext(); + HttpServletRequest request = ctx.getRequest(); + if (request.getParameter("foo") != null) { + // put the serviceId in `RequestContext` + ctx.put(SERVICE_ID_KEY, request.getParameter("foo")); + } + return null; + } +} +The filter above populates SERVICE_ID_KEY from the foo request parameter. In reality, it’s not a good idea to do that kind of direct mapping, but the service id should be looked up from the value of foo instead. +Now that SERVICE_ID_KEY is populated, PreDecorationFilter won’t run and RibbonRoutingFilter will. If you wanted to route to a full URL instead, call ctx.setRouteHost(url) instead. +To modify the path that routing filters will forward to, set the REQUEST_URI_KEY. +
+
+How to Write a Route Filter +Route filters are run after pre filters and are used to make requests to other services. Much of the work here is to translate request and response data to and from the client required model. +public class OkHttpRoutingFilter extends ZuulFilter { + @Autowired + private ProxyRequestHelper helper; + + @Override + public String filterType() { + return ROUTE_TYPE; + } + + @Override + public int filterOrder() { + return SIMPLE_HOST_ROUTING_FILTER_ORDER - 1; + } + + @Override + public boolean shouldFilter() { + return RequestContext.getCurrentContext().getRouteHost() != null + && RequestContext.getCurrentContext().sendZuulResponse(); + } + + @Override + public Object run() { + OkHttpClient httpClient = new OkHttpClient.Builder() + // customize + .build(); + + RequestContext context = RequestContext.getCurrentContext(); + HttpServletRequest request = context.getRequest(); + + String method = request.getMethod(); + + String uri = this.helper.buildZuulRequestURI(request); + + Headers.Builder headers = new Headers.Builder(); + Enumeration<String> headerNames = request.getHeaderNames(); + while (headerNames.hasMoreElements()) { + String name = headerNames.nextElement(); + Enumeration<String> values = request.getHeaders(name); + + while (values.hasMoreElements()) { + String value = values.nextElement(); + headers.add(name, value); + } + } + + InputStream inputStream = request.getInputStream(); + + RequestBody requestBody = null; + if (inputStream != null && HttpMethod.permitsRequestBody(method)) { + MediaType mediaType = null; + if (headers.get("Content-Type") != null) { + mediaType = MediaType.parse(headers.get("Content-Type")); + } + requestBody = RequestBody.create(mediaType, StreamUtils.copyToByteArray(inputStream)); + } + + Request.Builder builder = new Request.Builder() + .headers(headers.build()) + .url(uri) + .method(method, requestBody); + + Response response = httpClient.newCall(builder.build()).execute(); + + LinkedMultiValueMap<String, String> responseHeaders = new LinkedMultiValueMap<>(); + + for (Map.Entry<String, List<String>> entry : response.headers().toMultimap().entrySet()) { + responseHeaders.put(entry.getKey(), entry.getValue()); + } + + this.helper.setResponse(response.code(), response.body().byteStream(), + responseHeaders); + context.setRouteHost(null); // prevent SimpleHostRoutingFilter from running + return null; + } +} +The above filter translates Servlet request information into OkHttp3 request information, executes an HTTP request, then translates OkHttp3 reponse information to the Servlet response. WARNING: this filter might have bugs and not function correctly. +
+
+How to Write a Post Filter +Post filters typically manipulate the response. In the filter below, we add a random UUID as the X-Foo header. Other manipulations, such as transforming the response body, are much more complex and compute-intensive. +public class AddResponseHeaderFilter extends ZuulFilter { + @Override + public String filterType() { + return POST_TYPE; + } + + @Override + public int filterOrder() { + return SEND_RESPONSE_FILTER_ORDER - 1; + } + + @Override + public boolean shouldFilter() { + return true; + } + + @Override + public Object run() { + RequestContext context = RequestContext.getCurrentContext(); + HttpServletResponse servletResponse = context.getResponse(); + servletResponse.addHeader("X-Foo", UUID.randomUUID().toString()); + return null; + } +} +
+
+How Zuul Errors Work +If an exception is thrown during any portion of the Zuul filter lifecycle, the error filters are executed. The SendErrorFilter is only run if RequestContext.getThrowable() is not null. It then sets specific javax.servlet.error.* attributes in the request and forwards the request to the Spring Boot error page. +
+
+Zuul Eager Application Context Loading +Zuul internally uses Ribbon for calling the remote url’s and Ribbon clients are by default lazily loaded up by Spring Cloud on first call. +This behavior can be changed for Zuul using the following configuration and will result in the child Ribbon related Application contexts being eagerly loaded up at application startup time. + +application.yml + +zuul: + ribbon: + eager-load: + enabled: true + + +
+
+
+ +Polyglot support with Sidecar +Do you have non-jvm languages you want to take advantage of Eureka, Ribbon and +Config Server? The Spring Cloud Netflix Sidecar was inspired by +Netflix Prana. It includes a simple http api +to get all of the instances (ie host and port) for a given service. You can +also proxy service calls through an embedded Zuul proxy which gets its route +entries from Eureka. The Spring Cloud Config Server can be accessed directly +via host lookup or through the Zuul Proxy. The non-jvm app should implement +a health check so the Sidecar can report to eureka if the app is up or down. +To include Sidecar in your project use the dependency with group org.springframework.cloud +and artifact id spring-cloud-netflix-sidecar. +To enable the Sidecar, create a Spring Boot application with @EnableSidecar. +This annotation includes @EnableCircuitBreaker, @EnableDiscoveryClient, +and @EnableZuulProxy. Run the resulting application on the same host as the +non-jvm application. +To configure the side car add sidecar.port and sidecar.health-uri to application.yml. +The sidecar.port property is the port the non-jvm app is listening on. This +is so the Sidecar can properly register the app with Eureka. The sidecar.health-uri +is a uri accessible on the non-jvm app that mimicks a Spring Boot health +indicator. It should return a json document like the following: + +health-uri-document + +{ + "status":"UP" +} + + +Here is an example application.yml for a Sidecar application: + +application.yml + +server: + port: 5678 +spring: + application: + name: sidecar + +sidecar: + port: 8000 + health-uri: http://localhost:8000/health.json + + +The api for the DiscoveryClient.getInstances() method is /hosts/{serviceId}. +Here is an example response for /hosts/customers that returns two instances on +different hosts. This api is accessible to the non-jvm app (if the sidecar is +on port 5678) at http://localhost:5678/hosts/{serviceId}. + +/hosts/customers + +[ + { + "host": "myhost", + "port": 9000, + "uri": "http://myhost:9000", + "serviceId": "CUSTOMERS", + "secure": false + }, + { + "host": "myhost2", + "port": 9000, + "uri": "http://myhost2:9000", + "serviceId": "CUSTOMERS", + "secure": false + } +] + + +The Zuul proxy automatically adds routes for each service known in eureka to +/<serviceId>, so the customers service is available at /customers. The +Non-jvm app can access the customer service via http://localhost:5678/customers +(assuming the sidecar is listening on port 5678). +If the Config Server is registered with Eureka, non-jvm application can access +it via the Zuul proxy. If the serviceId of the ConfigServer is configserver +and the Sidecar is on port 5678, then it can be accessed at +http://localhost:5678/configserver +Non-jvm app can take advantage of the Config Server’s ability to return YAML +documents. For example, a call to http://sidecar.local.spring.io:5678/configserver/default-master.yml +might result in a YAML document like the following +eureka: + client: + serviceUrl: + defaultZone: http://localhost:8761/eureka/ + password: password +info: + description: Spring Cloud Samples + url: https://github.com/spring-cloud-samples + + +Metrics Backend: Atlas +Atlas was developed by Netflix to manage dimensional time series data for near real-time operational insight. Atlas features in-memory data storage, allowing it to gather and report very large numbers of metrics, very quickly. +Atlas captures operational intelligence. Whereas business intelligence is data gathered for analyzing trends over time, operational intelligence provides a picture of what is currently happening within a system. +Spring Cloud provides a spring-cloud-starter-netflix-atlas that has all the dependencies you need. Then just annotate your Spring Boot application with @EnableAtlas and provide a location for your running Atlas server with the netflix.atlas.uri property. +
+Using Atlas +To bootstrap a in-memory standalone Atlas instance: +$ curl -LO https://github.com/Netflix/atlas/releases/download/v1.4.2/atlas-1.4.2-standalone.jar +$ java -jar atlas-1.4.2-standalone.jar + +An Atlas standalone node running on an r3.2xlarge (61GB RAM) can handle roughly 2 million metrics per minute for a given 6 hour window. + +Once running and you have collected a handful of metrics, verify that your setup is correct by listing tags on the Atlas server: +$ curl http://ATLAS/api/v1/tags + +After executing several requests against your service, you can gather some very basic information on the request latency of every request by pasting the following url in your browser: http://ATLAS/api/v1/graph?q=name,rest,:eq,:avg + +The Atlas wiki contains a compilation of sample queries for various scenarios. +Make sure to check out the alerting philosophy and docs on using double exponential smoothing to generate dynamic alert thresholds. +
+
+ +Retrying Failed Requests +Spring Cloud Netflix offers a variety of ways to make HTTP requests. You can use a load balanced +RestTemplate, Ribbon, or Feign. No matter how you choose to your HTTP requests, there is always +a chance the request may fail. When a request fails you may want to have the request retried +automatically. To accomplish this when using Sping Cloud Netflix you need to include +Spring Retry on your application’s classpath. +When Spring Retry is present load balanced RestTemplates, Feign, and Zuul will automatically +retry any failed requests (assuming you configuration allows it to). +
+BackOff Policies +By default no backoff policy is used when retrying requests. If you would like to configure +a backoff policy you will need to create a bean of type LoadBalancedBackOffPolicyFactory +which will be used to create a BackOffPolicy for a given service. +@Configuration +public class MyConfiguration { + @Bean + LoadBalancedBackOffPolicyFactory backOffPolciyFactory() { + return new LoadBalancedBackOffPolicyFactory() { + @Override + public BackOffPolicy createBackOffPolicy(String service) { + return new ExponentialBackOffPolicy(); + } + }; + } +} +
+
+Configuration +Anytime Ribbon is used with Spring Retry you can control the retry functionality by configuring +certain Ribbon properties. The properties you can use are +client.ribbon.MaxAutoRetries, client.ribbon.MaxAutoRetriesNextServer, and +client.ribbon.OkToRetryOnAllOperations. See the Ribbon documentation +for a description of what there properties do. + +Enabling client.ribbon.OkToRetryOnAllOperations includes retring POST requests wich can have a impact +on the server’s resources due to the buffering of the request’s body. + +In addition you may want to retry requests when certain status codes are returned in the +response. You can list the response codes you would like the Ribbon client to retry using the + property clientName.ribbon.retryableStatusCodes. For example +clientName: + ribbon: + retryableStatusCodes: 404,502 +You can also create a bean of type LoadBalancedRetryPolicy and implement the retryableStatusCode +method to determine whether you want to retry a request given the status code. +
+Zuul +You can turn off Zuul’s retry functionality by setting zuul.retryable to false. You +can also disable retry functionality on route by route basis by setting +zuul.routes.routename.retryable to false. +
+
+
+ +HTTP Clients +Spring Cloud Netflix will automatically create the HTTP client used by Ribbon, Feign, and +Zuul for you. However you can also provide your own HTTP clients customized how you please +yourself. To do this you can either create a bean of type ClosableHttpClient if you +are using the Apache Http Cient, or OkHttpClient if you are using OK HTTP. + +When you create your own HTTP client you are also responsible for implementing +the correct connection management strategies for these clients. Doing this improperly +can result in resource management issues. + + +
\ No newline at end of file