Compare commits

...

444 Commits
3.0.x ... main

Author SHA1 Message Date
Olga MaciaszekSharma 14bfa57922 Fix lifecycle synchronisation. 1 year ago
Ryan Baxter f51cc1fd92 Merge branch '4.0.x' 1 year ago
Ryan Baxter 1dbe6c0c39 Fix bad merge 1 year ago
Ryan Baxter fb70b21b9a Merge branch '3.1.x' into 4.0.x 1 year ago
Jinghao Song 9b2d247537
Fix #1285 Spring Cloud activates unexpected profiles when some conditions met (#1286) 1 year ago
Ryan Baxter 233159843f Merge branch '4.0.x' 1 year ago
Ryan Baxter 511b7cae8c Exclude more dependencies from the duplicate finder plugin 1 year ago
Ryan Baxter 379eea58f0 Merge branch '3.1.x' into 4.0.x 1 year ago
Ryan Baxter 96006b51ba Fixing include in docs 1 year ago
Ryan Baxter 5d0a442250
Upgrade spring-security-rsa (#1290) 1 year ago
buildmaster 083675da7c Bumping versions 1 year ago
buildmaster 1b8075e06a Bumping versions 1 year ago
Maurice Zeijen a7876333d3 Fixed order of the `BootstrapConfigFileApplicationListener` so that it always runs after the `ConfigDataEnvironmentPostProcessor` (#1213) 1 year ago
Maurice Zeijen 9ea5801529
Fixed order of the `BootstrapConfigFileApplicationListener` so that it always runs after the `ConfigDataEnvironmentPostProcessor` (#1213) 1 year ago
buildmaster 56f16d116e Bumping versions 1 year ago
Olga MaciaszekSharma f181cb7ea6 Merge remote-tracking branch 'origin/4.0.x'. 1 year ago
Olga MaciaszekSharma 01098128f1 Document context refresh not supported for AOT and native. 1 year ago
buildmaster b156a8b635 Going back to snapshots 1 year ago
buildmaster 751fe797e0 Update SNAPSHOT to 4.1.0-M2 1 year ago
Olga MaciaszekSharma 5c6b7bac56 Fix endpoint reference. Based on gh-1241. 1 year ago
Alex bf27081a88
Fix #1240. (#1241) 1 year ago
dependabot[bot] e7702a458e
Bump maven-resolver.version from 1.1.1 to 1.9.16 (#1284) 1 year ago
dependabot[bot] 158a3c32ef
Bump actions/cache from 2 to 3 (#1283) 1 year ago
dependabot[bot] fffb31353b
Bump mikepenz/action-junit-report from 2 to 4 (#1282) 1 year ago
dependabot[bot] 768fa3abd7
Bump actions/setup-java from 2 to 3 (#1279) 1 year ago
dependabot[bot] 583710b52e
Bump actions/upload-artifact from 2 to 3 (#1278) 1 year ago
dependabot[bot] 73e98cae58
Bump actions/upload-artifact from 2 to 3 (#1277) 1 year ago
dependabot[bot] 86f32406f3
Bump actions/checkout from 2 to 4 (#1276) 1 year ago
dependabot[bot] f44270b00f
Bump actions/setup-java from 2 to 3 (#1275) 1 year ago
dependabot[bot] 7cc5f0180f
Bump actions/cache from 2 to 3 (#1272) 1 year ago
dependabot[bot] 0562d449bb
Bump mikepenz/action-junit-report from 2 to 4 (#1270) 1 year ago
spencergibb ac7228e4db
Adds antora extension and update ui version 1 year ago
Olga MaciaszekSharma bcf93cb8e8 Upgrade antora-ui-spring to 0.3.7. 1 year ago
buildmaster 3a29227a28 Bumping versions 1 year ago
Olga MaciaszekSharma 930885da0e Update docs. 1 year ago
Olga MaciaszekSharma 88cbd37ad1 Add dependabot.yml. 1 year ago
Olga Maciaszek-Sharma 9449edf93b
Refresh Scope on restart. (#1266) 1 year ago
buildmaster 7a4f30f2e0 Bumping versions 1 year ago
spencergibb d604e526f8
updates for docs and formatting 1 year ago
buildmaster d4bc60929b Bumping versions 1 year ago
Marcin Grzejszczak cc4a47f278 Speeds up antora build 1 year ago
Ryan Baxter dea6c45b19 Merge branch 'main' of github.com:spring-cloud/spring-cloud-commons 1 year ago
Ryan Baxter a51f56f47d Merge branch '4.0.x' 1 year ago
Marcin Grzejszczak 3589642cac Generated files are committed 1 year ago
Ryan Baxter 794dc5192c Merge branch '4.0.x' of github.com:spring-cloud/spring-cloud-commons into 4.0.x 1 year ago
Ryan Baxter ea1fc56772 Clarify property docs. Fixes #1264 1 year ago
Marcin Grzejszczak 14291a608e Skipping phases for antora build 1 year ago
Marcin Grzejszczak 78717f75ad install -> package 1 year ago
Marcin Grzejszczak f9df7ef59b Fixing antora 1 year ago
Marcin Grzejszczak ca9ebc2f56
Antora (#1263) 1 year ago
buildmaster 5191950aa4 Going back to snapshots 1 year ago
buildmaster 4f5a29cb0c Update SNAPSHOT to 4.1.0-M1 1 year ago
buildmaster 8c82e1b56e Bumping versions 1 year ago
buildmaster 8857f8fd66 Bumping versions 1 year ago
buildmaster 229fa179f7 Bumping versions to 4.0.5-SNAPSHOT after release 1 year ago
buildmaster 605b2e0b74 Going back to snapshots 1 year ago
buildmaster 1a387e1e39 Update SNAPSHOT to 4.0.4 1 year ago
Olga MaciaszekSharma db4a1bbd75 Temporarily disable test. 1 year ago
Olga MaciaszekSharma 8fdedcfa42 Merge remote-tracking branch 'origin/4.0.x' 1 year ago
Olga MaciaszekSharma 6ce1debaf2 Merge remote-tracking branch 'origin/3.1.x' into 4.0.x 1 year ago
Olga MaciaszekSharma 989ed7dc15 Use classloader from class. 1 year ago
Olga Maciaszek-Sharma 464a9820fd
Use classloader from class. (#1256) 1 year ago
spencergibb 8cfb8e3732
Updates SpringBootVersionVerifier with class from boot 3.2 1 year ago
Olga MaciaszekSharma e52bae7773 Revert "Temporarily downgrade version." 1 year ago
Olga MaciaszekSharma a0b8a51742 Temporarily downgrade version. 1 year ago
Ryan Baxter c956c81b28 Merge branch '4.0.x' of github.com:spring-cloud/spring-cloud-commons into 4.0.x 1 year ago
Ryan Baxter 49170f6ff7 Try 1.0.12 release of spring-security-rsa 1 year ago
Olga MaciaszekSharma a6ac50f0a7 Merge remote-tracking branch 'origin/main' 1 year ago
Olga MaciaszekSharma b516856cea Merge remote-tracking branch 'origin/4.0.x' 1 year ago
Olga MaciaszekSharma fb879e7cf1 Adjust docs. 1 year ago
Olga MaciaszekSharma cb96b632bb Merge remote-tracking branch 'origin/3.1.x' into 4.0.x 1 year ago
Ryan Baxter d796c28527 Revert to spring-security-rsa 1.0.11 1 year ago
Ryan Baxter ace5a3d5f3 Merge branch '4.0.x' 1 year ago
Ryan Baxter 78d87d6547 Build 4.0.x branch in github actions 1 year ago
Ryan Baxter a5e71fde36 Merge branch '4.0.x' 1 year ago
Ryan Baxter 8531a7d40b Update to Spring Security RSA 1.0.12 1 year ago
Olga MaciaszekSharma 172452d2ed Update copyright and fix docs. 1 year ago
buildmaster 8f65504863 Bumping versions 1 year ago
buildmaster d53f45d1f7 Bumping versions to 3.1.8-SNAPSHOT after release 1 year ago
buildmaster 7a9bba08ed Going back to snapshots 1 year ago
buildmaster 4c639f1cf1 Update SNAPSHOT to 3.1.7 1 year ago
Olga MaciaszekSharma 0d1f4967fd Update config property info. 1 year ago
Olga MaciaszekSharma 72c526549f Merge remote-tracking branch 'origin/main' 1 year ago
Dave Syer f1840b51d0 Move certs into files 1 year ago
Dave Syer 78b96e6160 Add bouncycastle in test scope (temporarily?) 1 year ago
Dave Syer e090bd234f Fix dependencies 1 year ago
Olga MaciaszekSharma 2e8631b127 Call `get(Request request)` on delegates by default. 1 year ago
Olga MaciaszekSharma 63c3eb614d Merge remote-tracking branch 'origin/main' 1 year ago
Dave Syer f0ccaf01ac Remove obsolete code 1 year ago
Olga MaciaszekSharma 7efe08c674 Merge remote-tracking branch 'origin/4.0.x' 1 year ago
Olga MaciaszekSharma e4e56e93cf Call `get(Request request)` on delegates in WeightedServiceInstanceListSupplier. 1 year ago
Dave Syer 0a531d2930 Remove obsolete code 1 year ago
Dave Syer ce379d5e31
Update RSA library version 1 year ago
Olga MaciaszekSharma f620c44ea5 Merge remote-tracking branch 'origin/3.1.x' into 4.0.x 1 year ago
Olga MaciaszekSharma cc1aaa8883 Merge remote-tracking branch 'origin/3.1.x' into 4.0.x 1 year ago
Olga MaciaszekSharma d36062b8bb Update copyright and fix docs. 1 year ago
Olga Maciaszek-Sharma 354a894606
Call get request on delegates (#1250) 1 year ago
Dave Syer 214f2401e5
Update RSA library version 1 year ago
Olga MaciaszekSharma 1a04b22591 Merge remote-tracking branch 'origin/4.0.x' 1 year ago
Olga MaciaszekSharma a22bb12e75 Add missing reflection hints for EncryptionBootstrapConfiguration. Fixes gh-1245. 1 year ago
buildmaster 3df50061ac Bumping versions 1 year ago
buildmaster e47d5e5f88 Bumping versions 1 year ago
spencergibb 5b4a46fc60
formattingˆ 1 year ago
spencergibb c682b2de1d
Uses a custom event to share the SpringApplication. 1 year ago
spencergibb d0f6d2b2e9
Uses a custom event to share the SpringApplication. 1 year ago
Olga MaciaszekSharma 5068621601 Merge remote-tracking branch 'origin/4.0.x' 1 year ago
Olga MaciaszekSharma 12e709cdc6 Remove deprecated method use. 1 year ago
buildmaster a0ba27fba2 Bumping versions 1 year ago
spencergibb 443d0e89f4
Updates to 4.1.0-SNAPSHOT 1 year ago
spencergibb 3c0b55bac9
Updates compatibility verifier for boot 3.2 compatibility 1 year ago
spencergibb 9cb8802f74
Updates for boot 3.2 compatibility 1 year ago
Ryan Baxter 8fbf183015 Merge branch 'main' of github.com:spring-cloud/spring-cloud-commons 1 year ago
Ryan Baxter 6c04576b18 Fix typo in configprops. 1 year ago
Olga MaciaszekSharma 8238abdf8b Merge remote-tracking branch 'origin/3.1.x' 1 year ago
sruffatti 31c07aa2db
Fixes gh-1209 (#1239) 1 year ago
buildmaster 142d8e50f7 Bumping versions 1 year ago
HJK181 f2068833bd
Fix DelegatingServiceInstanceListSupplier must (#1226) 1 year ago
buildmaster fd2d374381 Bumping versions 1 year ago
buildmaster f22d75050f Bumping versions 1 year ago
buildmaster 409e13f289 Bumping versions to 4.0.4-SNAPSHOT after release 1 year ago
buildmaster 0661beb4b7 Going back to snapshots 1 year ago
buildmaster 261562aa04 Update SNAPSHOT to 4.0.3 1 year ago
Olga MaciaszekSharma cb97108f57 Fix logging in tests for Boot 3.1.x. 2 years ago
omernaci f00cc0e052
note section added for security implications of exposed actuator env. (#1231) 2 years ago
Ryan Baxter b4010c9cf8 Updating versions in docs 2 years ago
Ryan Baxter 07a2821ac7 Merge branch '3.1.x' 2 years ago
Ryan Baxter 130208e0aa Fixing version in docs 2 years ago
Ryan Baxter ac709ec6e2 Merge branch '3.1.x' 2 years ago
Ryan Baxter 2f467e5823
Add application listener to locate property sources during bootstrap (#1228) 2 years ago
omernaci 81314d50d7
commonsFeatures method name updated to springCloudCommonsFeatures. Fixes #1229 (#1230) 2 years ago
buildmaster c9aaa5fdb6 Bumping versions 2 years ago
buildmaster 51ee78555d Bumping versions to 4.0.3-SNAPSHOT after release 2 years ago
buildmaster 096d870fd6 Going back to snapshots 2 years ago
buildmaster 9ad2f7c988 Update SNAPSHOT to 4.0.2 2 years ago
heqiang 8ec45e03b0
Polish spring-cloud-commons.adoc. (#1216) 2 years ago
Olga Maciaszek-Sharma 80643ef3ed
Allow batching the emitted alive instances flux. (#1206) 2 years ago
buildmaster 3697738614 Bumping versions 2 years ago
buildmaster 548f589a0f Bumping versions 2 years ago
buildmaster 383ae12c7a Bumping versions to 3.1.7-SNAPSHOT after release 2 years ago
buildmaster 743e98b0a6 Going back to snapshots 2 years ago
buildmaster 0668ebf67d Update SNAPSHOT to 3.1.6 2 years ago
Olga Maciaszek-Sharma dbdb21a199 Adjust to changes in main. 2 years ago
Olga Maciaszek-Sharma cffed824bb Merge remote-tracking branch 'origin/3.1.x' 2 years ago
Olga Maciaszek-Sharma 366c5f52bd
Add caching to all user-enabled configs other than healthcheck lb. (#1208) 2 years ago
buildmaster 6c21c85080 Bumping versions 2 years ago
spencergibb ce030c0f12
Adds boot 3.1 support in SpringBootDependencyTests 2 years ago
spencergibb a2cc42614c
Adds boot 3.1 support in SpringBootVersionVerifier 2 years ago
Olga Maciaszek-Sharma 3bbd9524ad Merge remote-tracking branch 'origin/3.1.x' 2 years ago
Olga Maciaszek-Sharma 6677d16736
Add Reactive probe (#1201) 2 years ago
纪卓志 b996fec203
Refactor code to simplify calculation logic (#1199) 2 years ago
Ryan Baxter f990f1c8cf Remove unused parameters in reinitializeLoggingSystem. Fixes #1200 2 years ago
buildmaster 4c456f6071 Bumping versions to 4.0.2-SNAPSHOT after release 2 years ago
buildmaster 4518b68b1d Going back to snapshots 2 years ago
buildmaster 201cadc911 Update SNAPSHOT to 4.0.1 2 years ago
spencergibb b886421427
Adds junit-platform-launcher to other commons modules 2 years ago
spencergibb 7444cec131
Adds provided scope to junit dependency. 2 years ago
spencergibb 5e21e76646
Adds test scope to junit dependency. 2 years ago
buildmaster e4b199df93 Bumping versions 2 years ago
Krishna a6c5d438fe
Removed ModifiedClasspathRunner and used the ClasspathExtensions from the Spring boot test support (#1181) 2 years ago
Olga Maciaszek-Sharma 77f9d2b1e7 Merge remote-tracking branch 'origin/3.1.x' into 3.1.x 2 years ago
Olga Maciaszek-Sharma 34b05afbe3 Add GH actions setup. 2 years ago
Olga Maciaszek-Sharma f6dd5926b5 Merge remote-tracking branch 'origin/3.1.x' 2 years ago
Olga Maciaszek-Sharma a4a37cd975
Recheck for null service instance to avoid micrometer NPE. (#1197) 2 years ago
Olga Maciaszek-Sharma 097959a64a Merge remote-tracking branch 'origin/3.1.x' 2 years ago
qingshanpeng 483798a7d2 add override annotation for ScopeCache child class 2 years ago
qingshanpeng d22b30b508 add override annotation for Specification child class 2 years ago
Olga Maciaszek-Sharma 2eaaf287e3 Merge remote-tracking branch 'origin/3.1.x' 2 years ago
Olga Maciaszek-Sharma 66b0abdacd Regenerate docs. 2 years ago
DESKTOP-35GNJVO\harry.yoon fc445271d8 Fixed typos in the appendix. 2 years ago
Ning Sun 86017665ca
Provide setter for DefaultServiceInstance.secure (#1089) 2 years ago
纪卓志 aee2354798
Optimizing selectors to ensure that selection is always `O(1)` time (#1184) 2 years ago
Olga Maciaszek-Sharma e4bd5b300b
Add native hints for Caffeine cache. (#1194) 2 years ago
Olga Maciaszek-Sharma 9a06eb4a05 Merge remote-tracking branch 'origin/3.1.x' 2 years ago
Olga Maciaszek-Sharma 95b7d2f91e Do not run BlockingLoadBalancerClientAutoConfiguration or LoadBalancerCacheAutoConfiguration when load-balancing disabled. Fixes gh-1114. 2 years ago
buildmaster b6e4fb00d4 Bumping versions 2 years ago
buildmaster 1e4f2c5a77 Bumping versions 2 years ago
buildmaster 7f287120d7 Bumping versions to 4.0.1-SNAPSHOT after release 2 years ago
buildmaster 9f231ec824 Going back to snapshots 2 years ago
buildmaster 90bfce5be6 Update SNAPSHOT to 4.0.0 2 years ago
Marcin Grzejszczak 31cade5948 Fixed observation convention issues 2 years ago
spencergibb 99fda44272
removed non-existent micrometer docs jars 2 years ago
Marcin Grzejszczak 07c6d2d791
Removing libs prefix and local suffix from repositories 2 years ago
spencergibb af8a36b36b
Update micrometer docs generator to 1.0.0 2 years ago
Ryan Baxter 34687af510
Use spring.config.activate.on-profile instead of spring.profiles for Boot 3 compatibility. Fixes #1177 (#1182) 2 years ago
Moary Chen 5faadf3aa4
Use a class name that is only available on Spring Boot 3 (#1179) 2 years ago
Olga Maciaszek-Sharma d1c3449b57 Merge remote-tracking branch 'origin/3.1.x' 2 years ago
Benoit Kessler c13c8bbb5b Add flexibility to zone preference in load balancing (#1174) 2 years ago
Benoit Kessler 9849d9b23d
Add flexibility to zone preference in load balancing (#1174) 2 years ago
buildmaster f26c2b3e93 Going back to snapshots 2 years ago
buildmaster 007f844e6c Update SNAPSHOT to 4.0.0-RC3 2 years ago
Olga Maciaszek-Sharma 78eb9a0fd6
Lazily initialize child contexts with AOT initializers. (#1176) 2 years ago
buildmaster e18fc0d602 Bumping versions 2 years ago
Marcin Grzejszczak e98e315704
Adds a check for Sleuth with 2022 cloud (#1175) 2 years ago
buildmaster b1fc0d8d6f Going back to snapshots 2 years ago
buildmaster ef88c4164a Update SNAPSHOT to 4.0.0-RC2 2 years ago
Ryan Baxter 768384d8a0 Remove httpclient package. Fixes #1171 2 years ago
Ryan Baxter 82fb22649b Remove deprecated bind method 2 years ago
Ryan Baxter 8209a047d3 Remove @SpringCloudApplication annotation 2 years ago
Ryan Baxter 5e7c2a6601 Merge branch 'main' of github.com:spring-cloud/spring-cloud-commons 2 years ago
Ryan Baxter d676889701 Remove @EnableCircuitBreaker annotation 2 years ago
buildmaster b86d06e1e2 Bumping versions 2 years ago
Ryan Baxter dbdc87bb76 Remove deprecated AbstractAutoServiceRegistration constructor 2 years ago
Olga Maciaszek-Sharma 5b7e03b133 Revert "Allow overriding getScheme on DefaultServiceInstance. (#1168)" 2 years ago
Olga Maciaszek-Sharma e41b59d140 Remove CircleCI icon from readme. Reformat. 2 years ago
Olga Maciaszek-Sharma 603bb2d7e3 Remove Circle CI config. 2 years ago
Olga Maciaszek-Sharma 5015b13f22
Allow overriding getScheme on DefaultServiceInstance. (#1168) 2 years ago
Olga Maciaszek-Sharma 0637a76355 Fix failing tests. 2 years ago
Olga Maciaszek-Sharma 4a0e403ec2 Remove unused imports. 2 years ago
Olga Maciaszek-Sharma 5cb7a0d289 Remove deprecated elements in SC LoadBalancer. 2 years ago
Olga Maciaszek-Sharma efe5131a36 Remove some deprecated API usage, switch to newer JDK api usages, refactor. 2 years ago
Ryan Baxter 6f39b7ed22 Merge branch '3.1.x' 2 years ago
Ryan Baxter 987704784f
Add note about removing configuration values and performing refreshes. Fixes #1161 (#1167) 2 years ago
buildmaster be72e49e91 Bumping versions to 3.1.6-SNAPSHOT after release 2 years ago
buildmaster 5d95ca7137 Going back to snapshots 2 years ago
buildmaster d33cadbe5c Update SNAPSHOT to 3.1.5 2 years ago
Olga Maciaszek-Sharma 82213bab6b Cosmetic fix in doc. 2 years ago
jizhuozhi 07f7328ca2
Lazy fills service instances to reduce max latency (#1165) 2 years ago
buildmaster fa53e6cb1c Going back to snapshots 2 years ago
buildmaster 3acff28aeb Update SNAPSHOT to 4.0.0-RC1 2 years ago
jizhuozhi aef64061be
feat: support autoconfigure WeightedServiceInstanceListSupplier (#1163) 2 years ago
spencergibb 0a4ee74bca
Merge branch '3.1.x' 2 years ago
spencergibb 3a582dc603
Adds rebind/refresh an individual bean by type 2 years ago
spencergibb d1dba70bbf
Adds rebind/refresh an individual bean by type 2 years ago
Ryan Baxter 7afddc8eb8 Destroy and initialize beans within the correct context. Fixes #1158 (#1160) 2 years ago
Ryan Baxter 86c44de855
Destroy and initialize beans within the correct context. Fixes #1158 (#1160) 2 years ago
Marcin Grzejszczak 6a03d2b201
Sets parentObservation on circuitbreaker Observation (#1159) 2 years ago
Olga Maciaszek-Sharma ceab8dc08f Fix capitalisation. 2 years ago
spencergibb 4f553328e7
Updates version compatibility 3.0 class to check 2 years ago
Ryan Baxter 37f17ba9e2 Merge branch '3.1.x' 2 years ago
Ryan Baxter 12beb8cc08
Switch default in id from 0 to 8080 if server.port is not set. Fixes #1154 (#1155) 2 years ago
spencergibb c0c2b1ee83
Updates to new Observation classes 2 years ago
spencergibb d73f3b614e
Updates to new AOT classes 2 years ago
spencergibb 8937a79d0d
Makes LoadBalancerChildContextInitializer static 2 years ago
spencergibb b18ea82607
Fixes test 2 years ago
spencergibb 733e9f3ee8
Fixes test 2 years ago
spencergibb 1eb27ae9e7
Rename to avoid conflict 2 years ago
buildmaster f30a42f01e Going back to snapshots 2 years ago
buildmaster f003ea1813 Update SNAPSHOT to 4.0.0-M5 2 years ago
Olga Maciaszek-Sharma 64a0f4618d Merge remote-tracking branch 'origin/3.1.x' 2 years ago
jizhuozhi 69856a0ea8
Do not move position when there is only 1 instance (#1152) 2 years ago
Olga Maciaszek-Sharma 42b5a915c0 Merge remote-tracking branch 'origin/3.1.x' 2 years ago
Olga Maciaszek-Sharma cf20bc788b Fix docs after editor review. Fix checkstyle issues. 2 years ago
jizhuozhi 6955fdcc7a
feat: expand the list by weights to implement weighted load balancing (#1140) 2 years ago
Misagh Moayyed 5dc06fefc7
add @AliasFor declaration for RefreshScope (#1151) 2 years ago
Ryan Baxter 398b29ee23
Create maven.yaml 2 years ago
buildmaster 0ec7e02009 Bumping versions 2 years ago
Olga Maciaszek-Sharma 3a2301e344 Merge remote-tracking branch 'origin/3.1.x' 2 years ago
Olga Maciaszek-Sharma c1d81903b3 Revert "Revert "fix bug of XForwardedHeadersTransformer ConditionalOnBean"" 2 years ago
Olga Maciaszek-Sharma d3300c9ad1 Merge remote-tracking branch 'origin/3.1.x' 2 years ago
Olga Maciaszek-Sharma f938e797be Revert "fix bug of XForwardedHeadersTransformer ConditionalOnBean" 2 years ago
Olga Maciaszek-Sharma 1c4f546295 Merge remote-tracking branch 'origin/3.1.x' 2 years ago
Olga Maciaszek-Sharma 9399b2d1d3 Reformat. 2 years ago
liubao e1061af545 [#1141]RequestData add constructors so that we can set attributes 2 years ago
galaxy 5f32ef216f fix bug of XForwardedHeadersTransformer ConditionalOnBean 2 years ago
Olga Maciaszek-Sharma 3fc07ae777 Merge remote-tracking branch 'origin/3.1.x' 2 years ago
Jay 3552094806 Change xforwardedProto to xForwardedProto 2 years ago
spencergibb 77fc4dc628
Migrates to AutoConfiguration.imports 2 years ago
Olga Maciaszek-Sharma 813104de85
Document lb aot support (#1147) 2 years ago
Olga Maciaszek-Sharma 0d40b30f40 Remove unnecessary stubbing. 2 years ago
Olga Maciaszek-Sharma f3cf13118d Adapt to changes in Micrometer. 2 years ago
Stéphane Nicoll d8094ecb73
Adapt to API change in Spring Framework (#1146) 2 years ago
Ryan Baxter e892e0e3ac Fix AOT imports 2 years ago
Ryan Baxter 6535873c2a Fix observability API changes 2 years ago
buildmaster 856bba6ce7 Going back to snapshots 2 years ago
buildmaster 4cf57a3e50 Update SNAPSHOT to 3.1.4 2 years ago
buildmaster fdc3ac4659 Bumping versions 2 years ago
buildmaster 53e160b2ad Bumping versions 2 years ago
buildmaster 7cf6acb40c Bumping versions to 3.1.5-SNAPSHOT after release 2 years ago
buildmaster 99db0fdeb6 Going back to snapshots 2 years ago
buildmaster 9dd4af43af Update SNAPSHOT to 3.1.4 2 years ago
Olga Maciaszek-Sharma cf69508a39 Switch to using HttpStatusCode in ResponseData. Fixes gh-1088. 2 years ago
Ryan Baxter 9eb3a08c14 Fixing EnvironmentEndpoints to work with new constructors. Fixes #1137 2 years ago
Marcin Grzejszczak 17311ebfd7
Support for Micrometer Observations (#1131) 2 years ago
Marcin Grzejszczak c7790815fb
Changed the base image for the build (#1136) 2 years ago
Olga Maciaszek-Sharma 94ab8728fb
Support LoadBalancer child context creation during AOT processing (#1135) 2 years ago
buildmaster 6e610bf5c9 Going back to snapshots 2 years ago
buildmaster 2de290524a Update SNAPSHOT to 4.0.0-M4 2 years ago
Olga Maciaszek-Sharma 830cadadd8 Merge remote-tracking branch 'origin/main' 2 years ago
Olga Maciaszek-Sharma 620b0c9001 Retrieve configuration as Class array. 2 years ago
buildmaster 9ca83dc892 Bumping versions 2 years ago
Olga Maciaszek-Sharma 327c1b6735 Mark DefaultServiceInstance as NestedConfigurationProperty. 2 years ago
Olga Maciaszek-Sharma 9b67e2fd8e Refactor eager-load PR. Add docs. 2 years ago
Andrii Bohutskyi d84c772b7e Implemented clients eager load 2 years ago
Olga Maciaszek-Sharma 0b5789f6ce Merge remote-tracking branch 'origin/3.1.x' 2 years ago
Olga Maciaszek-Sharma 12efda3e5c Merge remote-tracking branch 'origin/3.0.x' into 3.1.x 2 years ago
buildmaster ecfeb88362 Bumping versions 2 years ago
buildmaster dc2dc34583 Bumping versions 2 years ago
julianladisch 6c825ab1ca Bump spring-security-rsa to 1.0.11 (#1123) 2 years ago
julianladisch 0525fb686b
Bump spring-security-rsa to 1.0.11 (#1123) 2 years ago
buildmaster 764c08165f Bumping versions 2 years ago
buildmaster c843244d28 Bumping versions 2 years ago
buildmaster 3cfa13c967 Going back to snapshots 2 years ago
buildmaster 319394ec1d Update SNAPSHOT to 4.0.0-M3 2 years ago
Zen Huifer aa273f8af3
Adds: RegistrationLifecycle (#1044) 2 years ago
spencergibb 77eb281f34
Bumps to next snapshot version 3 years ago
spencergibb d8795d2316
Merge remote-tracking branch 'origin/3.1.x' into 3.1.x 3 years ago
buildmaster 6a1eadd8ad
Update SNAPSHOT to 3.1.3 3 years ago
Spencer Gibb 1c59951e9a
don't deploy docs 3 years ago
Olga Maciaszek-Sharma c2a22346cd Fix @LocalServerPort and @LocalManagementPort imports. 3 years ago
buildmaster ccd06bf76c Bumping versions 3 years ago
buildmaster 8ae7c5fe38 Bumping versions to 3.1.3-SNAPSHOT after release 3 years ago
buildmaster 80d399c255 Going back to snapshots 3 years ago
buildmaster 4a58471e2c Update SNAPSHOT to 3.1.2 3 years ago
Olga Maciaszek-Sharma d010885bfc Revert "Update SNAPSHOT to 3.1.2" 3 years ago
Olga Maciaszek-Sharma 31107af02d Revert "Going back to snapshots" 3 years ago
Olga Maciaszek-Sharma 52d40e58e3 Revert "Bumping versions to 3.1.3-SNAPSHOT after release" 3 years ago
Olga Maciaszek-Sharma 5b167f1ef2 Revert "Bumping versions" 3 years ago
buildmaster 3aa868b1c8 Bumping versions 3 years ago
buildmaster f17d06990a Bumping versions to 3.1.3-SNAPSHOT after release 3 years ago
buildmaster b61850b97d Going back to snapshots 3 years ago
buildmaster cb3d1d892f Update SNAPSHOT to 3.1.2 3 years ago
Olga Maciaszek-Sharma 9c40daa224 Merge remote-tracking branch 'origin/3.1.x' 3 years ago
Olga Maciaszek-Sharma 690d1d3cef
Request data context in blocking lb client (#1100) 3 years ago
Olga Maciaszek-Sharma 4682d0535c Merge remote-tracking branch 'origin/3.1.x' 3 years ago
Tommy Karlsson e293e694cb
Inject the class loader from the parent context into the child context (#1098) 3 years ago
Chanhyeong Cho 1eee03a313
Fix typo in spring-cloud-commons.adoc (#1096) 3 years ago
Olga Maciaszek-Sharma b818e72dc1 Merge remote-tracking branch 'origin/3.1.x' 3 years ago
Olga Maciaszek-Sharma 353d4f30c6 Fix test naming. 3 years ago
buildmaster c9f514ee3a Going back to snapshots 3 years ago
buildmaster 03baadb3e1 Update SNAPSHOT to 4.0.0-M2 3 years ago
Olga Maciaszek-Sharma 1c37df7a56 Edit ResponseData docs. 3 years ago
Olga Maciaszek-Sharma fbb5c920c4 Fix merge. 3 years ago
Olga Maciaszek-Sharma b991442f90 merge 3.1.x 3 years ago
Olga Maciaszek-Sharma c72f6d0795
Backport support for custom HTTP status in a backwards compatible way. (#1087) 3 years ago
spencergibb bed3e3de6e
Updates to use new boot 3 class in version verifier. 3 years ago
Olga Maciaszek-Sharma 63cbb815b0 Add missing properties to config and docs. 3 years ago
Olga Maciaszek-Sharma fedd786417 Merge remote-tracking branch 'origin/3.1.x' 3 years ago
Olga Maciaszek-Sharma 395386414d Add missing LB properties to additiona-spring-configuration-metadata and configprops. Fix typo. Fixes gh-1086. 3 years ago
Olga Maciaszek-Sharma 6d344c9581
Custom retry exceptions (#1085) 3 years ago
Olga Maciaszek-Sharma 66b295529e Merge remote-tracking branch 'origin/3.1.x' 3 years ago
Olga Maciaszek-Sharma 294badc4bf Reformat. 3 years ago
jizhuozhi 094514ec4b
Remove unnecessary sign check, whether positive or negative (#1078) 3 years ago
Olga Maciaszek-Sharma 14dd6425e7 Merge remote-tracking branch 'origin/3.1.x' 3 years ago
Olga Maciaszek-Sharma 71426cfa8a Expose indicators map - needed for a bugfix in SC Netflix. 3 years ago
spencergibb 97033063e5
Adds TestSocketUtils which was removed from framework 6 3 years ago
Olga Maciaszek-Sharma ab864281a3 Merge remote-tracking branch 'origin/3.1.x' 3 years ago
Olga Maciaszek-Sharma 6082154010 Reformat. 3 years ago
jizhuozhi 88c6a9e31f
Enforces the order of RoundRobinLoadBalancer when positive overflow (#1077) 3 years ago
Olga Maciaszek-Sharma e5ae816204
Use raw status codes in ResponseData. (#1073) 3 years ago
spencergibb a1f408c8e1
Fixes DefaultOkHttpClientFactoryTest to not use reflection 3 years ago
spencergibb 7817046f77
Fixes DefaultOkHttpClientFactoryTest to not use reflection 3 years ago
buildmaster 76d522c125 Bumping versions 3 years ago
Olga Maciaszek-Sharma e7b8960b65 Merge remote-tracking branch 'origin/3.1.x', reformat. Fix OkHttpClient test. 3 years ago
Olga Maciaszek-Sharma 9c3620b772 Reformat and regenerate docs. 3 years ago
Neil Powell 64b0d17e0b Support uri without port for default service instance (#1054) 3 years ago
Neil Powell 757900e77a
Support uri without port for default service instance (#1054) 3 years ago
Ryan Baxter f1be8803cc Make class abstract. Fixes #1069 3 years ago
buildmaster 7b8e7d9050 Bumping versions to 3.1.2-SNAPSHOT after release 3 years ago
buildmaster 80338bc99b Going back to snapshots 3 years ago
buildmaster 8925ab5e3f Update SNAPSHOT to 3.1.1 3 years ago
buildmaster a14efc17de Bumping versions 3 years ago
Ryan Baxter e69c61aee4 Merge branch '3.1.x' 3 years ago
L. Stitz 7401022838
Consider spring.profiles.active when resolving service ID. (#1064) 3 years ago
buildmaster 171c0a4485 Bumping versions 3 years ago
spencergibb 9eae606b18
Merge branch '3.1.x' 3 years ago
spencergibb b041b0a55d
Adds verifier support for boot 2.7 3 years ago
spencergibb 05382d3053
Return empty array if ConfigurationPropertySource.from returns null 3 years ago
spencergibb c9ee1fab60
Return empty array if ConfigurationPropertySource.from returns null 3 years ago
buildmaster 1ce1201e9d Going back to snapshots 3 years ago
buildmaster d49432a406 Update SNAPSHOT to 4.0.0-M1 3 years ago
spencergibb 14efdc71c7
formatting 3 years ago
spencergibb 29ea80fae1
changes milestone repository 3 years ago
buildmaster 5fc44a17a3 Bumping versions 3 years ago
spencergibb 0d7722dec8
Restores bootstrap functionality. 3 years ago
buildmaster e335b1245b Bumping versions 3 years ago
spencergibb 14923ae268
Make token relay require servlet web app 3 years ago
spencergibb cc99331339
Updates to 4.0.0-SNAPSHOT 3 years ago
spencergibb 5d0915b8ad
Removes old spring-security-oauth2. 3 years ago
spencergibb c93ffbf034
Removes old spring-security-oauth2. 3 years ago
spencergibb fedeb0aa4b
Removes old spring-security-oauth2. 3 years ago
spencergibb 4d9d242841
Compatibility updates for framework 6 and boot 3 3 years ago
spencergibb 1f3977e5f7
Updates sdkmanrc to 17 3 years ago
spencergibb db4fac1ce4
Merge branch '3.1.x' 3 years ago
spencergibb 7e7ef895d5
Adds .sdkmanrc 3 years ago
spencergibb 953fc38cea
Updates to 4.0.0-SNAPSHOT 3 years ago
spencergibb 8807b4dac0
Merge branch '3.0.x' 3 years ago
Olga MaciaszekSharma 4a6b194907 Merge remote-tracking branch 'origin/3.0.x' 3 years ago
buildmaster 208fecdaa1 Bumping versions 3 years ago
buildmaster 5fc236cdac Bumping versions to 3.1.1-SNAPSHOT after release 3 years ago
buildmaster de0fb67135 Going back to snapshots 3 years ago
buildmaster 5179927052 Update SNAPSHOT to 3.1.0 3 years ago
Olga MaciaszekSharma 0f2a36d8f8 Refactor. 3 years ago
Olga MaciaszekSharma d00a66d2ea Merge remote-tracking branch 'origin/3.0.x' 3 years ago
Olga Maciaszek-Sharma a87f6c7d90
Add duplicate plugin. Remove class duplicates. (#1047) 3 years ago
Olga MaciaszekSharma 334f2192de Merge remote-tracking branch 'origin/3.0.x' 3 years ago
spencergibb 4967442474
Re-enables disabled tests. 3 years ago
L. Stitz 51aec79bb4
Add spring-cloud-test-support. (#1045) 3 years ago
buildmaster c3ffffb099 Bumping versions 3 years ago
spencergibb e47a3a08ce
Temporarily disables tests. 3 years ago
Olga Maciaszek-Sharma d639552fb8
Support setting custom port for LB health-checks. (#1039) 3 years ago
Olga MaciaszekSharma f5da442726 Increase visibility of LoadBalancerRetryContext. Fixes gh-1038. 3 years ago
Olga MaciaszekSharma a71a1e2b4c Use new LoadBalancerServiceInstanceCookieTransformer constructor. 3 years ago
buildmaster a7fb100201 Going back to snapshots 3 years ago
buildmaster fc98bc205f Update SNAPSHOT to 3.1.0-RC1 3 years ago
Olga Maciaszek-Sharma a61593ff3b
Fix handling transformers properties. (#1037) 3 years ago
Olga Maciaszek-Sharma f30afc1983
Handle conditionals for client properties (#1033) 3 years ago
Olga Maciaszek-Sharma 68d43a177e
Switch to using LB per-client properties. Add deprecation docs. (#1036) 3 years ago
Olga Maciaszek-Sharma 181e452aec
Make XForwardedHeadersTransformer work with client properties. (#1035) 3 years ago
Olga Maciaszek-Sharma 331b523513
Handle null serviceId. (#1034) 3 years ago
Olga MaciaszekSharma 7cb8c34978 Refactor. 3 years ago
Olga MaciaszekSharma e3fc8bd782 Refactor tets. 3 years ago
gandhiUH a59b3f6031 added X-forward-Host and X-Forward-Proto 3 years ago
buildmaster adf1fbb2a6 Bumping versions 3 years ago
Spencer Gibb 3a6a9e0a91
Adds config per load balancer client. (#1028) 3 years ago
Tim te Beek 95ce58741d
Increase JUnit5 usage (#1020) 3 years ago
buildmaster 3beb53a089 Going back to snapshots 3 years ago
buildmaster 20a36980bd Update SNAPSHOT to 3.1.0-M3 3 years ago
spencergibb d3c595afbb
updates tests to use updated Mockito classes 3 years ago
Olga MaciaszekSharma 8b96eab186 Switch to new Spring Hateoas API. 3 years ago
buildmaster 779d482730 Going back to snapshots 3 years ago
buildmaster 7142c082c5 Update SNAPSHOT to 3.1.0-M2 3 years ago
buildmaster 712e3ba9e8 Bumping versions 3 years ago
干货满满张哈希 bc0d54bfd3
add getter for parent to fix: https://github.com/spring-cloud/spring-cloud-sleuth/issues/2023 (#1012) 3 years ago
Robert McNees 03fd58cd53
Skip health check if null or empty (#1011) 3 years ago
Ryan Baxter 38aa3acaca Merge branch '3.0.x' into main 3 years ago
Ryan Baxter 67144a63b2
Take into account spring.config.imports in referenced imports. Fixes #1006 (#1007) 3 years ago
Olga MaciaszekSharma d85dd9bdcb Merge remote-tracking branch 'origin/3.0.x' 3 years ago
Olga MaciaszekSharma 002fa303ca Merge remote-tracking branch 'origin/3.0.x' 3 years ago
limo520 4bfb6fe4e4
Fix SimpleReactiveDiscoveryClientTests (#1003) 3 years ago
qxo b647ccb86a
fix: remove unnecessary code (#1000) 3 years ago
buildmaster 1c776cc413 Bumping versions 3 years ago
Ryan Baxter adce4476fa Merge branch '3.0.x' into main 3 years ago
buildmaster 41f7af42b7 Going back to snapshots 3 years ago
buildmaster 958410f11c Update SNAPSHOT to 3.1.0-M1 3 years ago
Olga MaciaszekSharma bc42390206 Refactor and add javadocs. 3 years ago
sabyasachi de32d2b68c Issue-906 Adding support for query param in lb health-check 3 years ago
Olga MaciaszekSharma bd8d640c42 Reformat with updated plugin. 3 years ago
Olga MaciaszekSharma c009fd159d Merge remote-tracking branch 'origin/3.0.x' 3 years ago
Zhiguo.Chen 9feb443009
Add `with()` method to support external ServiceInstanceListSupplier(#988) (#989) 3 years ago
Olga MaciaszekSharma 9b97470296 Merge remote-tracking branch 'origin/3.0.x' 3 years ago
Olga MaciaszekSharma 4eae197929 Merge remote-tracking branch 'origin/3.0.x' 3 years ago
Yanming Zhou 5c0fc1425f
Fix typo (#985) 3 years ago
Olga MaciaszekSharma d6c9b1583c Fix outdated API calls. 3 years ago
Olga MaciaszekSharma 771907e475 Merge remote-tracking branch 'origin/main' 3 years ago
spencergibb cfa273be8f
updates javadoc 3 years ago
Robert McNees ea459cee64
Issue 973 - Update Unit version - spring-cloud-context (#977) 3 years ago
Marcin Grzejszczak d43a4acd2f Updated maven wrapper to use Maven 3.6.3 3 years ago
Marcin Grzejszczak 2c5befcb53 Fixed symlink 3 years ago
Jonathan Schneider e1a31619cc
Polish `@RequestMapping` annotations (#979) 3 years ago
spencergibb f8f549cc72
Updated SpringBootVersionVerifier to require boot 2.6 3 years ago
spencergibb 85f95ceb0a
Updates to version 3.1.0-SNAPSHOT 3 years ago
Olga MaciaszekSharma a23bdb8845 Merge remote-tracking branch 'origin/2.2.x' 3 years ago
Olga MaciaszekSharma f90f11d7b1 Fixes gh-898. 3 years ago
o.gusev b628338e54 Fixes gh-898 3 years ago
  1. 39
      .circleci/config.yml
  2. 49
      .github/dependabot.yml
  3. 33
      .github/workflows/deploy-docs.yml
  4. 42
      .github/workflows/maven.yml
  5. 6
      .gitignore
  6. 1
      .java-version
  7. 117
      .mvn/wrapper/MavenWrapperDownloader.java
  8. BIN
      .mvn/wrapper/maven-wrapper.jar
  9. 3
      .mvn/wrapper/maven-wrapper.properties
  10. 3
      .sdkmanrc
  11. 338
      README.adoc
  12. 39
      docs/antora-playbook.yml
  13. 12
      docs/antora.yml
  14. 11
      docs/modules/ROOT/nav.adoc
  15. 12
      docs/modules/ROOT/pages/appendix.adoc
  16. 6
      docs/modules/ROOT/pages/configprops.adoc
  17. 9
      docs/modules/ROOT/pages/index.adoc
  18. 3
      docs/modules/ROOT/pages/intro.adoc
  19. 17
      docs/modules/ROOT/pages/spring-cloud-circuitbreaker.adoc
  20. 261
      docs/modules/ROOT/pages/spring-cloud-commons/application-context-services.adoc
  21. 15
      docs/modules/ROOT/pages/spring-cloud-commons/cachedrandompropertysource.adoc
  22. 595
      docs/modules/ROOT/pages/spring-cloud-commons/common-abstractions.adoc
  23. 515
      docs/modules/ROOT/pages/spring-cloud-commons/loadbalancer.adoc
  24. 89
      docs/modules/ROOT/pages/spring-cloud-commons/security.adoc
  25. 3
      docs/modules/ROOT/partials/_attributes.adoc
  26. 84
      docs/modules/ROOT/partials/_configprops.adoc
  27. 11
      docs/modules/ROOT/partials/_conventions.adoc
  28. 70
      docs/modules/ROOT/partials/_metrics.adoc
  29. 44
      docs/modules/ROOT/partials/_spans.adoc
  30. 59
      docs/pom.xml
  31. 20
      docs/src/main/antora/resources/antora-resources/antora.yml
  32. 11
      docs/src/main/asciidoc/README.adoc
  33. 16
      docs/src/main/asciidoc/_attributes.adoc
  34. 65
      docs/src/main/asciidoc/_configprops.adoc
  35. 330
      docs/src/main/asciidoc/ghpages.sh
  36. 1
      docs/src/main/asciidoc/index.adoc
  37. 8
      docs/src/main/asciidoc/jce.adoc
  38. 1359
      docs/src/main/asciidoc/spring-cloud-commons.adoc
  39. 199
      mvnw
  40. 55
      mvnw.cmd
  41. 41
      pom.xml
  42. 19
      spring-cloud-commons-dependencies/pom.xml
  43. 89
      spring-cloud-commons/pom.xml
  44. 3
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/CommonsClientAutoConfiguration.java
  45. 14
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/DefaultServiceInstance.java
  46. 5
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/HostInfoEnvironmentPostProcessor.java
  47. 46
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/SpringCloudApplication.java
  48. 9
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/FeaturesEndpoint.java
  49. 4
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/HasFeatures.java
  50. 2
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/CircuitBreaker.java
  51. 43
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/EnableCircuitBreaker.java
  52. 36
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/EnableCircuitBreakerImportSelector.java
  53. 64
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/CircuitBreakerObservationContext.java
  54. 35
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/CircuitBreakerObservationConvention.java
  55. 83
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/CircuitBreakerObservationDocumentation.java
  56. 55
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/DefaultCircuitBreakerObservationConvention.java
  57. 67
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/ObservedCircuitBreaker.java
  58. 51
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/ObservedFunction.java
  59. 51
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/ObservedSupplier.java
  60. 3
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelector.java
  61. 30
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/ReactiveDiscoveryClient.java
  62. 12
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClient.java
  63. 2
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/InstanceRegisteredEvent.java
  64. 8
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorProperties.java
  65. 2
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthContributor.java
  66. 49
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/reactive/ReactiveDiscoveryClientHealthIndicator.java
  67. 2
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/reactive/ReactiveDiscoveryCompositeHealthContributor.java
  68. 11
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryProperties.java
  69. 9
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/reactive/SimpleReactiveDiscoveryProperties.java
  70. 10
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResourceRefresher.java
  71. 83
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerAutoConfiguration.java
  72. 49
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerInterceptor.java
  73. 69
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerRequest.java
  74. 6
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeException.java
  75. 3
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultRequest.java
  76. 3
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultRequestContext.java
  77. 3
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultResponse.java
  78. 3
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/HintRequestContext.java
  79. 3
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/InterceptorRetryPolicy.java
  80. 3
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRecoveryCallback.java
  81. 8
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryPolicy.java
  82. 9
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfiguration.java
  83. 43
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerClientsProperties.java
  84. 46
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerDefaultMappingsProviderAutoConfiguration.java
  85. 27
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerEagerLoadProperties.java
  86. 130
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerProperties.java
  87. 8
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RequestData.java
  88. 11
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ResponseData.java
  89. 33
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java
  90. 3
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryableRequestContext.java
  91. 69
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerRetryContext.java
  92. 12
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerRetryPolicy.java
  93. 5
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancer.java
  94. 19
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerClientAutoConfiguration.java
  95. 25
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerExchangeFilterFunction.java
  96. 27
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableExchangeFilterFunctionLoadBalancerRetryPolicy.java
  97. 77
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableLoadBalancerExchangeFilterFunction.java
  98. 2
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableStatusCodeException.java
  99. 75
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistration.java
  100. 9
      spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationAutoConfiguration.java
  101. Some files were not shown because too many files have changed in this diff Show More

39
.circleci/config.yml

@ -1,39 +0,0 @@ @@ -1,39 +0,0 @@
version: 2
jobs:
build:
docker:
- image: springcloud/pipeline-base
user: appuser
environment:
_JAVA_OPTIONS: "-Xms1024m -Xmx2048m"
TERM: dumb
branches:
ignore:
- gh-pages # list of branches to ignore
steps:
- checkout
- restore_cache:
key: sc-commons-{{ .Branch }}
- run:
name: "Download dependencies"
command: ./mvnw -s .settings.xml -U --fail-never dependency:go-offline || true
- save_cache:
key: sc-commons-{{ .Branch }}
paths:
- ~/.m2
- run:
name: "Running build"
command: ./mvnw -s .settings.xml clean org.jacoco:jacoco-maven-plugin:prepare-agent install -U -P sonar -nsu --batch-mode -Dmaven.test.redirectTestOutputToFile=true -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- run:
name: "Aggregate test results"
when: always
command: |
mkdir -p ~/junit/
find . -type f -regex ".*/target/.*-reports/.*" -exec cp {} ~/junit/ \;
bash <(curl -s https://codecov.io/bash)
- store_artifacts:
path: ~/junit/
destination: artifacts
- store_test_results:
path: ~/junit/
destination: testartifacts

49
.github/dependabot.yml

@ -0,0 +1,49 @@ @@ -0,0 +1,49 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
target-branch: "3.1.x" # oldest OSS supported branch
schedule:
interval: "weekly"
- package-ecosystem: "github-actions"
directory: "/"
target-branch: "4.0.x" # oldest OSS supported branch
schedule:
interval: "weekly"
- package-ecosystem: "github-actions"
directory: "/"
target-branch: "main"
schedule:
interval: "weekly"
- package-ecosystem: maven
directory: /
schedule:
interval: daily
target-branch: 3.1.x
ignore:
# only upgrade patch versions for maintenance branch
- dependency-name: "*"
update-types:
- version-update:semver-major
- version-update:semver-minor
- package-ecosystem: maven
directory: /
schedule:
interval: daily
target-branch: 4.0.x
ignore:
# only upgrade patch versions for maintenance branch
- dependency-name: "*"
update-types:
- version-update:semver-major
- version-update:semver-minor
- package-ecosystem: maven
directory: /
schedule:
interval: daily
target-branch: main
ignore:
# only upgrade by minor or patch
- dependency-name: "*"
update-types:
- version-update:semver-major

33
.github/workflows/deploy-docs.yml

@ -0,0 +1,33 @@ @@ -0,0 +1,33 @@
name: Deploy Docs
on:
push:
branches-ignore: [ gh-pages ]
tags: '**'
repository_dispatch:
types: request-build-reference # legacy
#schedule:
#- cron: '0 10 * * *' # Once per day at 10am UTC
workflow_dispatch:
permissions:
actions: write
jobs:
build:
runs-on: ubuntu-latest
# FIXME: enable when pushed to spring-projects
# if: github.repository_owner == 'spring-projects'
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: docs-build
fetch-depth: 1
- name: Dispatch (partial build)
if: github.ref_type == 'branch'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: gh workflow run deploy-docs.yml -r $(git rev-parse --abbrev-ref HEAD) -f build-refname=${{ github.ref_name }}
- name: Dispatch (full build)
if: github.ref_type == 'tag'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: gh workflow run deploy-docs.yml -r $(git rev-parse --abbrev-ref HEAD)

42
.github/workflows/maven.yml

@ -0,0 +1,42 @@ @@ -0,0 +1,42 @@
# This workflow will build a Java project with Maven
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Build
on:
push:
branches: [ main, 4.0.x, 3.1.x ]
pull_request:
branches: [ main, 4.0.x, 3.1.x ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '17'
- name: Cache local Maven repository
uses: actions/cache@v3
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Build with Maven
run: ./mvnw -s .settings.xml clean org.jacoco:jacoco-maven-plugin:prepare-agent install -U -P sonar -nsu --batch-mode -Dmaven.test.redirectTestOutputToFile=true -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn
- name: Publish Test Report
uses: mikepenz/action-junit-report@v4
if: always() # always run even if the previous step fails
with:
report_paths: '**/surefire-reports/TEST-*.xml'
- name: Archive code coverage results
uses: actions/upload-artifact@v3
with:
name: surefire-reports
path: '**/surefire-reports/*'

6
.gitignore vendored

@ -21,4 +21,8 @@ _site/ @@ -21,4 +21,8 @@ _site/
antrun
.vscode/
.flattened-pom.xml
.sdkmanrc
node
node_modules
build
package.json
package-lock.json

1
.java-version

@ -0,0 +1 @@ @@ -0,0 +1 @@
17

117
.mvn/wrapper/MavenWrapperDownloader.java vendored

@ -0,0 +1,117 @@ @@ -0,0 +1,117 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

BIN
.mvn/wrapper/maven-wrapper.jar vendored

Binary file not shown.

3
.mvn/wrapper/maven-wrapper.properties vendored

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

3
.sdkmanrc

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

338
README.adoc

@ -5,337 +5,15 @@ Edit the files in the src/main/asciidoc/ directory instead. @@ -5,337 +5,15 @@ Edit the files in the src/main/asciidoc/ directory instead.
////
image::https://circleci.com/gh/spring-cloud/spring-cloud-commons.svg?style=svg[Build Status, link=https://circleci.com/gh/spring-cloud/spring-cloud-commons]
[[building]]
= Building
:page-section-summary-toc: 1
https://pivotal.io/platform-as-a-service/migrating-to-cloud-native-application-architectures-ebook[Cloud Native] is a style of application development that encourages easy adoption of best practices in the areas of continuous delivery and value-driven development.
A related discipline is that of building https://12factor.net/[12-factor Applications], in which development practices are aligned with delivery and operations goals -- for instance, by using declarative programming and management and monitoring.
Spring Cloud facilitates these styles of development in a number of specific ways.
The starting point is a set of features to which all components in a distributed system need easy access.
Unresolved directive in <stdin> - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/docs/src/main/asciidoc/building.adoc[]
Many of those features are covered by https://projects.spring.io/spring-boot[Spring Boot], on which Spring Cloud builds. Some more features are delivered by Spring Cloud as two libraries: Spring Cloud Context and Spring Cloud Commons.
Spring Cloud Context provides utilities and special services for the `ApplicationContext` of a Spring Cloud application (bootstrap context, encryption, refresh scope, and environment endpoints). Spring Cloud Commons is a set of abstractions and common classes used in different Spring Cloud implementations (such as Spring Cloud Netflix and Spring Cloud Consul).
If you get an exception due to "Illegal key size" and you use Sun's JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files.
See the following links for more information:
* https://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html[Java 6 JCE]
* https://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html[Java 7 JCE]
* https://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html[Java 8 JCE]
Extract the files into the JDK/jre/lib/security folder for whichever version of JRE/JDK x64/x86 you use.
== Building
:jdkversion: 17
=== Basic Compile and Test
To build the source you will need to install JDK {jdkversion}.
Spring Cloud uses Maven for most build-related activities, and you
should be able to get off the ground quite quickly by cloning the
project you are interested in and typing
----
$ ./mvnw install
----
NOTE: You can also install Maven (>=3.3.3) yourself and run the `mvn` command
in place of `./mvnw` in the examples below. If you do that you also
might need to add `-P spring` if your local Maven settings do not
contain repository declarations for spring pre-release artifacts.
NOTE: Be aware that you might need to increase the amount of memory
available to Maven by setting a `MAVEN_OPTS` environment variable with
a value like `-Xmx512m -XX:MaxPermSize=128m`. We try to cover this in
the `.mvn` configuration, so if you find you have to do it to make a
build succeed, please raise a ticket to get the settings added to
source control.
The projects that require middleware (i.e. Redis) for testing generally
require that a local instance of [Docker](https://www.docker.com/get-started) is installed and running.
=== Documentation
The spring-cloud-build module has a "docs" profile, and if you switch
that on it will try to build asciidoc sources from
`src/main/asciidoc`. As part of that process it will look for a
`README.adoc` and process it by loading all the includes, but not
parsing or rendering it, just copying it to `${main.basedir}`
(defaults to `${basedir}`, i.e. the root of the project). If there are
any changes in the README it will then show up after a Maven build as
a modified file in the correct place. Just commit it and push the change.
=== Working with the code
If you don't have an IDE preference we would recommend that you use
https://www.springsource.com/developer/sts[Spring Tools Suite] or
https://eclipse.org[Eclipse] when working with the code. We use the
https://eclipse.org/m2e/[m2eclipse] eclipse plugin for maven support. Other IDEs and tools
should also work without issue as long as they use Maven 3.3.3 or better.
==== Activate the Spring Maven profile
Spring Cloud projects require the 'spring' Maven profile to be activated to resolve
the spring milestone and snapshot repositories. Use your preferred IDE to set this
profile to be active, or you may experience build errors.
==== Importing into eclipse with m2eclipse
We recommend the https://eclipse.org/m2e/[m2eclipse] eclipse plugin when working with
eclipse. If you don't already have m2eclipse installed it is available from the "eclipse
marketplace".
NOTE: Older versions of m2e do not support Maven 3.3, so once the
projects are imported into Eclipse you will also need to tell
m2eclipse to use the right profile for the projects. If you
see many different errors related to the POMs in the projects, check
that you have an up to date installation. If you can't upgrade m2e,
add the "spring" profile to your `settings.xml`. Alternatively you can
copy the repository settings from the "spring" profile of the parent
pom into your `settings.xml`.
==== Importing into eclipse without m2eclipse
If you prefer not to use m2eclipse you can generate eclipse project metadata using the
following command:
[indent=0]
----
$ ./mvnw eclipse:eclipse
----
The generated eclipse projects can be imported by selecting `import existing projects`
from the `file` menu.
== Contributing
:spring-cloud-build-branch: master
Spring Cloud is released under the non-restrictive Apache 2.0 license,
and follows a very standard Github development process, using Github
tracker for issues and merging pull requests into master. If you want
to contribute even something trivial please do not hesitate, but
follow the guidelines below.
=== Sign the Contributor License Agreement
Before we accept a non-trivial patch or pull request we will need you to sign the
https://cla.pivotal.io/sign/spring[Contributor License Agreement].
Signing the contributor's agreement does not grant anyone commit rights to the main
repository, but it does mean that we can accept your contributions, and you will get an
author credit if we do. Active contributors might be asked to join the core team, and
given the ability to merge pull requests.
=== Code of Conduct
This project adheres to the Contributor Covenant https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc[code of
conduct]. By participating, you are expected to uphold this code. Please report
unacceptable behavior to spring-code-of-conduct@pivotal.io.
=== Code Conventions and Housekeeping
None of these is essential for a pull request, but they will all help. They can also be
added after the original pull request but before a merge.
* Use the Spring Framework code format conventions. If you use Eclipse
you can import formatter settings using the
`eclipse-code-formatter.xml` file from the
https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml[Spring
Cloud Build] project. If using IntelliJ, you can use the
https://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter
Plugin] to import the same file.
* Make sure all new `.java` files to have a simple Javadoc class comment with at least an
`@author` tag identifying you, and preferably at least a paragraph on what the class is
for.
* Add the ASF license header comment to all new `.java` files (copy from existing files
in the project)
* Add yourself as an `@author` to the .java files that you modify substantially (more
than cosmetic changes).
* Add some Javadocs and, if you change the namespace, some XSD doc elements.
* A few unit tests would help a lot as well -- someone has to do it.
* If no-one else is using your branch, please rebase it against the current master (or
other target branch in the main project).
* When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions],
if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit
message (where XXXX is the issue number).
=== Checkstyle
Spring Cloud Build comes with a set of checkstyle rules. You can find them in the `spring-cloud-build-tools` module. The most notable files under the module are:
.spring-cloud-build-tools/
----
└── src
   ├── checkstyle
     └── checkstyle-suppressions.xml <3>
   └── main
   └── resources
   ├── checkstyle-header.txt <2>
   └── checkstyle.xml <1>
----
<1> Default Checkstyle rules
<2> File header setup
<3> Default suppression rules
==== Checkstyle configuration
Checkstyle rules are *disabled by default*. To add checkstyle to your project just define the following properties and plugins.
.pom.xml
----
<properties>
<maven-checkstyle-plugin.failsOnError>true</maven-checkstyle-plugin.failsOnError> <1>
<maven-checkstyle-plugin.failsOnViolation>true
</maven-checkstyle-plugin.failsOnViolation> <2>
<maven-checkstyle-plugin.includeTestSourceDirectory>true
</maven-checkstyle-plugin.includeTestSourceDirectory> <3>
</properties>
<build>
<plugins>
<plugin> <4>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
</plugin>
<plugin> <5>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
<reporting>
<plugins>
<plugin> <5>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</reporting>
</build>
----
<1> Fails the build upon Checkstyle errors
<2> Fails the build upon Checkstyle violations
<3> Checkstyle analyzes also the test sources
<4> Add the Spring Java Format plugin that will reformat your code to pass most of the Checkstyle formatting rules
<5> Add checkstyle plugin to your build and reporting phases
If you need to suppress some rules (e.g. line length needs to be longer), then it's enough for you to define a file under `${project.root}/src/checkstyle/checkstyle-suppressions.xml` with your suppressions. Example:
.projectRoot/src/checkstyle/checkstyle-suppresions.xml
----
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Puppy Crawl//DTD Suppressions 1.1//EN"
"https://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
<suppress files=".*ConfigServerApplication\.java" checks="HideUtilityClassConstructor"/>
<suppress files=".*ConfigClientWatch\.java" checks="LineLengthCheck"/>
</suppressions>
----
It's advisable to copy the `${spring-cloud-build.rootFolder}/.editorconfig` and `${spring-cloud-build.rootFolder}/.springformat` to your project. That way, some default formatting rules will be applied. You can do so by running this script:
```bash
$ curl https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/.editorconfig -o .editorconfig
$ touch .springformat
```
=== IDE setup
==== Intellij IDEA
In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin.
The following files can be found in the https://github.com/spring-cloud/spring-cloud-build/tree/master/spring-cloud-build-tools[Spring Cloud Build] project.
.spring-cloud-build-tools/
----
└── src
   ├── checkstyle
     └── checkstyle-suppressions.xml <3>
   └── main
   └── resources
   ├── checkstyle-header.txt <2>
   ├── checkstyle.xml <1>
   └── intellij
      ├── Intellij_Project_Defaults.xml <4>
      └── Intellij_Spring_Boot_Java_Conventions.xml <5>
----
<1> Default Checkstyle rules
<2> File header setup
<3> Default suppression rules
<4> Project defaults for Intellij that apply most of Checkstyle rules
<5> Project style conventions for Intellij that apply most of Checkstyle rules
.Code style
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-code-style.png[Code style]
Go to `File` -> `Settings` -> `Editor` -> `Code style`. There click on the icon next to the `Scheme` section. There, click on the `Import Scheme` value and pick the `Intellij IDEA code style XML` option. Import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml` file.
.Inspection profiles
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-inspections.png[Code style]
Go to `File` -> `Settings` -> `Editor` -> `Inspections`. There click on the icon next to the `Profile` section. There, click on the `Import Profile` and import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml` file.
.Checkstyle
To have Intellij work with Checkstyle, you have to install the `Checkstyle` plugin. It's advisable to also install the `Assertions2Assertj` to automatically convert the JUnit assertions
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-checkstyle.png[Checkstyle]
Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on the `+` icon in the `Configuration file` section. There, you'll have to define where the checkstyle rules should be picked from. In the image above, we've picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build's GitHub repository (e.g. for the `checkstyle.xml` : `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml`). We need to provide the following variables:
- `checkstyle.header.file` - please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` URL.
- `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` URL.
- `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`.
IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources.
=== Duplicate Finder
Spring Cloud Build brings along the `basepom:duplicate-finder-maven-plugin`, that enables flagging duplicate and conflicting classes and resources on the java classpath.
==== Duplicate Finder configuration
Duplicate finder is *enabled by default* and will run in the `verify` phase of your Maven build, but it will only take effect in your project if you add the `duplicate-finder-maven-plugin` to the `build` section of the projecst's `pom.xml`.
.pom.xml
[source,xml]
----
<build>
<plugins>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
----
For other properties, we have set defaults as listed in the https://github.com/basepom/duplicate-finder-maven-plugin/wiki[plugin documentation].
You can easily override them but setting the value of the selected property prefixed with `duplicate-finder-maven-plugin`. For example, set `duplicate-finder-maven-plugin.skip` to `true` in order to skip duplicates check in your build.
If you need to add `ignoredClassPatterns` or `ignoredResourcePatterns` to your setup, make sure to add them in the plugin configuration section of your project:
[source,xml]
----
<build>
<plugins>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
<configuration>
<ignoredClassPatterns>
<ignoredClassPattern>org.joda.time.base.BaseDateTime</ignoredClassPattern>
<ignoredClassPattern>.*module-info</ignoredClassPattern>
</ignoredClassPatterns>
<ignoredResourcePatterns>
<ignoredResourcePattern>changelog.txt</ignoredResourcePattern>
</ignoredResourcePatterns>
</configuration>
</plugin>
</plugins>
</build>
----
[[contributing]]
= Contributing
:page-section-summary-toc: 1
Unresolved directive in <stdin> - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/docs/src/main/asciidoc/contributing.adoc[]

39
docs/antora-playbook.yml

@ -0,0 +1,39 @@ @@ -0,0 +1,39 @@
antora:
extensions:
- '@springio/antora-extensions/partial-build-extension'
- require: '@springio/antora-extensions/latest-version-extension'
- require: '@springio/antora-extensions/inject-collector-cache-config-extension'
- '@antora/collector-extension'
- '@antora/atlas-extension'
- require: '@springio/antora-extensions/root-component-extension'
root_component_name: 'cloud-commons'
- '@springio/antora-extensions/static-page-extension'
site:
title: Spring Cloud Commons
url: https://docs.spring.io/spring-cloud-commons/reference/
content:
sources:
- url: ./..
branches: HEAD
start_path: docs
worktrees: true
asciidoc:
attributes:
page-stackoverflow-url: https://stackoverflow.com/tags/spring-cloud
page-pagination: ''
hide-uri-scheme: '@'
tabs-sync-option: '@'
chomp: 'all'
extensions:
- '@asciidoctor/tabs'
- '@springio/asciidoctor-extensions'
sourcemap: true
urls:
latest_version_segment: ''
runtime:
log:
failure_level: warn
format: pretty
ui:
bundle:
url: https://github.com/spring-io/antora-ui-spring/releases/download/v0.4.2/ui-bundle.zip

12
docs/antora.yml

@ -0,0 +1,12 @@ @@ -0,0 +1,12 @@
name: cloud-commons
version: true
title: Spring Cloud Commons
nav:
- modules/ROOT/nav.adoc
ext:
collector:
run:
command: ./mvnw --no-transfer-progress -B process-resources -Pdocs -pl docs -Dantora-maven-plugin.phase=none -Dgenerate-docs.phase=none -Dgenerate-readme.phase=none -Dgenerate-cloud-resources.phase=none -Dmaven-dependency-plugin-for-docs.phase=none -Dmaven-dependency-plugin-for-docs-classes.phase=none -DskipTests
local: true
scan:
dir: ./target/classes/antora-resources/

11
docs/modules/ROOT/nav.adoc

@ -0,0 +1,11 @@ @@ -0,0 +1,11 @@
* xref:index.adoc[]
** xref:intro.adoc[]
** xref:spring-cloud-commons/application-context-services.adoc[]
** xref:spring-cloud-commons/common-abstractions.adoc[]
** xref:spring-cloud-commons/loadbalancer.adoc[]
** xref:spring-cloud-commons/cachedrandompropertysource.adoc[]
** xref:spring-cloud-commons/security.adoc[]
* xref:spring-cloud-circuitbreaker.adoc[]
* xref:appendix.adoc[]
** xref:configprops.adoc[]

12
docs/src/main/asciidoc/appendix.adoc → docs/modules/ROOT/pages/appendix.adoc

@ -1,9 +1,8 @@ @@ -1,9 +1,8 @@
:numbered!:
[appendix]
[[common-application-properties]]
== Common application properties
= Common application properties
include::_attributes.adoc[]
include::partial$_attributes.adoc[]
Various properties can be specified inside your `application.properties` file, inside your `application.yml` file, or as command line switches.
This appendix provides a list of common {project-full-name} properties and references to the underlying classes that consume them.
@ -11,4 +10,9 @@ This appendix provides a list of common {project-full-name} properties and refer @@ -11,4 +10,9 @@ This appendix provides a list of common {project-full-name} properties and refer
NOTE: Property contributions can come from additional jar files on your classpath, so you should not consider this an exhaustive list.
Also, you can define your own properties.
include::_configprops.adoc[]
[[observability]]
== Observability metadata
include::partial$_metrics.adoc[]
include::partial$_spans.adoc[]

6
docs/modules/ROOT/pages/configprops.adoc

@ -0,0 +1,6 @@ @@ -0,0 +1,6 @@
[[configuration-properties]]
= Configuration Properties
Below you can find a list of configuration properties.
include::partial$_configprops.adoc[]

9
docs/modules/ROOT/pages/index.adoc

@ -0,0 +1,9 @@ @@ -0,0 +1,9 @@
[[cloud-native-applications]]
= Cloud Native Applications
include::partial$_attributes.adoc[]
// TODO: figure out remote includes in docs and replace pasted text
// include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing-docs.adoc[]
NOTE: Spring Cloud is released under the non-restrictive Apache 2.0 license.
If you would like to contribute to this section of the documentation or if you find an error, you can find the source code and issue trackers for the project at {github-issues}[github].

3
docs/src/main/asciidoc/intro.adoc → docs/modules/ROOT/pages/intro.adoc

@ -1,3 +1,5 @@ @@ -1,3 +1,5 @@
[[introduction]]
= Introduction
https://pivotal.io/platform-as-a-service/migrating-to-cloud-native-application-architectures-ebook[Cloud Native] is a style of application development that encourages easy adoption of best practices in the areas of continuous delivery and value-driven development.
A related discipline is that of building https://12factor.net/[12-factor Applications], in which development practices are aligned with delivery and operations goals -- for instance, by using declarative programming and management and monitoring.
@ -7,4 +9,3 @@ Spring Cloud facilitates these styles of development in a number of specific way @@ -7,4 +9,3 @@ Spring Cloud facilitates these styles of development in a number of specific way
Many of those features are covered by https://projects.spring.io/spring-boot[Spring Boot], on which Spring Cloud builds. Some more features are delivered by Spring Cloud as two libraries: Spring Cloud Context and Spring Cloud Commons.
Spring Cloud Context provides utilities and special services for the `ApplicationContext` of a Spring Cloud application (bootstrap context, encryption, refresh scope, and environment endpoints). Spring Cloud Commons is a set of abstractions and common classes used in different Spring Cloud implementations (such as Spring Cloud Netflix and Spring Cloud Consul).
include::jce.adoc[]

17
docs/src/main/asciidoc/spring-cloud-circuitbreaker.adoc → docs/modules/ROOT/pages/spring-cloud-circuitbreaker.adoc

@ -1,9 +1,11 @@ @@ -1,9 +1,11 @@
== Introduction
[[introduction]]
= Spring Cloud Circuit Breaker
Spring Cloud Circuit breaker provides an abstraction across different circuit breaker implementations.
It provides a consistent API to use in your applications, letting you, the developer, choose the circuit breaker implementation that best fits your needs for your application.
=== Supported Implementations
[[supported-implementations]]
== Supported Implementations
Spring Cloud supports the following circuit-breaker implementations:
@ -11,12 +13,12 @@ Spring Cloud supports the following circuit-breaker implementations: @@ -11,12 +13,12 @@ Spring Cloud supports the following circuit-breaker implementations:
* https://github.com/alibaba/Sentinel[Sentinel]
* https://github.com/spring-projects/spring-retry[Spring Retry]
[[core-concepts]]
== Core Concepts
To create a circuit breaker in your code, you can use the `CircuitBreakerFactory` API. When you include a Spring Cloud Circuit Breaker starter on your classpath, a bean that implements this API is automatically created for you.
The following example shows a simple example of how to use this API:
====
[source,java]
----
@Service
@ -35,7 +37,6 @@ public static class DemoControllerService { @@ -35,7 +37,6 @@ public static class DemoControllerService {
}
----
====
The `CircuitBreakerFactory.create` API creates an instance of a class called `CircuitBreaker`.
The `run` method takes a `Supplier` and a `Function`.
@ -44,12 +45,12 @@ The `Function` is the fallback that is run if the circuit breaker is tripped. @@ -44,12 +45,12 @@ The `Function` is the fallback that is run if the circuit breaker is tripped.
The function is passed the `Throwable` that caused the fallback to be triggered.
You can optionally exclude the fallback if you do not want to provide one.
[[circuit-breakers-in-reactive-code]]
=== Circuit Breakers In Reactive Code
If Project Reactor is on the class path, you can also use `ReactiveCircuitBreakerFactory` for your reactive code.
The following example shows how to do so:
====
[source,java]
----
@Service
@ -69,13 +70,13 @@ public static class DemoControllerService { @@ -69,13 +70,13 @@ public static class DemoControllerService {
}
}
----
====
The `ReactiveCircuitBreakerFactory.create` API creates an instance of a class called `ReactiveCircuitBreaker`.
The `run` method takes a `Mono` or a `Flux` and wraps it in a circuit breaker.
You can optionally profile a fallback `Function`, which will be called if the circuit breaker is tripped and is passed the `Throwable`
that caused the failure.
[[configuration]]
== Configuration
You can configure your circuit breakers by creating beans of type `Customizer`.
@ -85,7 +86,7 @@ For detailed information on how to customize a given implementation see @@ -85,7 +86,7 @@ For detailed information on how to customize a given implementation see
the following documentation:
* link:../../../../spring-cloud-circuitbreaker/current/reference/html/spring-cloud-circuitbreaker.html#configuring-resilience4j-circuit-breakers[Resilience4J]
* link:https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-docs/src/main/asciidoc/circuitbreaker-sentinel.adoc#circuit-breaker-spring-cloud-circuit-breaker-with-sentinel--configuring-sentinel-circuit-breakers[Sentinal]
* link:https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-docs/src/main/asciidoc/circuitbreaker-sentinel.adoc#circuit-breaker-spring-cloud-circuit-breaker-with-sentinel--configuring-sentinel-circuit-breakers[Sentinel]
* link:../../../../../spring-cloud-circuitbreaker/docs/current/reference/html/spring-cloud-circuitbreaker.html#configuring-spring-retry-circuit-breakers[Spring Retry]
Some `CircuitBreaker` implementations such as `Resilience4JCircuitBreaker` call `customize` method every time `CircuitBreaker#run` is called.
@ -94,7 +95,6 @@ for example, in case of https://resilience4j.readme.io/docs/circuitbreaker#secti @@ -94,7 +95,6 @@ for example, in case of https://resilience4j.readme.io/docs/circuitbreaker#secti
The following example shows the way for each `io.github.resilience4j.circuitbreaker.CircuitBreaker` to consume events.
====
[source,java]
----
Customizer.once(circuitBreaker -> {
@ -102,4 +102,3 @@ Customizer.once(circuitBreaker -> { @@ -102,4 +102,3 @@ Customizer.once(circuitBreaker -> {
.onStateTransition(event -> log.info("{}: {}", event.getCircuitBreakerName(), event.getStateTransition()));
}, CircuitBreaker::getName)
----
====

261
docs/modules/ROOT/pages/spring-cloud-commons/application-context-services.adoc

@ -0,0 +1,261 @@ @@ -0,0 +1,261 @@
[[spring-cloud-context-application-context-services]]
= Spring Cloud Context: Application Context Services
Spring Boot has an opinionated view of how to build an application with Spring.
For instance, it has conventional locations for common configuration files and has endpoints for common management and monitoring tasks.
Spring Cloud builds on top of that and adds a few features that many components in a system would use or occasionally need.
[[the-bootstrap-application-context]]
== The Bootstrap Application Context
A Spring Cloud application operates by creating a "`bootstrap`" context, which is a parent context for the main application.
This context is responsible for loading configuration properties from the external sources and for decrypting properties in the local external configuration files.
The two contexts share an `Environment`, which is the source of external properties for any Spring application.
By default, bootstrap properties (not `bootstrap.properties` but properties that are loaded during the bootstrap phase) are added with high precedence, so they cannot be overridden by local configuration.
The bootstrap context uses a different convention for locating external configuration than the main application context.
Instead of `application.yml` (or `.properties`), you can use `bootstrap.yml`, keeping the external configuration for bootstrap and main context nicely separate.
The following listing shows an example:
.bootstrap.yml
----
spring:
application:
name: foo
cloud:
config:
uri: ${SPRING_CONFIG_URI:http://localhost:8888}
----
If your application needs any application-specific configuration from the server, it is a good idea to set the `spring.application.name` (in `bootstrap.yml` or `application.yml`).
For the property `spring.application.name` to be used as the application's context ID, you must set it in `bootstrap.[properties | yml]`.
If you want to retrieve specific profile configuration, you should also set `spring.profiles.active` in `bootstrap.[properties | yml]`.
You can disable the bootstrap process completely by setting `spring.cloud.bootstrap.enabled=false` (for example, in system properties).
[[application-context-hierarchies]]
== Application Context Hierarchies
If you build an application context from `SpringApplication` or `SpringApplicationBuilder`, the Bootstrap context is added as a parent to that context.
It is a feature of Spring that child contexts inherit property sources and profiles from their parent, so the "`main`" application context contains additional property sources, compared to building the same context without Spring Cloud Config.
The additional property sources are:
* "`bootstrap`": If any `PropertySourceLocators` are found in the bootstrap context and if they have non-empty properties, an optional `CompositePropertySource` appears with high priority.
An example would be properties from the Spring Cloud Config Server.
See "`xref:spring-cloud-commons/application-context-services.adoc#customizing-bootstrap-property-sources[Customizing the Bootstrap Property Sources]`" for how to customize the contents of this property source.
NOTE: Prior to Spring Cloud 2022.0.3 `PropertySourceLocators` (including the ones for Spring Cloud Config) were run during
the main application context and not in the Bootstrap context. You can force `PropertySourceLocators` to be run during the
Bootstrap context by setting `spring.cloud.config.initialize-on-context-refresh=true` in `bootstrap.[properties | yaml]`.
* "`applicationConfig: [classpath:bootstrap.yml]`" (and related files if Spring profiles are active): If you have a `bootstrap.yml` (or `.properties`), those properties are used to configure the bootstrap context.
Then they get added to the child context when its parent is set.
They have lower precedence than the `application.yml` (or `.properties`) and any other property sources that are added to the child as a normal part of the process of creating a Spring Boot application.
See "`xref:spring-cloud-commons/application-context-services.adoc#customizing-bootstrap-properties[Changing the Location of Bootstrap Properties]`" for how to customize the contents of these property sources.
Because of the ordering rules of property sources, the "`bootstrap`" entries take precedence.
However, note that these do not contain any data from `bootstrap.yml`, which has very low precedence but can be used to set defaults.
You can extend the context hierarchy by setting the parent context of any `ApplicationContext` you create -- for example, by using its own interface or with the `SpringApplicationBuilder` convenience methods (`parent()`, `child()` and `sibling()`).
The bootstrap context is the parent of the most senior ancestor that you create yourself.
Every context in the hierarchy has its own "`bootstrap`" (possibly empty) property source to avoid promoting values inadvertently from parents down to their descendants.
If there is a config server, every context in the hierarchy can also (in principle) have a different `spring.application.name` and, hence, a different remote property source.
Normal Spring application context behavior rules apply to property resolution: properties from a child context override those in
the parent, by name and also by property source name.
(If the child has a property source with the same name as the parent, the value from the parent is not included in the child).
Note that the `SpringApplicationBuilder` lets you share an `Environment` amongst the whole hierarchy, but that is not the default.
Thus, sibling contexts (in particular) do not need to have the same profiles or property sources, even though they may share common values with their parent.
[[customizing-bootstrap-properties]]
== Changing the Location of Bootstrap Properties
The `bootstrap.yml` (or `.properties`) location can be specified by setting `spring.cloud.bootstrap.name` (default: `bootstrap`), `spring.cloud.bootstrap.location` (default: empty) or `spring.cloud.bootstrap.additional-location` (default: empty) -- for example, in System properties.
Those properties behave like the `spring.config.*` variants with the same name.
With `spring.cloud.bootstrap.location` the default locations are replaced and only the specified ones are used.
To add locations to the list of default ones, `spring.cloud.bootstrap.additional-location` can be used.
In fact, they are used to set up the bootstrap `ApplicationContext` by setting those properties in its `Environment`.
If there is an active profile (from `spring.profiles.active` or through the `Environment` API in the context you are building), properties in that profile get loaded as well, the same as in a regular Spring Boot app -- for example, from `bootstrap-development.properties` for a `development` profile.
[[overriding-bootstrap-properties]]
== Overriding the Values of Remote Properties
The property sources that are added to your application by the bootstrap context are often "`remote`" (from example, from Spring Cloud Config Server).
By default, they cannot be overridden locally.
If you want to let your applications override the remote properties with their own system properties or config files, the remote property source has to grant it permission by setting `spring.cloud.config.allowOverride=true` (it does not work to set this locally).
Once that flag is set, two finer-grained settings control the location of the remote properties in relation to system properties and the application's local configuration:
* `spring.cloud.config.overrideNone=true`: Override from any local property source.
* `spring.cloud.config.overrideSystemProperties=false`: Only system properties, command line arguments, and environment variables (but not the local config files) should override the remote settings.
[[customizing-the-bootstrap-configuration]]
== Customizing the Bootstrap Configuration
The bootstrap context can be set to do anything you like by adding entries to `/META-INF/spring.factories` under a key named `org.springframework.cloud.bootstrap.BootstrapConfiguration`.
This holds a comma-separated list of Spring `@Configuration` classes that are used to create the context.
Any beans that you want to be available to the main application context for autowiring can be created here.
There is a special contract for `@Beans` of type `ApplicationContextInitializer`.
If you want to control the startup sequence, you can mark classes with the `@Order` annotation (the default order is `last`).
WARNING: When adding custom `BootstrapConfiguration`, be careful that the classes you add are not `@ComponentScanned` by mistake into your "`main`" application context, where they might not be needed.
Use a separate package name for boot configuration classes and make sure that name is not already covered by your `@ComponentScan` or `@SpringBootApplication` annotated configuration classes.
The bootstrap process ends by injecting initializers into the main `SpringApplication` instance (which is the normal Spring Boot startup sequence, whether it runs as a standalone application or is deployed in an application server).
First, a bootstrap context is created from the classes found in `spring.factories`.
Then, all `@Beans` of type `ApplicationContextInitializer` are added to the main `SpringApplication` before it is started.
[[customizing-bootstrap-property-sources]]
== Customizing the Bootstrap Property Sources
The default property source for external configuration added by the bootstrap process is the Spring Cloud Config Server, but you can add additional sources by adding beans of type `PropertySourceLocator` to the bootstrap context (through `spring.factories`).
For instance, you can insert additional properties from a different server or from a database.
As an example, consider the following custom locator:
[source,java]
----
@Configuration
public class CustomPropertySourceLocator implements PropertySourceLocator {
@Override
public PropertySource<?> locate(Environment environment) {
return new MapPropertySource("customProperty",
Collections.<String, Object>singletonMap("property.from.sample.custom.source", "worked as intended"));
}
}
----
The `Environment` that is passed in is the one for the `ApplicationContext` about to be created -- in other words, the one for which we supply additional property sources.
It already has its normal Spring Boot-provided property sources, so you can use those to locate a property source specific to this `Environment` (for example, by keying it on `spring.application.name`, as is done in the default Spring Cloud Config Server property source locator).
If you create a jar with this class in it and then add a `META-INF/spring.factories` containing the following setting, the `customProperty` `PropertySource` appears in any application that includes that jar on its classpath:
[source]
----
org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator
----
As of Spring Cloud 2022.0.3, Spring Cloud will now call `PropertySourceLocators` twice. The first fetch
will retrieve any property sources without any profiles. These property sources will have the opportunity to
activate profiles using `spring.profiles.active`. After the main application context starts `PropertySourceLocators`
will be called a second time, this time with any active profiles allowing `PropertySourceLocators` to locate
any additional `PropertySources` with profiles.
[[logging-configuration]]
== Logging Configuration
If you use Spring Boot to configure log settings, you should place this configuration in `bootstrap.[yml | properties]` if you would like it to apply to all events.
NOTE: For Spring Cloud to initialize logging configuration properly, you cannot use a custom prefix.
For example, using `custom.loggin.logpath` is not recognized by Spring Cloud when initializing the logging system.
[[environment-changes]]
== Environment Changes
The application listens for an `EnvironmentChangeEvent` and reacts to the change in a couple of standard ways (additional `ApplicationListeners` can be added as `@Beans` in the normal way).
When an `EnvironmentChangeEvent` is observed, it has a list of key values that have changed, and the application uses those to:
* Re-bind any `@ConfigurationProperties` beans in the context.
* Set the logger levels for any properties in `logging.level.*`.
Note that the Spring Cloud Config Client does not, by default, poll for changes in the `Environment`.
Generally, we would not recommend that approach for detecting changes (although you can set it up with a
`@Scheduled` annotation).
If you have a scaled-out client application, it is better to broadcast the `EnvironmentChangeEvent` to all the instances instead of having them polling for changes (for example, by using the https://github.com/spring-cloud/spring-cloud-bus[Spring Cloud Bus]).
The `EnvironmentChangeEvent` covers a large class of refresh use cases, as long as you can actually make a change to the `Environment` and publish the event.
Note that those APIs are public and part of core Spring).
You can verify that the changes are bound to `@ConfigurationProperties` beans by visiting the `/configprops` endpoint (a standard Spring Boot Actuator feature).
For instance, a `DataSource` can have its `maxPoolSize` changed at runtime (the default `DataSource` created by Spring Boot is a `@ConfigurationProperties` bean) and grow capacity dynamically.
Re-binding `@ConfigurationProperties` does not cover another large class of use cases, where you need more control over the refresh and where you need a change to be atomic over the whole `ApplicationContext`.
To address those concerns, we have `@RefreshScope`.
[[refresh-scope]]
== Refresh Scope
When there is a configuration change, a Spring `@Bean` that is marked as `@RefreshScope` gets special treatment.
This feature addresses the problem of stateful beans that get their configuration injected only when they are initialized.
For instance, if a `DataSource` has open connections when the database URL is changed through the `Environment`, you probably want the holders of those connections to be able to complete what they are doing.
Then, the next time something borrows a connection from the pool, it gets one with the new URL.
Sometimes, it might even be mandatory to apply the `@RefreshScope` annotation on some beans that can be only initialized once.
If a bean is "`immutable`", you have to either annotate the bean with `@RefreshScope` or specify the classname under the property key: `spring.cloud.refresh.extra-refreshable`.
WARNING: If you hava a `DataSource` bean that is a `HikariDataSource`, it can not be
refreshed. It is the default value for `spring.cloud.refresh.never-refreshable`. Choose a
different `DataSource` implementation if you need it to be refreshed.
Refresh scope beans are lazy proxies that initialize when they are used (that is, when a method is called), and the scope acts as a cache of initialized values.
To force a bean to re-initialize on the next method call, you must invalidate its cache entry.
The `RefreshScope` is a bean in the context and has a public `refreshAll()` method to refresh all beans in the scope by clearing the target cache.
The `/refresh` endpoint exposes this functionality (over HTTP or JMX).
To refresh an individual bean by name, there is also a `refresh(String)` method.
To expose the `/refresh` endpoint, you need to add following configuration to your application:
[source,yaml]
----
management:
endpoints:
web:
exposure:
include: refresh
----
NOTE: `@RefreshScope` works (technically) on a `@Configuration` class, but it might lead to surprising behavior.
For example, it does not mean that all the `@Beans` defined in that class are themselves in `@RefreshScope`.
Specifically, anything that depends on those beans cannot rely on them being updated when a refresh is initiated, unless it is itself in `@RefreshScope`.
In that case, it is rebuilt on a refresh and its dependencies are re-injected.
At that point, they are re-initialized from the refreshed `@Configuration`).
NOTE: Removing a configuration value and then performing a refresh will not update the presence of the configuration value.
The configuration property must be present in order to update the value after a refresh. If you are relying on the presence of
a value in your application you might want to switch your logic to rely on its absence instead. Another option would be to rely
on the value changing rather than not being present in the application's configuration.
WARNING: Context Refresh is not supported for Spring AOT transformations and native images. For AOT and native images, `spring.cloud.refresh.enabled` needs to be set to `false`.
[refresh-scope-on-restart]
=== Refresh Scope on Restart
Seamlessly refreshing beans on restart is especially useful for applications that run with JVM Checkpoint Restore (such as https://github.com/CRaC[Project CRaC]). To allow this ability, we now instantiate a `RefreshScopeLifecycle` bean that triggers Context Refresh on restart, resulting in rebinding configuration properties and refreshing any beans annotated with `@RefreshScope`. You can disable this behavior by setting `spring.cloud.refresh.on-restart.enabled` to `false`.
[[encryption-and-decryption]]
== Encryption and Decryption
Spring Cloud has an `Environment` pre-processor for decrypting property values locally.
It follows the same rules as the Spring Cloud Config Server and has the same external configuration through `encrypt.\*`.
Thus, you can use encrypted values in the form of `\{cipher}*`, and, as long as there is a valid key, they are decrypted before the main application context gets the `Environment` settings.
To use the encryption features in an application, you need to include Spring Security RSA in your classpath (Maven co-ordinates: `org.springframework.security:spring-security-rsa`), and you also need the full strength JCE extensions in your JVM.
If you get an exception due to "Illegal key size" and you use Sun's JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files.
See the following links for more information:
* https://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html[Java 6 JCE]
* https://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html[Java 7 JCE]
* https://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html[Java 8 JCE]
Extract the files into the JDK/jre/lib/security folder for whichever version of JRE/JDK x64/x86 you use.
[[endpoints]]
== Endpoints
For a Spring Boot Actuator application, some additional management endpoints are available. You can use:
* `POST` to `/actuator/env` to update the `Environment` and rebind `@ConfigurationProperties` and log levels.
To enabled this endpoint you must set `management.endpoint.env.post.enabled=true`.
* `/actuator/refresh` to re-load the boot strap context and refresh the `@RefreshScope` beans.
* `/actuator/restart` to close the `ApplicationContext` and restart it (disabled by default).
* `/actuator/pause` and `/actuator/resume` for calling the `Lifecycle` methods (`stop()` and `start()` on the `ApplicationContext`).
NOTE: While enabling the `POST` method for `/actuator/env` endpoint can provide flexibility and convenience in managing your application environment variables,
it's critical to ensure that the endpoint is secured and monitored to prevent potential security risks.
Add a `spring-boot-starter-security` dependency to configure access control for the actuator’s endpoint.
NOTE: If you disable the `/actuator/restart` endpoint then the `/actuator/pause` and `/actuator/resume` endpoints
will also be disabled since they are just a special case of `/actuator/restart`.

15
docs/modules/ROOT/pages/spring-cloud-commons/cachedrandompropertysource.adoc

@ -0,0 +1,15 @@ @@ -0,0 +1,15 @@
[[cachedrandompropertysource]]
= CachedRandomPropertySource
:page-section-summary-toc: 1
Spring Cloud Context provides a `PropertySource` that caches random values based on a key. Outside of the caching
functionality it works the same as Spring Boot's https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/RandomValuePropertySource.java[`RandomValuePropertySource`].
This random value might be useful in the case where you want a random value that is consistent even after the Spring Application
context restarts. The property value takes the form of `cachedrandom.[yourkey].[type]` where `yourkey` is the key in the cache. The `type` value can
be any type supported by Spring Boot's `RandomValuePropertySource`.
[source,properties,indent=0]
----
myrandom=${cachedrandom.appname.value}
----

595
docs/modules/ROOT/pages/spring-cloud-commons/common-abstractions.adoc

@ -0,0 +1,595 @@ @@ -0,0 +1,595 @@
[[spring-cloud-common-abstractions]]
= Spring Cloud Commons: Common Abstractions
Patterns such as service discovery, load balancing, and circuit breakers lend themselves to a common abstraction layer that can be consumed by all Spring Cloud clients, independent of the implementation (for example, discovery with Eureka or Consul).
[[discovery-client]]
== The `@EnableDiscoveryClient` Annotation
Spring Cloud Commons provides the `@EnableDiscoveryClient` annotation.
This looks for implementations of the `DiscoveryClient` and `ReactiveDiscoveryClient` interfaces with `META-INF/spring.factories`.
Implementations of the discovery client add a configuration class to `spring.factories` under the `org.springframework.cloud.client.discovery.EnableDiscoveryClient` key.
Examples of `DiscoveryClient` implementations include https://cloud.spring.io/spring-cloud-netflix/[Spring Cloud Netflix Eureka], https://cloud.spring.io/spring-cloud-consul/[Spring Cloud Consul Discovery], and https://cloud.spring.io/spring-cloud-zookeeper/[Spring Cloud Zookeeper Discovery].
Spring Cloud will provide both the blocking and reactive service discovery clients by default.
You can disable the blocking and/or reactive clients easily by setting `spring.cloud.discovery.blocking.enabled=false` or `spring.cloud.discovery.reactive.enabled=false`.
To completely disable service discovery you just need to set `spring.cloud.discovery.enabled=false`.
By default, implementations of `DiscoveryClient` auto-register the local Spring Boot server with the remote discovery server.
This behavior can be disabled by setting `autoRegister=false` in `@EnableDiscoveryClient`.
NOTE: `@EnableDiscoveryClient` is no longer required.
You can put a `DiscoveryClient` implementation on the classpath to cause the Spring Boot application to register with the service discovery server.
[[health-indicators]]
=== Health Indicators
Commons auto-configures the following Spring Boot health indicators.
[[discoveryclienthealthindicator]]
==== DiscoveryClientHealthIndicator
This health indicator is based on the currently registered `DiscoveryClient` implementation.
* To disable entirely, set `spring.cloud.discovery.client.health-indicator.enabled=false`.
* To disable the description field, set `spring.cloud.discovery.client.health-indicator.include-description=false`.
Otherwise, it can bubble up as the `description` of the rolled up `HealthIndicator`.
* To disable service retrieval, set `spring.cloud.discovery.client.health-indicator.use-services-query=false`.
By default, the indicator invokes the client's `getServices` method. In deployments with many registered services it may too
costly to retrieve all services during every check. This will skip the service retrieval and instead use the client's `probe` method.
[[discoverycompositehealthcontributor]]
==== DiscoveryCompositeHealthContributor
This composite health indicator is based on all registered `DiscoveryHealthIndicator` beans. To disable,
set `spring.cloud.discovery.client.composite-indicator.enabled=false`.
[[ordering-discoveryclient-instances]]
=== Ordering `DiscoveryClient` instances
`DiscoveryClient` interface extends `Ordered`. This is useful when using multiple discovery
clients, as it allows you to define the order of the returned discovery clients, similar to
how you can order the beans loaded by a Spring application. By default, the order of any `DiscoveryClient` is set to
`0`. If you want to set a different order for your custom `DiscoveryClient` implementations, you just need to override
the `getOrder()` method so that it returns the value that is suitable for your setup. Apart from this, you can use
properties to set the order of the `DiscoveryClient`
implementations provided by Spring Cloud, among others `ConsulDiscoveryClient`, `EurekaDiscoveryClient` and
`ZookeeperDiscoveryClient`. In order to do it, you just need to set the
`spring.cloud.\{clientIdentifier}.discovery.order` (or `eureka.client.order` for Eureka) property to the desired value.
[[simplediscoveryclient]]
=== SimpleDiscoveryClient
If there is no Service-Registry-backed `DiscoveryClient` in the classpath, `SimpleDiscoveryClient`
instance, that uses properties to get information on service and instances, will be used.
The information about the available instances should be passed to via properties in the following format:
`spring.cloud.discovery.client.simple.instances.service1[0].uri=http://s11:8080`, where
`spring.cloud.discovery.client.simple.instances` is the common prefix, then `service1` stands
for the ID of the service in question, while `[0]` indicates the index number of the instance
(as visible in the example, indexes start with `0`), and then the value of `uri` is
the actual URI under which the instance is available.
[[serviceregistry]]
== ServiceRegistry
Commons now provides a `ServiceRegistry` interface that provides methods such as `register(Registration)` and `deregister(Registration)`, which let you provide custom registered services.
`Registration` is a marker interface.
The following example shows the `ServiceRegistry` in use:
[source,java,indent=0]
----
@Configuration
@EnableDiscoveryClient(autoRegister=false)
public class MyConfiguration {
private ServiceRegistry registry;
public MyConfiguration(ServiceRegistry registry) {
this.registry = registry;
}
// called through some external process, such as an event or a custom actuator endpoint
public void register() {
Registration registration = constructRegistration();
this.registry.register(registration);
}
}
----
Each `ServiceRegistry` implementation has its own `Registry` implementation.
* `ZookeeperRegistration` used with `ZookeeperServiceRegistry`
* `EurekaRegistration` used with `EurekaServiceRegistry`
* `ConsulRegistration` used with `ConsulServiceRegistry`
If you are using the `ServiceRegistry` interface, you are going to need to pass the
correct `Registry` implementation for the `ServiceRegistry` implementation you
are using.
[[serviceregistry-auto-registration]]
=== ServiceRegistry Auto-Registration
By default, the `ServiceRegistry` implementation auto-registers the running service.
To disable that behavior, you can set:
* `@EnableDiscoveryClient(autoRegister=false)` to permanently disable auto-registration.
* `spring.cloud.service-registry.auto-registration.enabled=false` to disable the behavior through configuration.
[[serviceregistry-auto-registration-events]]
==== ServiceRegistry Auto-Registration Events
There are two events that will be fired when a service auto-registers. The first event, called
`InstancePreRegisteredEvent`, is fired before the service is registered. The second
event, called `InstanceRegisteredEvent`, is fired after the service is registered. You can register an
`ApplicationListener`(s) to listen to and react to these events.
NOTE: These events will not be fired if the `spring.cloud.service-registry.auto-registration.enabled` property is set to `false`.
[[service-registry-actuator-endpoint]]
=== Service Registry Actuator Endpoint
Spring Cloud Commons provides a `/serviceregistry` actuator endpoint.
This endpoint relies on a `Registration` bean in the Spring Application Context.
Calling `/serviceregistry` with GET returns the status of the `Registration`.
Using POST to the same endpoint with a JSON body changes the status of the current `Registration` to the new value.
The JSON body has to include the `status` field with the preferred value.
Please see the documentation of the `ServiceRegistry` implementation you use for the allowed values when updating the status and the values returned for the status.
For instance, Eureka's supported statuses are `UP`, `DOWN`, `OUT_OF_SERVICE`, and `UNKNOWN`.
[[rest-template-loadbalancer-client]]
== Spring RestTemplate as a Load Balancer Client
You can configure a `RestTemplate` to use a Load-balancer client.
To create a load-balanced `RestTemplate`, create a `RestTemplate` `@Bean` and use the `@LoadBalanced` qualifier, as the following example shows:
[source,java,indent=0]
----
@Configuration
public class MyConfiguration {
@LoadBalanced
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
}
public class MyClass {
@Autowired
private RestTemplate restTemplate;
public String doOtherStuff() {
String results = restTemplate.getForObject("http://stores/stores", String.class);
return results;
}
}
----
CAUTION: A `RestTemplate` bean is no longer created through auto-configuration.
Individual applications must create it.
The URI needs to use a virtual host name (that is, a service name, not a host name).
The BlockingLoadBalancerClient is used to create a full physical address.
IMPORTANT: To use a load-balanced `RestTemplate`, you need to have a load-balancer implementation in your classpath.
Add xref:spring-cloud-commons/loadbalancer.adoc#spring-cloud-loadbalancer-starter[Spring Cloud LoadBalancer starter] to your project in order to use it.
[[webclinet-loadbalancer-client]]
== Spring WebClient as a Load Balancer Client
You can configure `WebClient` to automatically use a load-balancer client.
To create a load-balanced `WebClient`, create a `WebClient.Builder` `@Bean` and use the `@LoadBalanced` qualifier, as follows:
[source,java,indent=0]
----
@Configuration
public class MyConfiguration {
@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {
return WebClient.builder();
}
}
public class MyClass {
@Autowired
private WebClient.Builder webClientBuilder;
public Mono<String> doOtherStuff() {
return webClientBuilder.build().get().uri("http://stores/stores")
.retrieve().bodyToMono(String.class);
}
}
----
The URI needs to use a virtual host name (that is, a service name, not a host name).
The Spring Cloud LoadBalancer is used to create a full physical address.
IMPORTANT: If you want to use a `@LoadBalanced WebClient.Builder`, you need to have a load balancer
implementation in the classpath. We recommend that you add the
xref:spring-cloud-commons/loadbalancer.adoc#spring-cloud-loadbalancer-starter[Spring Cloud LoadBalancer starter] to your project.
Then, `ReactiveLoadBalancer` is used underneath.
[[retrying-failed-requests]]
=== Retrying Failed Requests
A load-balanced `RestTemplate` can be configured to retry failed requests.
By default, this logic is disabled.
For the non-reactive version (with `RestTemplate`), you can enable it by adding link:https://github.com/spring-projects/spring-retry[Spring Retry] to your application's classpath. For the reactive version (with `WebTestClient`), you need to set `spring.cloud.loadbalancer.retry.enabled=true`.
If you would like to disable the retry logic with Spring Retry or Reactive Retry on the classpath, you can set `spring.cloud.loadbalancer.retry.enabled=false`.
For the non-reactive implementation, if you would like to implement a `BackOffPolicy` in your retries, you need to create a bean of type `LoadBalancedRetryFactory` and override the `createBackOffPolicy()` method.
For the reactive implementation, you just need to enable it by setting `spring.cloud.loadbalancer.retry.backoff.enabled` to `false`.
You can set:
- `spring.cloud.loadbalancer.retry.maxRetriesOnSameServiceInstance` - indicates how many times a request should be retried on the same `ServiceInstance` (counted separately for every selected instance)
- `spring.cloud.loadbalancer.retry.maxRetriesOnNextServiceInstance` - indicates how many times a request should be retried a newly selected `ServiceInstance`
- `spring.cloud.loadbalancer.retry.retryableStatusCodes` - the status codes on which to always retry a failed request.
For the reactive implementation, you can additionally set:
- `spring.cloud.loadbalancer.retry.backoff.minBackoff` - Sets the minimum backoff duration (by default, 5 milliseconds)
- `spring.cloud.loadbalancer.retry.backoff.maxBackoff` - Sets the maximum backoff duration (by default, max long value of milliseconds)
- `spring.cloud.loadbalancer.retry.backoff.jitter` - Sets the jitter used for calculating the actual backoff duration for each call (by default, 0.5).
For the reactive implementation, you can also implement your own `LoadBalancerRetryPolicy` to have more detailed control over the load-balanced call retries.
For both implementations, you can also set the exceptions that trigger the replies by adding a list of values under the `spring.cloud.loadbalancer.[serviceId].retry.retryable-exceptions` property. If you do, we make sure to add `RetryableStatusCodeExceptions` to the list of exceptions provided by you, so that we also retry on retryable status codes. If you do not specify any exceptions via properties, the exceptions we use by default are `IOException`, `TimeoutException` and `RetryableStatusCodeException`. You can also enable retrying on all exceptions by setting `spring.cloud.loadbalancer.[serviceId].retry.retry-on-all-exceptions` to `true`.
WARNING: If you use the blocking implementation with Spring Retries, if you want to keep the behaviour from previous releases, set `spring.cloud.loadbalancer.[serviceId].retry.retry-on-all-exceptions` to `true` as that used to be the default mode for the blocking implementation.
NOTE: Individual Loadbalancer clients may be configured individually with the same properties as above except the prefix is `spring.cloud.loadbalancer.clients.<clientId>.*` where `clientId` is the name of the loadbalancer.
NOTE: For load-balanced retries, by default, we wrap the `ServiceInstanceListSupplier` bean with `RetryAwareServiceInstanceListSupplier` to select a different instance from the one previously chosen, if available. You can disable this behavior by setting the value of `spring.cloud.loadbalancer.retry.avoidPreviousInstance` to `false`.
[source,java,indent=0]
----
@Configuration
public class MyConfiguration {
@Bean
LoadBalancedRetryFactory retryFactory() {
return new LoadBalancedRetryFactory() {
@Override
public BackOffPolicy createBackOffPolicy(String service) {
return new ExponentialBackOffPolicy();
}
};
}
}
----
If you want to add one or more `RetryListener` implementations to your retry functionality, you need to
create a bean of type `LoadBalancedRetryListenerFactory` and return the `RetryListener` array
you would like to use for a given service, as the following example shows:
[source,java,indent=0]
----
@Configuration
public class MyConfiguration {
@Bean
LoadBalancedRetryListenerFactory retryListenerFactory() {
return new LoadBalancedRetryListenerFactory() {
@Override
public RetryListener[] createRetryListeners(String service) {
return new RetryListener[]{new RetryListener() {
@Override
public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
//TODO Do you business...
return true;
}
@Override
public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
//TODO Do you business...
}
@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
//TODO Do you business...
}
}};
}
};
}
}
----
[[multiple-resttemplate-objects]]
== Multiple `RestTemplate` Objects
If you want a `RestTemplate` that is not load-balanced, create a `RestTemplate` bean and inject it.
To access the load-balanced `RestTemplate`, use the `@LoadBalanced` qualifier when you create your `@Bean`, as the following example shows:
[source,java,indent=0]
----
@Configuration
public class MyConfiguration {
@LoadBalanced
@Bean
RestTemplate loadBalanced() {
return new RestTemplate();
}
@Primary
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
}
public class MyClass {
@Autowired
private RestTemplate restTemplate;
@Autowired
@LoadBalanced
private RestTemplate loadBalanced;
public String doOtherStuff() {
return loadBalanced.getForObject("http://stores/stores", String.class);
}
public String doStuff() {
return restTemplate.getForObject("http://example.com", String.class);
}
}
----
IMPORTANT: Notice the use of the `@Primary` annotation on the plain `RestTemplate` declaration in the preceding example to disambiguate the unqualified `@Autowired` injection.
TIP: If you see errors such as `java.lang.IllegalArgumentException: Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89`, try injecting `RestOperations` or setting `spring.aop.proxyTargetClass=true`.
[[multiple-webclient-objects]]
== Multiple WebClient Objects
If you want a `WebClient` that is not load-balanced, create a `WebClient` bean and inject it.
To access the load-balanced `WebClient`, use the `@LoadBalanced` qualifier when you create your `@Bean`, as the following example shows:
[source,java,indent=0]
----
@Configuration
public class MyConfiguration {
@LoadBalanced
@Bean
WebClient.Builder loadBalanced() {
return WebClient.builder();
}
@Primary
@Bean
WebClient.Builder webClient() {
return WebClient.builder();
}
}
public class MyClass {
@Autowired
private WebClient.Builder webClientBuilder;
@Autowired
@LoadBalanced
private WebClient.Builder loadBalanced;
public Mono<String> doOtherStuff() {
return loadBalanced.build().get().uri("http://stores/stores")
.retrieve().bodyToMono(String.class);
}
public Mono<String> doStuff() {
return webClientBuilder.build().get().uri("http://example.com")
.retrieve().bodyToMono(String.class);
}
}
----
[[loadbalanced-webclient]]
== Spring WebFlux `WebClient` as a Load Balancer Client
The Spring WebFlux can work with both reactive and non-reactive `WebClient` configurations, as the topics describe:
* xref:spring-cloud-commons/common-abstractions.adoc#webflux-with-reactive-loadbalancer[Spring WebFlux `WebClient` with `ReactorLoadBalancerExchangeFilterFunction`]
* xref:spring-cloud-commons/common-abstractions.adoc#load-balancer-exchange-filter-function[Spring WebFlux `WebClient` with a Non-reactive Load Balancer Client]
[[webflux-with-reactive-loadbalancer]]
=== Spring WebFlux `WebClient` with `ReactorLoadBalancerExchangeFilterFunction`
You can configure `WebClient` to use the `ReactiveLoadBalancer`.
If you add xref:spring-cloud-commons/loadbalancer.adoc#spring-cloud-loadbalancer-starter[Spring Cloud LoadBalancer starter] to your project
and if `spring-webflux` is on the classpath, `ReactorLoadBalancerExchangeFilterFunction` is auto-configured.
The following example shows how to configure a `WebClient` to use reactive load-balancer:
[source,java,indent=0]
----
public class MyClass {
@Autowired
private ReactorLoadBalancerExchangeFilterFunction lbFunction;
public Mono<String> doOtherStuff() {
return WebClient.builder().baseUrl("http://stores")
.filter(lbFunction)
.build()
.get()
.uri("/stores")
.retrieve()
.bodyToMono(String.class);
}
}
----
The URI needs to use a virtual host name (that is, a service name, not a host name).
The `ReactorLoadBalancer` is used to create a full physical address.
[[load-balancer-exchange-filter-function]]
=== Spring WebFlux `WebClient` with a Non-reactive Load Balancer Client
If `spring-webflux` is on the classpath, `LoadBalancerExchangeFilterFunction`
is auto-configured. Note, however, that this
uses a non-reactive client under the hood.
The following example shows how to configure a `WebClient` to use load-balancer:
[source,java,indent=0]
----
public class MyClass {
@Autowired
private LoadBalancerExchangeFilterFunction lbFunction;
public Mono<String> doOtherStuff() {
return WebClient.builder().baseUrl("http://stores")
.filter(lbFunction)
.build()
.get()
.uri("/stores")
.retrieve()
.bodyToMono(String.class);
}
}
----
The URI needs to use a virtual host name (that is, a service name, not a host name).
The `LoadBalancerClient` is used to create a full physical address.
WARN: This approach is now deprecated.
We suggest that you use xref:spring-cloud-commons/common-abstractions.adoc#webflux-with-reactive-loadbalancer[WebFlux with reactive Load-Balancer]
instead.
[[ignore-network-interfaces]]
== Ignore Network Interfaces
Sometimes, it is useful to ignore certain named network interfaces so that they can be excluded from Service Discovery registration (for example, when running in a Docker container).
A list of regular expressions can be set to cause the desired network interfaces to be ignored.
The following configuration ignores the `docker0` interface and all interfaces that start with `veth`:
.application.yml
----
spring:
cloud:
inetutils:
ignoredInterfaces:
- docker0
- veth.*
----
You can also force the use of only specified network addresses by using a list of regular expressions, as the following example shows:
.bootstrap.yml
----
spring:
cloud:
inetutils:
preferredNetworks:
- 192.168
- 10.0
----
You can also force the use of only site-local addresses, as the following example shows:
.application.yml
----
spring:
cloud:
inetutils:
useOnlySiteLocalInterfaces: true
----
See https://docs.oracle.com/javase/8/docs/api/java/net/Inet4Address.html#isSiteLocalAddress--[Inet4Address.html.isSiteLocalAddress()] for more details about what constitutes a site-local address.
[[http-clients]]
== HTTP Client Factories
Spring Cloud Commons provides beans for creating both Apache HTTP clients (`ApacheHttpClientFactory`) and OK HTTP clients (`OkHttpClientFactory`).
The `OkHttpClientFactory` bean is created only if the OK HTTP jar is on the classpath.
In addition, Spring Cloud Commons provides beans for creating the connection managers used by both clients: `ApacheHttpClientConnectionManagerFactory` for the Apache HTTP client and `OkHttpClientConnectionPoolFactory` for the OK HTTP client.
If you would like to customize how the HTTP clients are created in downstream projects, you can provide your own implementation of these beans.
In addition, if you provide a bean of type `HttpClientBuilder` or `OkHttpClient.Builder`, the default factories use these builders as the basis for the builders returned to downstream projects.
You can also disable the creation of these beans by setting `spring.cloud.httpclientfactories.apache.enabled` or `spring.cloud.httpclientfactories.ok.enabled` to `false`.
[[enabled-features]]
== Enabled Features
Spring Cloud Commons provides a `/features` actuator endpoint.
This endpoint returns features available on the classpath and whether they are enabled.
The information returned includes the feature type, name, version, and vendor.
[[feature-types]]
=== Feature types
There are two types of 'features': abstract and named.
Abstract features are features where an interface or abstract class is defined and that an implementation the creates, such as `DiscoveryClient`, `LoadBalancerClient`, or `LockService`.
The abstract class or interface is used to find a bean of that type in the context.
The version displayed is `bean.getClass().getPackage().getImplementationVersion()`.
Named features are features that do not have a particular class they implement. These features include "`Circuit Breaker`", "`API Gateway`", "`Spring Cloud Bus`", and others. These features require a name and a bean type.
[[declaring-features]]
=== Declaring features
Any module can declare any number of `HasFeature` beans, as the following examples show:
[source,java,indent=0]
----
@Bean
public HasFeatures commonsFeatures() {
return HasFeatures.abstractFeatures(DiscoveryClient.class, LoadBalancerClient.class);
}
@Bean
public HasFeatures consulFeatures() {
return HasFeatures.namedFeatures(
new NamedFeature("Spring Cloud Bus", ConsulBusAutoConfiguration.class),
new NamedFeature("Circuit Breaker", HystrixCommandAspect.class));
}
@Bean
HasFeatures localFeatures() {
return HasFeatures.builder()
.abstractFeature(Something.class)
.namedFeature(new NamedFeature("Some Other Feature", Someother.class))
.abstractFeature(Somethingelse.class)
.build();
}
----
Each of these beans should go in an appropriately guarded `@Configuration`.
[[spring-cloud-compatibility-verification]]
== Spring Cloud Compatibility Verification
Due to the fact that some users have problem with setting up Spring Cloud application, we've decided
to add a compatibility verification mechanism. It will break if your current setup is not compatible
with Spring Cloud requirements, together with a report, showing what exactly went wrong.
At the moment we verify which version of Spring Boot is added to your classpath.
Example of a report
----
***************************
APPLICATION FAILED TO START
***************************
Description:
Your project setup is incompatible with our requirements due to following reasons:
- Spring Boot [2.1.0.RELEASE] is not compatible with this Spring Cloud release train
Action:
Consider applying the following actions:
- Change Spring Boot version to one of the following versions [1.2.x, 1.3.x] .
You can find the latest Spring Boot versions here [https://spring.io/projects/spring-boot#learn].
If you want to learn more about the Spring Cloud Release train compatibility, you can visit this page [https://spring.io/projects/spring-cloud#overview] and check the [Release Trains] section.
----
In order to disable this feature, set `spring.cloud.compatibility-verifier.enabled` to `false`.
If you want to override the compatible Spring Boot versions, just set the
`spring.cloud.compatibility-verifier.compatible-boot-versions` property with a comma separated list
of compatible Spring Boot versions.

515
docs/modules/ROOT/pages/spring-cloud-commons/loadbalancer.adoc

@ -0,0 +1,515 @@ @@ -0,0 +1,515 @@
[[spring-cloud-loadbalancer]]
= Spring Cloud LoadBalancer
Spring Cloud provides its own client-side load-balancer abstraction and implementation. For the load-balancing
mechanism, `ReactiveLoadBalancer` interface has been added and a *Round-Robin-based* and *Random* implementations
have been provided for it. In order to get instances to select from reactive `ServiceInstanceListSupplier`
is used. Currently we support a service-discovery-based implementation of `ServiceInstanceListSupplier`
that retrieves available instances from Service Discovery using a xref:spring-cloud-commons/common-abstractions.adoc#discovery-client[Discovery Client] available in the classpath.
TIP: It is possible to disable Spring Cloud LoadBalancer by setting the value of `spring.cloud.loadbalancer.enabled` to `false`.
[[eager-loading-of-loadbalancer-contexts]]
== Eager loading of LoadBalancer contexts
Spring Cloud LoadBalancer creates a separate Spring child context for each service id. By default, these contexts are initialised lazily, whenever the first request for a service id is being load-balanced.
You can choose to load those contexts eagerly. In order to do that, specify the service ids for which you want to do eager load using the `spring.cloud-loadbalancer.eager-load.clients` property.
[[switching-between-the-load-balancing-algorithms]]
== Switching between the load-balancing algorithms
The `ReactiveLoadBalancer` implementation that is used by default is `RoundRobinLoadBalancer`. To switch to a different implementation, either for selected services or all of them, you can use the xref:spring-cloud-commons/loadbalancer.adoc#custom-loadbalancer-configuration[custom LoadBalancer configurations mechanism].
For example, the following configuration can be passed via `@LoadBalancerClient` annotation to switch to using the `RandomLoadBalancer`:
[[random-loadbalancer-configuration]]
[source,java,indent=0]
----
public class CustomLoadBalancerConfiguration {
@Bean
ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new RandomLoadBalancer(loadBalancerClientFactory
.getLazyProvider(name, ServiceInstanceListSupplier.class),
name);
}
}
----
NOTE: The classes you pass as `@LoadBalancerClient` or `@LoadBalancerClients` configuration arguments should either not be annotated with `@Configuration` or be outside component scan scope.
[[spring-cloud-loadbalancer-integrations]]
== Spring Cloud LoadBalancer integrations
In order to make it easy to use Spring Cloud LoadBalancer, we provide `ReactorLoadBalancerExchangeFilterFunction` that can be used with `WebClient` and `BlockingLoadBalancerClient` that works with `RestTemplate`.
You can see more information and examples of usage in the following sections:
* xref:spring-cloud-commons/common-abstractions.adoc#rest-template-loadbalancer-client[Spring RestTemplate as a Load Balancer Client]
* xref:spring-cloud-commons/common-abstractions.adoc#webclinet-loadbalancer-client[Spring WebClient as a Load Balancer Client]
* xref:spring-cloud-commons/common-abstractions.adoc#webflux-with-reactive-loadbalancer[Spring WebFlux WebClient with `ReactorLoadBalancerExchangeFilterFunction`]
[[loadbalancer-caching]]
== Spring Cloud LoadBalancer Caching
Apart from the basic `ServiceInstanceListSupplier` implementation that retrieves instances via `DiscoveryClient` each time it has to choose an instance, we provide two caching implementations.
[[https://github-com/ben-manes/caffeine[caffeine]-backed-loadbalancer-cache-implementation]]
=== https://github.com/ben-manes/caffeine[Caffeine]-backed LoadBalancer Cache Implementation
If you have `com.github.ben-manes.caffeine:caffeine` in the classpath, Caffeine-based implementation will be used.
See the xref:spring-cloud-commons/loadbalancer.adoc#loadbalancer-cache-configuration[LoadBalancerCacheConfiguration] section for information on how to configure it.
If you are using Caffeine, you can also override the default Caffeine Cache setup for the LoadBalancer by passing your own https://static.javadoc.io/com.github.ben-manes.caffeine/caffeine/2.2.2/com/github/benmanes/caffeine/cache/CaffeineSpec.html[Caffeine Specification]
in the `spring.cloud.loadbalancer.cache.caffeine.spec` property.
WARN: Passing your own Caffeine specification will override any other LoadBalancerCache settings, including xref:spring-cloud-commons/loadbalancer.adoc#loadbalancer-cache-configuration[General LoadBalancer Cache Configuration] fields, such as `ttl` and `capacity`.
[[default-loadbalancer-cache-implementation]]
=== Default LoadBalancer Cache Implementation
If you do not have Caffeine in the classpath, the `DefaultLoadBalancerCache`, which comes automatically with `spring-cloud-starter-loadbalancer`, will be used.
See the xref:spring-cloud-commons/loadbalancer.adoc#loadbalancer-cache-configuration[LoadBalancerCacheConfiguration] section for information on how to configure it.
TIP: To use Caffeine instead of the default cache, add the `com.github.ben-manes.caffeine:caffeine` dependency to classpath.
[[loadbalancer-cache-configuration]]
=== LoadBalancer Cache Configuration
You can set your own `ttl` value (the time after write after which entries should be expired), expressed as `Duration`, by passing a `String` compliant with the https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-conversion-duration[Spring Boot `String` to `Duration` converter syntax].
as the value of the `spring.cloud.loadbalancer.cache.ttl` property.
You can also set your own LoadBalancer cache initial capacity by setting the value of the `spring.cloud.loadbalancer.cache.capacity` property.
The default setup includes `ttl` set to 35 seconds and the default `initialCapacity` is `256`.
You can also altogether disable loadBalancer caching by setting the value of `spring.cloud.loadbalancer.cache.enabled`
to `false`.
WARNING: Although the basic, non-cached, implementation is useful for prototyping and testing, it's much less efficient than the cached versions, so we recommend always using the cached version in production. If the caching is already done by the `DiscoveryClient` implementation, for example `EurekaDiscoveryClient`, the load-balancer caching should be disabled to prevent double caching.
NOTE: When you create your own configuration, if you use `CachingServiceInstanceListSupplier` make sure to place it in the hierarchy directly after the supplier that retrieves the instances over the network, for example, `DiscoveryClientServiceInstanceListSupplier`, before any other filtering suppliers.
[[weighted-load-balancing]]
== Weighted Load-Balancing
To enable weighted load-balancing, we provide the `WeightedServiceInstanceListSupplier`. We use `WeightFunction` to calculate the weight of each instance.
By default, we try to read and parse the weight from the metadata map (the key is `weight`).
If the weight is not specified in the metadata map, we default the weight of this instance to be 1.
You can configure it either by setting the value of `spring.cloud.loadbalancer.configurations` to `weighted` or by providing your own `ServiceInstanceListSupplier` bean, for example:
[[weighted-custom-loadbalancer-configuration]]
[source,java,indent=0]
----
public class CustomLoadBalancerConfiguration {
@Bean
public ServiceInstanceListSupplier discoveryClientServiceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder()
.withDiscoveryClient()
.withWeighted()
.withCaching()
.build(context);
}
}
----
NOTE: You can also customize the weight calculation logic by providing `WeightFunction`.
You can use this sample configuration to make all instances have a random weight:
[[random-weight-weighted-custom-loadbalancer-configuration]]
[source,java,indent=0]
----
public class CustomLoadBalancerConfiguration {
@Bean
public ServiceInstanceListSupplier discoveryClientServiceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder()
.withDiscoveryClient()
.withWeighted(instance -> ThreadLocalRandom.current().nextInt(1, 101))
.withCaching()
.build(context);
}
}
----
[[zone-based-load-balancing]]
== Zone-Based Load-Balancing
To enable zone-based load-balancing, we provide the `ZonePreferenceServiceInstanceListSupplier`.
We use `DiscoveryClient`-specific `zone` configuration (for example, `eureka.instance.metadata-map.zone`) to pick the zone that the client tries to filter available service instances for.
NOTE: You can also override `DiscoveryClient`-specific zone setup by setting the value of `spring.cloud.loadbalancer.zone` property.
WARNING: For the time being, only Eureka Discovery Client is instrumented to set the LoadBalancer zone. For other discovery client, set the `spring.cloud.loadbalancer.zone` property. More instrumentations coming shortly.
NOTE: To determine the zone of a retrieved `ServiceInstance`, we check the value under the `"zone"` key in its metadata map.
The `ZonePreferenceServiceInstanceListSupplier` filters retrieved instances and only returns the ones within the same zone.
If the zone is `null` or there are no instances within the same zone, it returns all the retrieved instances.
In order to use the zone-based load-balancing approach, you will have to instantiate a `ZonePreferenceServiceInstanceListSupplier` bean in a xref:spring-cloud-commons/loadbalancer.adoc#custom-loadbalancer-configuration[custom configuration].
We use delegates to work with `ServiceInstanceListSupplier` beans.
We suggest using a `DiscoveryClientServiceInstanceListSupplier` delegate, wrapping it with a `CachingServiceInstanceListSupplier` to leverage xref:spring-cloud-commons/loadbalancer.adoc#loadbalancer-caching[LoadBalancer caching mechanism], and then passing the resulting bean in the constructor of `ZonePreferenceServiceInstanceListSupplier`.
You can use this sample configuration to set it up:
[[zoned-based-custom-loadbalancer-configuration]]
[source,java,indent=0]
----
public class CustomLoadBalancerConfiguration {
@Bean
public ServiceInstanceListSupplier discoveryClientServiceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder()
.withDiscoveryClient()
.withCaching()
.withZonePreference()
.build(context);
}
}
----
[[instance-health-check-for-loadbalancer]]
== Instance Health-Check for LoadBalancer
It is possible to enable a scheduled HealthCheck for the LoadBalancer. The `HealthCheckServiceInstanceListSupplier`
is provided for that. It regularly verifies if the instances provided by a delegate
`ServiceInstanceListSupplier` are still alive and only returns the healthy instances,
unless there are none - then it returns all the retrieved instances.
TIP: This mechanism is particularly helpful while using the `SimpleDiscoveryClient`. For the
clients backed by an actual Service Registry, it's not necessary to use, as we already get
healthy instances after querying the external ServiceDiscovery.
TIP: This supplier is also recommended for setups with a small number of instances per service
in order to avoid retrying calls on a failing instance.
WARNING: If using any of the Service Discovery-backed suppliers, adding this health-check mechanism is usually not necessary, as we retrieve the health state of the instances directly
from the Service Registry.
TIP: The `HealthCheckServiceInstanceListSupplier` relies on having updated instances provided by a delegate flux. In the rare cases when you want to use a delegate that does not refresh the instances, even though the list of instances may change (such as the `DiscoveryClientServiceInstanceListSupplier` provided by us), you can set `spring.cloud.loadbalancer.health-check.refetch-instances` to `true` to have the instance list refreshed by the `HealthCheckServiceInstanceListSupplier`. You can then also adjust the refretch intervals by modifying the value of `spring.cloud.loadbalancer.health-check.refetch-instances-interval` and opt to disable the additional healthcheck repetitions by setting `spring.cloud.loadbalancer.health-check.repeat-health-check` to `false` as every instances refetch
will also trigger a healthcheck.
`HealthCheckServiceInstanceListSupplier` uses properties prefixed with
`spring.cloud.loadbalancer.health-check`. You can set the `initialDelay` and `interval`
for the scheduler. You can set the default path for the healthcheck URL by setting
the value of the `spring.cloud.loadbalancer.health-check.path.default` property. You can also set a specific value for any given service by setting the value of the `spring.cloud.loadbalancer.health-check.path.[SERVICE_ID]` property, substituting `[SERVICE_ID]` with the correct ID of your service. If the `[SERVICE_ID]` is not specified, `/actuator/health` is used by default. If the `[SERVICE_ID]` is set to `null` or empty as a value, then the health check will not be executed. You can also set a custom port for health-check requests by setting the value of `spring.cloud.loadbalancer.health-check.port`. If none is set, the port under which the requested service is available at the service instance.
TIP: If you rely on the default path (`/actuator/health`), make sure you add `spring-boot-starter-actuator` to your collaborator's dependencies, unless you are planning to add such an endpoint on your own.
TIP: By default, the `healthCheckFlux` will emit on each alive `ServiceInstance` that has been retrieved. You can modify this behaviour by setting the value of `spring.cloud.loadbalancer.health-check.update-results-list` to `false`. If this property is set to `false`, the entire alive instances sequence is first collected into a list and only then emitted, which ensures the flux does not emit values in between the health-check intervals set in properties.
In order to use the health-check scheduler approach, you will have to instantiate a `HealthCheckServiceInstanceListSupplier` bean in a xref:spring-cloud-commons/loadbalancer.adoc#custom-loadbalancer-configuration[custom configuration].
We use delegates to work with `ServiceInstanceListSupplier` beans.
We suggest passing a `DiscoveryClientServiceInstanceListSupplier` delegate in the constructor of `HealthCheckServiceInstanceListSupplier`.
You can use this sample configuration to set it up:
[[health-check-based-custom-loadbalancer-configuration]]
[source,java,indent=0]
----
public class CustomLoadBalancerConfiguration {
@Bean
public ServiceInstanceListSupplier discoveryClientServiceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder()
.withDiscoveryClient()
.withHealthChecks()
.build(context);
}
}
----
TIP: For the non-reactive stack, create this supplier with the `withBlockingHealthChecks()`.
You can also pass your own `WebClient` or `RestTemplate` instance to be used for the checks.
WARNING: `HealthCheckServiceInstanceListSupplier` has its own caching mechanism based on Reactor Flux `replay()`. Therefore, if it's being used, you may want to skip wrapping that supplier with `CachingServiceInstanceListSupplier`.
NOTE: When you create your own configuration, `HealthCheckServiceInstanceListSupplier`, make sure to place it in the hierarchy directly after the supplier that retrieves the instances over the network, for example, `DiscoveryClientServiceInstanceListSupplier`, before any other filtering suppliers.
[[same-instance-preference-for-loadbalancer]]
== Same instance preference for LoadBalancer
You can set up the LoadBalancer in such a way that it prefers the instance that was previously selected, if that instance is available.
For that, you need to use `SameInstancePreferenceServiceInstanceListSupplier`. You can configure it either by setting the value of `spring.cloud.loadbalancer.configurations` to `same-instance-preference` or by providing your own `ServiceInstanceListSupplier` bean -- for example:
[source,java,indent=0]
----
public class CustomLoadBalancerConfiguration {
@Bean
public ServiceInstanceListSupplier discoveryClientServiceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder()
.withDiscoveryClient()
.withSameInstancePreference()
.build(context);
}
}
----
TIP: This is also a replacement for Zookeeper `StickyRule`.
[[request-based-sticky-session-for-loadbalancer]]
== Request-based Sticky Session for LoadBalancer
You can set up the LoadBalancer in such a way that it prefers the instance with `instanceId` provided in a request cookie. We currently support this if the request is being passed to the LoadBalancer through either `ClientRequestContext` or `ServerHttpRequestContext`, which are used by the SC LoadBalancer exchange filter functions and filters.
For that, you need to use the `RequestBasedStickySessionServiceInstanceListSupplier`. You can configure it either by setting the value of `spring.cloud.loadbalancer.configurations` to `request-based-sticky-session` or by providing your own `ServiceInstanceListSupplier` bean -- for example:
[[health-check-based-custom-loadbalancer-configuration-example]]
[source,java,indent=0]
----
public class CustomLoadBalancerConfiguration {
@Bean
public ServiceInstanceListSupplier discoveryClientServiceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder()
.withDiscoveryClient()
.withRequestBasedStickySession()
.build(context);
}
}
----
For that functionality, it is useful to have the selected service instance (which can be different from the one in the original request cookie if that one is not available) to be updated before sending the request forward. To do that, set the value of `spring.cloud.loadbalancer.sticky-session.add-service-instance-cookie` to `true`.
By default, the name of the cookie is `sc-lb-instance-id`. You can modify it by changing the value of the `spring.cloud.loadbalancer.instance-id-cookie-name` property.
NOTE: This feature is currently supported for WebClient-backed load-balancing.
[[spring-cloud-loadbalancer-hints]]
== Spring Cloud LoadBalancer Hints
Spring Cloud LoadBalancer lets you set `String` hints that are passed to the LoadBalancer within the `Request` object and that can later be used in `ReactiveLoadBalancer` implementations that can handle them.
You can set a default hint for all services by setting the value of the `spring.cloud.loadbalancer.hint.default` property. You can also set a specific value
for any given service by setting the value of the `spring.cloud.loadbalancer.hint.[SERVICE_ID]` property, substituting `[SERVICE_ID]` with the correct ID of your service. If the hint is not set by the user, `default` is used.
[[hints-based-loadbalancing]]
== Hint-Based Load-Balancing
We also provide a `HintBasedServiceInstanceListSupplier`, which is a `ServiceInstanceListSupplier` implementation for hint-based instance selection.
`HintBasedServiceInstanceListSupplier` checks for a hint request header (the default header-name is `X-SC-LB-Hint`, but you can modify it by changing the value of the `spring.cloud.loadbalancer.hint-header-name` property) and, if it finds a hint request header, uses the hint value passed in the header to filter service instances.
If no hint header has been added, `HintBasedServiceInstanceListSupplier` uses xref:spring-cloud-commons/loadbalancer.adoc#spring-cloud-loadbalancer-hints[hint values from properties] to filter service instances.
If no hint is set, either by the header or by properties, all service instances provided by the delegate are returned.
While filtering, `HintBasedServiceInstanceListSupplier` looks for service instances that have a matching value set under the `hint` key in their `metadataMap`. If no matching instances are found, all instances provided by the delegate are returned.
You can use the following sample configuration to set it up:
[[hints-based-custom-loadbalancer-configuration]]
[source,java,indent=0]
----
public class CustomLoadBalancerConfiguration {
@Bean
public ServiceInstanceListSupplier discoveryClientServiceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder()
.withDiscoveryClient()
.withCaching()
.withHints()
.build(context);
}
}
----
[[transform-the-load-balanced-http-request]]
== Transform the load-balanced HTTP request
You can use the selected `ServiceInstance` to transform the load-balanced HTTP Request.
For `RestTemplate`, you need to implement and define `LoadBalancerRequestTransformer` as follows:
[source,java,indent=0]
----
@Bean
public LoadBalancerRequestTransformer transformer() {
return new LoadBalancerRequestTransformer() {
@Override
public HttpRequest transformRequest(HttpRequest request, ServiceInstance instance) {
return new HttpRequestWrapper(request) {
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.putAll(super.getHeaders());
headers.add("X-InstanceId", instance.getInstanceId());
return headers;
}
};
}
};
}
----
For `WebClient`, you need to implement and define `LoadBalancerClientRequestTransformer` as follows:
[source,java,indent=0]
----
@Bean
public LoadBalancerClientRequestTransformer transformer() {
return new LoadBalancerClientRequestTransformer() {
@Override
public ClientRequest transformRequest(ClientRequest request, ServiceInstance instance) {
return ClientRequest.from(request)
.header("X-InstanceId", instance.getInstanceId())
.build();
}
};
}
----
If multiple transformers are defined, they are applied in the order in which Beans are defined.
Alternatively, you can use `LoadBalancerRequestTransformer.DEFAULT_ORDER` or `LoadBalancerClientRequestTransformer.DEFAULT_ORDER` to specify the order.
[[spring-cloud-loadbalancer-starter]]
== Spring Cloud LoadBalancer Starter
We also provide a starter that allows you to easily add Spring Cloud LoadBalancer in a Spring Boot app.
In order to use it, just add `org.springframework.cloud:spring-cloud-starter-loadbalancer` to your Spring Cloud dependencies in your build file.
NOTE: Spring Cloud LoadBalancer starter includes
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-caching.html[Spring Boot Caching]
and https://github.com/stoyanr/Evictor[Evictor].
[[custom-loadbalancer-configuration]]
== Passing Your Own Spring Cloud LoadBalancer Configuration
You can also use the `@LoadBalancerClient` annotation to pass your own load-balancer client configuration, passing the name of the load-balancer client and the configuration class, as follows:
[source,java,indent=0]
----
@Configuration
@LoadBalancerClient(value = "stores", configuration = CustomLoadBalancerConfiguration.class)
public class MyConfiguration {
@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {
return WebClient.builder();
}
}
----
TIP: In order to make working on your own LoadBalancer configuration easier, we have added a `builder()` method to the `ServiceInstanceListSupplier` class.
TIP: You can also use our alternative predefined configurations in place of the default ones by setting the value of `spring.cloud.loadbalancer.configurations` property to `zone-preference` to use `ZonePreferenceServiceInstanceListSupplier` with caching or to `health-check` to use `HealthCheckServiceInstanceListSupplier` with caching.
You can use this feature to instantiate different implementations of `ServiceInstanceListSupplier` or `ReactorLoadBalancer`, either written by you, or provided by us as alternatives (for example `ZonePreferenceServiceInstanceListSupplier`) to override the default setup.
You can see an example of a custom configuration xref:spring-cloud-commons/loadbalancer.adoc#zoned-based-custom-loadbalancer-configuration[here].
NOTE: The annotation `value` arguments (`stores` in the example above) specifies the service id of the service that we should send the requests to with the given custom configuration.
You can also pass multiple configurations (for more than one load-balancer client) through the `@LoadBalancerClients` annotation, as the following example shows:
[source,java,indent=0]
----
@Configuration
@LoadBalancerClients({@LoadBalancerClient(value = "stores", configuration = StoresLoadBalancerClientConfiguration.class), @LoadBalancerClient(value = "customers", configuration = CustomersLoadBalancerClientConfiguration.class)})
public class MyConfiguration {
@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {
return WebClient.builder();
}
}
----
NOTE: The classes you pass as `@LoadBalancerClient` or `@LoadBalancerClients` configuration arguments should either not be annotated with `@Configuration` or be outside component scan scope.
NOTE: When you create your own configuration, if you use `CachingServiceInstanceListSupplier` or `HealthCheckServiceInstanceListSupplier`, makes sure to use one of them, not both, and make sure to place it in the hierarchy directly after the supplier that retrieves the instances over the network, for example, `DiscoveryClientServiceInstanceListSupplier`, before any other filtering suppliers.
[[loadbalancer-lifecycle]]
== Spring Cloud LoadBalancer Lifecycle
One type of bean that it may be useful to register using xref:spring-cloud-commons/loadbalancer.adoc#custom-loadbalancer-configuration[Custom LoadBalancer configuration] is `LoadBalancerLifecycle`.
The `LoadBalancerLifecycle` beans provide callback methods, named `onStart(Request<RC> request)`, `onStartRequest(Request<RC> request, Response<T> lbResponse)` and `onComplete(CompletionContext<RES, T, RC> completionContext)`, that you should implement to specify what actions should take place before and after load-balancing.
`onStart(Request<RC> request)` takes a `Request` object as a parameter. It contains data that is used to select an appropriate instance, including the downstream client request and xref:spring-cloud-commons/loadbalancer.adoc#spring-cloud-loadbalancer-hints[hint]. `onStartRequest` also takes the `Request` object and, additionally, the `Response<T>` object as parameters. On the other hand, a `CompletionContext` object is provided to the `onComplete(CompletionContext<RES, T, RC> completionContext)` method. It contains the LoadBalancer `Response`, including the selected service instance, the `Status` of the request executed against that service instance and (if available) the response returned to the downstream client, and (if an exception has occurred) the corresponding `Throwable`.
The `supports(Class requestContextClass, Class responseClass,
Class serverTypeClass)` method can be used to determine whether the processor in question handles objects of provided types. If not overridden by the user, it returns `true`.
NOTE: In the preceding method calls, `RC` means `RequestContext` type, `RES` means client response type, and `T` means returned server type.
[[loadbalancer-micrometer-stats-lifecycle]]
== Spring Cloud LoadBalancer Statistics
We provide a `LoadBalancerLifecycle` bean called `MicrometerStatsLoadBalancerLifecycle`, which uses Micrometer to provide statistics for load-balanced calls.
In order to get this bean added to your application context,
set the value of the `spring.cloud.loadbalancer.stats.micrometer.enabled` to `true` and have a `MeterRegistry` available (for example, by adding https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html[Spring Boot Actuator] to your project).
`MicrometerStatsLoadBalancerLifecycle` registers the following meters in `MeterRegistry`:
* `loadbalancer.requests.active`: A gauge that allows you to monitor the number of currently active requests for any service instance (service instance data available via tags);
* `loadbalancer.requests.success`: A timer that measures the time of execution of any load-balanced requests that have ended in passing a response on to the underlying client;
* `loadbalancer.requests.failed`: A timer that measures the time of execution of any load-balanced requests that have ended with an exception;
* `loadbalancer.requests.discard`: A counter that measures the number of discarded load-balanced requests, i.e. requests where a service instance to run the request on has not been retrieved by the LoadBalancer.
Additional information regarding the service instances, request data, and response data is added to metrics via tags whenever available.
NOTE: For some implementations, such as `BlockingLoadBalancerClient`, request and response data might not be available, as we establish generic types from arguments and might not be able to determine the types and read the data.
NOTE: The meters are registered in the registry when at least one record is added for a given meter.
TIP: You can further configure the behavior of those metrics (for example, add https://micrometer.io/docs/concepts#_histograms_and_percentiles[publishing percentiles and histograms]) by https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready-metrics-per-meter-properties[adding `MeterFilters`].
[[configuring-individual-loadbalancerclients]]
== Configuring Individual LoadBalancerClients
Individual Loadbalancer clients may be configured individually with a different prefix `spring.cloud.loadbalancer.clients.<clientId>.*` where `clientId` is the name of the loadbalancer. Default configuration values may be set in the `spring.cloud.loadbalancer.*` namespace and will be merged with the client specific values taking precedence
.application.yml
----
spring:
cloud:
loadbalancer:
health-check:
initial-delay: 1s
clients:
myclient:
health-check:
interval: 30s
----
The above example will result in a merged health-check `@ConfigurationProperties` object with `initial-delay=1s` and `interval=30s`.
The per-client configuration properties work for most of the properties, apart from the following global ones:
- `spring.cloud.loadbalancer.enabled` - globally enables or disables load-balancing
- `spring.cloud.loadbalancer.retry.enabled` - globally enables or disables load-balanced retries. If you enable it globally, you can still disable retries for specific clients using the `client`-prefixed properties, but not the other way round
- `spring.cloud.loadbalancer.cache.enabled` - globally enables or disables LoadBalancer caching. If you enable it globally, you can still disable caching for specific clients by creating a xref:spring-cloud-commons/loadbalancer.adoc#custom-loadbalancer-configuration[custom configuration] that does not include the `CachingServiceInstanceListSupplier` in the `ServiceInstanceListSupplier` delegates hierarchy, but not the other way round.
- `spring.cloud.loadbalancer.stats.micrometer.enabled` - globally enables or disables LoadBalancer Micrometer metrics
NOTE: For the properties where maps where already used, where you can specify a different value per-client without using the `clients` keyword (for example, `hints`, `health-check.path`), we have kept that behaviour in order to keep the library backwards compatible. It will be modified in the next major release.
NOTE: Starting with `4.1.0`, we have introduced the `callGetWithRequestOnDelegates` flag in `LoadBalancerProperties`. If this flag is set to `true`, `ServiceInstanceListSupplier#get(Request request)` method will be implemented to call `delegate.get(request)` in classes assignable from `DelegatingServiceInstanceListSupplier` that don't already implement that method, with the exclusion of `CachingServiceInstanceListSupplier` and `HealthCheckServiceInstanceListSupplier`, which should be placed in the instance supplier hierarchy directly after the supplier performing instance retrieval over the network, before any request-based filtering is done. It is set to `true` by default.
[[-aot-and-native-image-support]]
== AOT and Native Image Support
Since `4.0.0`, Spring Cloud LoadBalancer supports Spring AOT transformations and native images. However, to use this feature, you need to explicitly define your `LoadBalancerClient` service IDs. You can do so by using the `value` or `name` attributes of the `@LoadBalancerClient` annotation or as values of the `spring.cloud.loadbalancer.eager-load.clients` property.

89
docs/modules/ROOT/pages/spring-cloud-commons/security.adoc

@ -0,0 +1,89 @@ @@ -0,0 +1,89 @@
[[spring-cloud-security]]
= Security
[[spring-cloud-security-single-sign-on]]
== Single Sign On
NOTE: All of the OAuth2 SSO and resource server features moved to Spring Boot
in version 1.3. You can find documentation in the
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/[Spring Boot user guide].
[[spring-cloud-security-client-token-relay]]
=== Client Token Relay
If your app is a user facing OAuth2 client (i.e. has declared
`@EnableOAuth2Sso` or `@EnableOAuth2Client`) then it has an
`OAuth2ClientContext` in request scope from Spring Boot. You can
create your own `OAuth2RestTemplate` from this context and an
autowired `OAuth2ProtectedResourceDetails`, and then the context will
always forward the access token downstream, also refreshing the access
token automatically if it expires. (These are features of Spring
Security and Spring Boot.)
[[spring-cloud-security-resource-server-token-relay]]
=== Resource Server Token Relay
If your app has `@EnableResourceServer` you might want to relay the
incoming token downstream to other services. If you use a
`RestTemplate` to contact the downstream services then this is just a
matter of how to create the template with the right context.
If your service uses `UserInfoTokenServices` to authenticate incoming
tokens (i.e. it is using the `security.oauth2.user-info-uri`
configuration), then you can simply create an `OAuth2RestTemplate`
using an autowired `OAuth2ClientContext` (it will be populated by the
authentication process before it hits the backend code). Equivalently
(with Spring Boot 1.4), you can inject a
`UserInfoRestTemplateFactory` and grab its `OAuth2RestTemplate` in
your configuration. For example:
.MyConfiguration.java
[source,java]
----
@Bean
public OAuth2RestTemplate restTemplate(UserInfoRestTemplateFactory factory) {
return factory.getUserInfoRestTemplate();
}
----
This rest template will then have the same `OAuth2ClientContext`
(request-scoped) that is used by the authentication filter, so you can
use it to send requests with the same access token.
If your app is not using `UserInfoTokenServices` but is still a client
(i.e. it declares `@EnableOAuth2Client` or `@EnableOAuth2Sso`), then
with Spring Security Cloud any `OAuth2RestOperations` that the user
creates from an `@Autowired` `OAuth2Context` will also forward
tokens. This feature is implemented by default as an MVC handler
interceptor, so it only works in Spring MVC. If you are not using MVC
you can use a custom filter or AOP interceptor wrapping an
`AccessTokenContextRelay` to provide the same feature.
Here's a basic
example showing the use of an autowired rest template created
elsewhere ("foo.com" is a Resource Server accepting the same tokens as
the surrounding app):
.MyController.java
[source,java]
----
@Autowired
private OAuth2RestOperations restTemplate;
@RequestMapping("/relay")
public String relay() {
ResponseEntity<String> response =
restTemplate.getForEntity("https://foo.com/bar", String.class);
return "Success! (" + response.getBody() + ")";
}
----
If you don't want to forward tokens (and that is a valid
choice, since you might want to act as yourself, rather than the
client that sent you the token), then you only need to create your own
`OAuth2Context` instead of autowiring the default one.
Feign clients will also pick up an interceptor that uses the
`OAuth2ClientContext` if it is available, so they should also do a
token relay anywhere where a `RestTemplate` would.

3
docs/modules/ROOT/partials/_attributes.adoc

@ -0,0 +1,3 @@ @@ -0,0 +1,3 @@
:sc-ext: java
:project-full-name: Spring Cloud Commons
:all: {asterisk}{asterisk}

84
docs/modules/ROOT/partials/_configprops.adoc

@ -0,0 +1,84 @@ @@ -0,0 +1,84 @@
|===
|Name | Default | Description
|spring.cloud.compatibility-verifier.compatible-boot-versions | `+++3.2.x+++` | Default accepted versions for the Spring Boot dependency. You can set {@code x} for the patch version if you don't want to specify a concrete value. Example: {@code 3.4.x}
|spring.cloud.compatibility-verifier.enabled | `+++false+++` | Enables creation of Spring Cloud compatibility verification.
|spring.cloud.config.allow-override | `+++true+++` | Flag to indicate that {@link #isOverrideSystemProperties() systemPropertiesOverride} can be used. Set to false to prevent users from changing the default accidentally. Default true.
|spring.cloud.config.initialize-on-context-refresh | `+++false+++` | Flag to initialize bootstrap configuration on context refresh event. Default false.
|spring.cloud.config.override-none | `+++false+++` | Flag to indicate that when {@link #setAllowOverride(boolean) allowOverride} is true, external properties should take lowest priority and should not override any existing property sources (including local config files). Default false. This will only have an effect when using config first bootstrap.
|spring.cloud.config.override-system-properties | `+++true+++` | Flag to indicate that the external properties should override system properties. Default true.
|spring.cloud.decrypt-environment-post-processor.enabled | `+++true+++` | Enable the DecryptEnvironmentPostProcessor.
|spring.cloud.discovery.client.composite-indicator.enabled | `+++true+++` | Enables discovery client composite health indicator.
|spring.cloud.discovery.client.health-indicator.enabled | `+++true+++` |
|spring.cloud.discovery.client.health-indicator.include-description | `+++false+++` |
|spring.cloud.discovery.client.health-indicator.use-services-query | `+++true+++` | Whether or not the indicator should use {@link DiscoveryClient#getServices} to check its health. When set to {@code false} the indicator instead uses the lighter {@link DiscoveryClient#probe()}. This can be helpful in large deployments where the number of services returned makes the operation unnecessarily heavy.
|spring.cloud.discovery.client.simple.instances | |
|spring.cloud.discovery.client.simple.local.host | |
|spring.cloud.discovery.client.simple.local.instance-id | |
|spring.cloud.discovery.client.simple.local.metadata | |
|spring.cloud.discovery.client.simple.local.port | `+++0+++` |
|spring.cloud.discovery.client.simple.local.secure | `+++false+++` |
|spring.cloud.discovery.client.simple.local.service-id | |
|spring.cloud.discovery.client.simple.local.uri | |
|spring.cloud.discovery.client.simple.order | |
|spring.cloud.discovery.enabled | `+++true+++` | Enables discovery client health indicators.
|spring.cloud.features.enabled | `+++true+++` | Enables the features endpoint.
|spring.cloud.httpclientfactories.apache.enabled | `+++true+++` | Enables creation of Apache Http Client factory beans.
|spring.cloud.httpclientfactories.ok.enabled | `+++true+++` | Enables creation of OK Http Client factory beans.
|spring.cloud.hypermedia.refresh.fixed-delay | `+++5000+++` |
|spring.cloud.hypermedia.refresh.initial-delay | `+++10000+++` |
|spring.cloud.inetutils.default-hostname | `+++localhost+++` | The default hostname. Used in case of errors.
|spring.cloud.inetutils.default-ip-address | `+++127.0.0.1+++` | The default IP address. Used in case of errors.
|spring.cloud.inetutils.ignored-interfaces | | List of Java regular expressions for network interfaces that will be ignored.
|spring.cloud.inetutils.preferred-networks | | List of Java regular expressions for network addresses that will be preferred.
|spring.cloud.inetutils.timeout-seconds | `+++1+++` | Timeout, in seconds, for calculating hostname.
|spring.cloud.inetutils.use-only-site-local-interfaces | `+++false+++` | Whether to use only interfaces with site local addresses. See {@link InetAddress#isSiteLocalAddress()} for more details.
|spring.cloud.loadbalancer.cache.caffeine.spec | | The spec to use to create caches. See CaffeineSpec for more details on the spec format.
|spring.cloud.loadbalancer.cache.capacity | `+++256+++` | Initial cache capacity expressed as int.
|spring.cloud.loadbalancer.cache.enabled | `+++true+++` | Enables Spring Cloud LoadBalancer caching mechanism.
|spring.cloud.loadbalancer.cache.ttl | `+++35s+++` | Time To Live - time counted from writing of the record, after which cache entries are expired, expressed as a {@link Duration}. The property {@link String} has to be in keeping with the appropriate syntax as specified in Spring Boot <code>StringToDurationConverter</code>. @see <a href= "https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToDurationConverter.java">StringToDurationConverter.java</a>
|spring.cloud.loadbalancer.call-get-with-request-on-delegates | `+++true+++` | If this flag is set to {@code true}, {@code ServiceInstanceListSupplier#get(Request request)} method will be implemented to call {@code delegate.get(request)} in classes assignable from {@code DelegatingServiceInstanceListSupplier} that don't already implement that method, with the exclusion of {@code CachingServiceInstanceListSupplier} and {@code HealthCheckServiceInstanceListSupplier}, which should be placed in the instance supplier hierarchy directly after the supplier performing instance retrieval over the network, before any request-based filtering is done, {@code true} by default.
|spring.cloud.loadbalancer.clients | |
|spring.cloud.loadbalancer.configurations | `+++default+++` | Enables a predefined LoadBalancer configuration.
|spring.cloud.loadbalancer.eager-load.clients | | Names of the clients.
|spring.cloud.loadbalancer.enabled | `+++true+++` | Enables Spring Cloud LoadBalancer.
|spring.cloud.loadbalancer.health-check.initial-delay | `+++0+++` | Initial delay value for the HealthCheck scheduler.
|spring.cloud.loadbalancer.health-check.interval | `+++25s+++` | Interval for rerunning the HealthCheck scheduler.
|spring.cloud.loadbalancer.health-check.interval | `+++25s+++` | Interval for rerunning the HealthCheck scheduler.
|spring.cloud.loadbalancer.health-check.path | | Path at which the health-check request should be made. Can be set up per `serviceId`. A `default` value can be set up as well. If none is set up, `/actuator/health` will be used.
|spring.cloud.loadbalancer.health-check.port | | Path at which the health-check request should be made. If none is set, the port under which the requested service is available at the service instance.
|spring.cloud.loadbalancer.health-check.refetch-instances | `+++false+++` | Indicates whether the instances should be refetched by the `HealthCheckServiceInstanceListSupplier`. This can be used if the instances can be updated and the underlying delegate does not provide an ongoing flux.
|spring.cloud.loadbalancer.health-check.refetch-instances-interval | `+++25s+++` | Interval for refetching available service instances.
|spring.cloud.loadbalancer.health-check.repeat-health-check | `+++true+++` | Indicates whether health checks should keep repeating. It might be useful to set it to `false` if periodically refetching the instances, as every refetch will also trigger a healthcheck.
|spring.cloud.loadbalancer.health-check.update-results-list | `+++true+++` | Indicates whether the {@code healthCheckFlux} should emit on each alive {@link ServiceInstance} that has been retrieved. If set to {@code false}, the entire alive instances sequence is first collected into a list and only then emitted.
|spring.cloud.loadbalancer.hint | | Allows setting the value of <code>hint</code> that is passed on to the LoadBalancer request and can subsequently be used in {@link ReactiveLoadBalancer} implementations.
|spring.cloud.loadbalancer.hint-header-name | `+++X-SC-LB-Hint+++` | Allows setting the name of the header used for passing the hint for hint-based service instance filtering.
|spring.cloud.loadbalancer.retry.avoid-previous-instance | `+++true+++` | Enables wrapping ServiceInstanceListSupplier beans with `RetryAwareServiceInstanceListSupplier` if Spring-Retry is in the classpath.
|spring.cloud.loadbalancer.retry.backoff.enabled | `+++false+++` | Indicates whether Reactor Retry backoffs should be applied.
|spring.cloud.loadbalancer.retry.backoff.jitter | `+++0.5+++` | Used to set `RetryBackoffSpec.jitter`.
|spring.cloud.loadbalancer.retry.backoff.max-backoff | `+++Long.MAX ms+++` | Used to set `RetryBackoffSpec.maxBackoff`.
|spring.cloud.loadbalancer.retry.backoff.min-backoff | `+++5 ms+++` | Used to set `RetryBackoffSpec#minBackoff`.
|spring.cloud.loadbalancer.retry.enabled | `+++true+++` | Enables LoadBalancer retries.
|spring.cloud.loadbalancer.retry.max-retries-on-next-service-instance | `+++1+++` | Number of retries to be executed on the next `ServiceInstance`. A `ServiceInstance` is chosen before each retry call.
|spring.cloud.loadbalancer.retry.max-retries-on-same-service-instance | `+++0+++` | Number of retries to be executed on the same `ServiceInstance`.
|spring.cloud.loadbalancer.retry.retry-on-all-exceptions | `+++false+++` | Indicates retries should be attempted for all exceptions, not only those specified in `retryableExceptions`.
|spring.cloud.loadbalancer.retry.retry-on-all-operations | `+++false+++` | Indicates retries should be attempted on operations other than `HttpMethod.GET`.
|spring.cloud.loadbalancer.retry.retryable-exceptions | `+++{}+++` | A `Set` of `Throwable` classes that should trigger a retry.
|spring.cloud.loadbalancer.retry.retryable-status-codes | `+++{}+++` | A `Set` of status codes that should trigger a retry.
|spring.cloud.loadbalancer.service-discovery.timeout | | String representation of Duration of the timeout for calls to service discovery.
|spring.cloud.loadbalancer.stats.micrometer.enabled | `+++false+++` | Enables Spring Cloud LoadBalancer Micrometer stats.
|spring.cloud.loadbalancer.sticky-session.add-service-instance-cookie | `+++false+++` | Indicates whether a cookie with the newly selected instance should be added by LoadBalancer.
|spring.cloud.loadbalancer.sticky-session.instance-id-cookie-name | `+++sc-lb-instance-id+++` | The name of the cookie holding the preferred instance id.
|spring.cloud.loadbalancer.x-forwarded.enabled | `+++false+++` | To Enable X-Forwarded Headers.
|spring.cloud.loadbalancer.zone | | Spring Cloud LoadBalancer zone.
|spring.cloud.refresh.additional-property-sources-to-retain | | Additional property sources to retain during a refresh. Typically only system property sources are retained. This property allows property sources, such as property sources created by EnvironmentPostProcessors to be retained as well.
|spring.cloud.refresh.enabled | `+++true+++` | Enables autoconfiguration for the refresh scope and associated features.
|spring.cloud.refresh.extra-refreshable | `+++true+++` | Additional class names for beans to post process into refresh scope.
|spring.cloud.refresh.never-refreshable | `+++true+++` | Comma separated list of class names for beans to never be refreshed or rebound.
|spring.cloud.refresh.on-restart.enabled | `+++true+++` | Enable refreshing context on start.
|spring.cloud.service-registry.auto-registration.enabled | `+++true+++` | Whether service auto-registration is enabled. Defaults to true.
|spring.cloud.service-registry.auto-registration.fail-fast | `+++false+++` | Whether startup fails if there is no AutoServiceRegistration. Defaults to false.
|spring.cloud.service-registry.auto-registration.register-management | `+++true+++` | Whether to register the management as a service. Defaults to true.
|spring.cloud.util.enabled | `+++true+++` | Enables creation of Spring Cloud utility beans.
|===

11
docs/modules/ROOT/partials/_conventions.adoc

@ -0,0 +1,11 @@ @@ -0,0 +1,11 @@
[[observability-conventions]]
=== Observability - Conventions
Below you can find a list of all `GlobalObservationConvention` and `ObservationConvention` declared by this project.
.ObservationConvention implementations
|===
|ObservationConvention Class Name | Applicable ObservationContext Class Name
|`org.springframework.cloud.client.circuitbreaker.observation.CircuitBreakerObservationConvention`|`CircuitBreakerObservationContext`
|`org.springframework.cloud.client.circuitbreaker.observation.DefaultCircuitBreakerObservationConvention`|`CircuitBreakerObservationContext`
|===

70
docs/modules/ROOT/partials/_metrics.adoc

@ -0,0 +1,70 @@ @@ -0,0 +1,70 @@
[[observability-metrics]]
=== Observability - Metrics
Below you can find a list of all metrics declared by this project.
[[observability-metrics-circuit-breaker-function-observation]]
==== Circuit Breaker Function Observation
____
Observation created when we wrap a Function passed to the CircuitBreaker as fallback.
____
**Metric name** `spring.cloud.circuitbreaker` (defined by convention class `org.springframework.cloud.client.circuitbreaker.observation.DefaultCircuitBreakerObservationConvention`). **Type** `timer`.
**Metric name** `spring.cloud.circuitbreaker.active` (defined by convention class `org.springframework.cloud.client.circuitbreaker.observation.DefaultCircuitBreakerObservationConvention`). **Type** `long task timer`.
IMPORTANT: KeyValues that are added after starting the Observation might be missing from the *.active metrics.
IMPORTANT: Micrometer internally uses `nanoseconds` for the baseunit. However, each backend determines the actual baseunit. (i.e. Prometheus uses seconds)
Fully qualified name of the enclosing class `org.springframework.cloud.client.circuitbreaker.observation.CircuitBreakerObservationDocumentation`.
IMPORTANT: All tags must be prefixed with `spring.cloud.circuitbreaker` prefix!
.Low cardinality Keys
[cols="a,a"]
|===
|Name | Description
|`spring.cloud.circuitbreaker.type` _(required)_|Defines the type of wrapped lambda.
|===
[[observability-metrics-circuit-breaker-supplier-observation]]
==== Circuit Breaker Supplier Observation
____
Observation created when we wrap a Supplier passed to the CircuitBreaker.
____
**Metric name** `spring.cloud.circuitbreaker` (defined by convention class `org.springframework.cloud.client.circuitbreaker.observation.DefaultCircuitBreakerObservationConvention`). **Type** `timer`.
**Metric name** `spring.cloud.circuitbreaker.active` (defined by convention class `org.springframework.cloud.client.circuitbreaker.observation.DefaultCircuitBreakerObservationConvention`). **Type** `long task timer`.
IMPORTANT: KeyValues that are added after starting the Observation might be missing from the *.active metrics.
IMPORTANT: Micrometer internally uses `nanoseconds` for the baseunit. However, each backend determines the actual baseunit. (i.e. Prometheus uses seconds)
Fully qualified name of the enclosing class `org.springframework.cloud.client.circuitbreaker.observation.CircuitBreakerObservationDocumentation`.
IMPORTANT: All tags must be prefixed with `spring.cloud.circuitbreaker` prefix!
.Low cardinality Keys
[cols="a,a"]
|===
|Name | Description
|`spring.cloud.circuitbreaker.type` _(required)_|Defines the type of wrapped lambda.
|===

44
docs/modules/ROOT/partials/_spans.adoc

@ -0,0 +1,44 @@ @@ -0,0 +1,44 @@
[[observability-spans]]
=== Observability - Spans
Below you can find a list of all spans declared by this project.
[[observability-spans-circuit-breaker-function-observation]]
==== Circuit Breaker Function Observation Span
> Observation created when we wrap a Function passed to the CircuitBreaker as fallback.
**Span name** `spring.cloud.circuitbreaker` (defined by convention class `org.springframework.cloud.client.circuitbreaker.observation.DefaultCircuitBreakerObservationConvention`).
Fully qualified name of the enclosing class `org.springframework.cloud.client.circuitbreaker.observation.CircuitBreakerObservationDocumentation`.
IMPORTANT: All tags must be prefixed with `spring.cloud.circuitbreaker` prefix!
.Tag Keys
|===
|Name | Description
|`spring.cloud.circuitbreaker.type` _(required)_|Defines the type of wrapped lambda.
|===
[[observability-spans-circuit-breaker-supplier-observation]]
==== Circuit Breaker Supplier Observation Span
> Observation created when we wrap a Supplier passed to the CircuitBreaker.
**Span name** `spring.cloud.circuitbreaker` (defined by convention class `org.springframework.cloud.client.circuitbreaker.observation.DefaultCircuitBreakerObservationConvention`).
Fully qualified name of the enclosing class `org.springframework.cloud.client.circuitbreaker.observation.CircuitBreakerObservationDocumentation`.
IMPORTANT: All tags must be prefixed with `spring.cloud.circuitbreaker` prefix!
.Tag Keys
|===
|Name | Description
|`spring.cloud.circuitbreaker.type` _(required)_|Defines the type of wrapped lambda.
|===

59
docs/pom.xml

@ -8,7 +8,7 @@ @@ -8,7 +8,7 @@
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons-parent</artifactId>
<version>3.0.7-SNAPSHOT</version>
<version>4.1.0-SNAPSHOT</version>
</parent>
<packaging>jar</packaging>
<name>Spring Cloud Commons Docs</name>
@ -17,7 +17,14 @@ @@ -17,7 +17,14 @@
<docs.main>spring-cloud-commons</docs.main>
<main.basedir>${basedir}/..</main.basedir>
<configprops.inclusionPattern>spring.cloud.*</configprops.inclusionPattern>
<upload-docs-zip.phase>deploy</upload-docs-zip.phase>
<!-- Don't upload docs jar to central / repo.spring.io -->
<maven-deploy-plugin-default.phase>none</maven-deploy-plugin-default.phase>
<!-- Observability -->
<micrometer-docs-generator.version>1.0.2</micrometer-docs-generator.version>
<micrometer-docs-generator.inputPath>${maven.multiModuleProjectDirectory}/spring-cloud-commons/</micrometer-docs-generator.inputPath>
<micrometer-docs-generator.inclusionPattern>.*</micrometer-docs-generator.inclusionPattern>
<micrometer-docs-generator.outputPath>${maven.multiModuleProjectDirectory}/docs/modules/ROOT/partials/</micrometer-docs-generator.outputPath>
</properties>
<dependencies>
<dependency>
@ -36,26 +43,58 @@ @@ -36,26 +43,58 @@
<profile>
<id>docs</id>
<build>
<resources>
<resource>
<directory>src/main/antora/resources/antora-resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-observability-docs</id>
<phase>${generate-docs.phase}</phase>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>io.micrometer.docs.DocsGeneratorCommand</mainClass>
<includePluginDependencies>true</includePluginDependencies>
<arguments>
<argument>${micrometer-docs-generator.inputPath}</argument>
<argument>${micrometer-docs-generator.inclusionPattern}</argument>
<argument>${micrometer-docs-generator.outputPath}</argument>
</arguments>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-docs-generator</artifactId>
<version>${micrometer-docs-generator.version}</version>
<type>jar</type>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>io.spring.maven.antora</groupId>
<artifactId>antora-component-version-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<groupId>io.spring.maven.antora</groupId>
<artifactId>antora-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>

20
docs/src/main/antora/resources/antora-resources/antora.yml

@ -0,0 +1,20 @@ @@ -0,0 +1,20 @@
version: @antora-component.version@
prerelease: @antora-component.prerelease@
asciidoc:
attributes:
attribute-missing: 'warn'
chomp: 'all'
project-root: @maven.multiModuleProjectDirectory@
github-repo: @docs.main@
github-raw: https://raw.githubusercontent.com/spring-cloud/@docs.main@/@github-tag@
github-code: https://github.com/spring-cloud/@docs.main@/tree/@github-tag@
github-issues: https://github.com/spring-cloud/@docs.main@/issues/
github-wiki: https://github.com/spring-cloud/@docs.main@/wiki
spring-cloud-version: @project.version@
github-tag: @github-tag@
version-type: @version-type@
docs-url: https://docs.spring.io/@docs.main@/docs/@project.version@
raw-docs-url: https://raw.githubusercontent.com/spring-cloud/@docs.main@/@github-tag@
project-version: @project.version@
project-name: @docs.main@

11
docs/src/main/asciidoc/README.adoc

@ -1,11 +1,12 @@ @@ -1,11 +1,12 @@
image::https://circleci.com/gh/spring-cloud/spring-cloud-commons.svg?style=svg[Build Status, link=https://circleci.com/gh/spring-cloud/spring-cloud-commons]
include::intro.adoc[]
== Building
[[building]]
= Building
:page-section-summary-toc: 1
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/docs/src/main/asciidoc/building.adoc[]
== Contributing
[[contributing]]
= Contributing
:page-section-summary-toc: 1
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/main/docs/src/main/asciidoc/contributing.adoc[]

16
docs/src/main/asciidoc/_attributes.adoc

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

65
docs/src/main/asciidoc/_configprops.adoc

@ -1,65 +0,0 @@ @@ -1,65 +0,0 @@
|===
|Name | Default | Description
|spring.cloud.compatibility-verifier.compatible-boot-versions | | Default accepted versions for the Spring Boot dependency. You can set {@code x} for the patch version if you don't want to specify a concrete value. Example: {@code 3.4.x}
|spring.cloud.compatibility-verifier.enabled | `false` | Enables creation of Spring Cloud compatibility verification.
|spring.cloud.config.allow-override | `true` | Flag to indicate that {@link #isOverrideSystemProperties() systemPropertiesOverride} can be used. Set to false to prevent users from changing the default accidentally. Default true.
|spring.cloud.config.override-none | `false` | Flag to indicate that when {@link #setAllowOverride(boolean) allowOverride} is true, external properties should take lowest priority and should not override any existing property sources (including local config files). Default false.
|spring.cloud.config.override-system-properties | `true` | Flag to indicate that the external properties should override system properties. Default true.
|spring.cloud.decrypt-environment-post-processor.enabled | `true` | Enable the DecryptEnvironmentPostProcessor.
|spring.cloud.discovery.client.composite-indicator.enabled | `true` | Enables discovery client composite health indicator.
|spring.cloud.discovery.client.health-indicator.enabled | `true` |
|spring.cloud.discovery.client.health-indicator.include-description | `false` |
|spring.cloud.discovery.client.health-indicator.use-services-query | `true` | Whether or not the indicator should use {@link DiscoveryClient#getServices} to check its health. When set to {@code false} the indicator instead uses the lighter {@link DiscoveryClient#probe()}. This can be helpful in large deployments where the number of services returned makes the operation unnecessarily heavy.
|spring.cloud.discovery.client.simple.instances | |
|spring.cloud.discovery.client.simple.order | |
|spring.cloud.discovery.enabled | `true` | Enables discovery client health indicators.
|spring.cloud.features.enabled | `true` | Enables the features endpoint.
|spring.cloud.httpclientfactories.apache.enabled | `true` | Enables creation of Apache Http Client factory beans.
|spring.cloud.httpclientfactories.ok.enabled | `true` | Enables creation of OK Http Client factory beans.
|spring.cloud.hypermedia.refresh.fixed-delay | `5000` |
|spring.cloud.hypermedia.refresh.initial-delay | `10000` |
|spring.cloud.inetutils.default-hostname | `localhost` | The default hostname. Used in case of errors.
|spring.cloud.inetutils.default-ip-address | `127.0.0.1` | The default IP address. Used in case of errors.
|spring.cloud.inetutils.ignored-interfaces | | List of Java regular expressions for network interfaces that will be ignored.
|spring.cloud.inetutils.preferred-networks | | List of Java regular expressions for network addresses that will be preferred.
|spring.cloud.inetutils.timeout-seconds | `1` | Timeout, in seconds, for calculating hostname.
|spring.cloud.inetutils.use-only-site-local-interfaces | `false` | Whether to use only interfaces with site local addresses. See {@link InetAddress#isSiteLocalAddress()} for more details.
|spring.cloud.loadbalancer.cache.caffeine.spec | | The spec to use to create caches. See CaffeineSpec for more details on the spec format.
|spring.cloud.loadbalancer.cache.capacity | `256` | Initial cache capacity expressed as int.
|spring.cloud.loadbalancer.cache.enabled | `true` | Enables Spring Cloud LoadBalancer caching mechanism.
|spring.cloud.loadbalancer.cache.ttl | `35s` | Time To Live - time counted from writing of the record, after which cache entries are expired, expressed as a {@link Duration}. The property {@link String} has to be in keeping with the appropriate syntax as specified in Spring Boot <code>StringToDurationConverter</code>. @see <a href= "https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/StringToDurationConverter.java">StringToDurationConverter.java</a>
|spring.cloud.loadbalancer.configurations | `default` | Enables a predefined LoadBalancer configuration.
|spring.cloud.loadbalancer.enabled | `true` | Enables Spring Cloud LoadBalancer.
|spring.cloud.loadbalancer.health-check.initial-delay | `0` | Initial delay value for the HealthCheck scheduler.
|spring.cloud.loadbalancer.health-check.interval | `25s` | Interval for rerunning the HealthCheck scheduler.
|spring.cloud.loadbalancer.health-check.path | |
|spring.cloud.loadbalancer.health-check.refetch-instances | `false` | Indicates whether the instances should be refetched by the <code>HealthCheckServiceInstanceListSupplier</code>. This can be used if the instances can be updated and the underlying delegate does not provide an ongoing flux.
|spring.cloud.loadbalancer.health-check.refetch-instances-interval | `25s` | Interval for refetching available service instances.
|spring.cloud.loadbalancer.health-check.repeat-health-check | `true` | Indicates whether health checks should keep repeating. It might be useful to set it to <code>false</code> if periodically refetching the instances, as every refetch will also trigger a healthcheck.
|spring.cloud.loadbalancer.hint | | Allows setting the value of <code>hint</code> that is passed on to the LoadBalancer request and can subsequently be used in {@link ReactiveLoadBalancer} implementations.
|spring.cloud.loadbalancer.hint-header-name | `X-SC-LB-Hint` | Allows setting the name of the header used for passing the hint for hint-based service instance filtering.
|spring.cloud.loadbalancer.retry.avoid-previous-instance | `true` | Enables wrapping ServiceInstanceListSupplier beans with `RetryAwareServiceInstanceListSupplier` if Spring-Retry is in the classpath.
|spring.cloud.loadbalancer.retry.backoff.enabled | `false` | Indicates whether Reactor Retry backoffs should be applied.
|spring.cloud.loadbalancer.retry.backoff.jitter | `0.5` | Used to set {@link RetryBackoffSpec#jitter}.
|spring.cloud.loadbalancer.retry.backoff.max-backoff | | Used to set {@link RetryBackoffSpec#maxBackoff}.
|spring.cloud.loadbalancer.retry.backoff.min-backoff | `5ms` | Used to set {@link RetryBackoffSpec#minBackoff}.
|spring.cloud.loadbalancer.retry.enabled | `true` | Enables LoadBalancer retries.
|spring.cloud.loadbalancer.retry.max-retries-on-next-service-instance | `1` | Number of retries to be executed on the next <code>ServiceInstance</code>. A <code>ServiceInstance</code> is chosen before each retry call.
|spring.cloud.loadbalancer.retry.max-retries-on-same-service-instance | `0` | Number of retries to be executed on the same <code>ServiceInstance</code>.
|spring.cloud.loadbalancer.retry.retry-on-all-operations | `false` | Indicates retries should be attempted on operations other than {@link HttpMethod#GET}.
|spring.cloud.loadbalancer.retry.retryable-status-codes | | A {@link Set} of status codes that should trigger a retry.
|spring.cloud.loadbalancer.service-discovery.timeout | | String representation of Duration of the timeout for calls to service discovery.
|spring.cloud.loadbalancer.sticky-session.add-service-instance-cookie | `false` | Indicates whether a cookie with the newly selected instance should be added by SC LoadBalancer.
|spring.cloud.loadbalancer.sticky-session.instance-id-cookie-name | `sc-lb-instance-id` | The name of the cookie holding the preferred instance id.
|spring.cloud.loadbalancer.zone | | Spring Cloud LoadBalancer zone.
|spring.cloud.refresh.additional-property-sources-to-retain | | Additional property sources to retain during a refresh. Typically only system property sources are retained. This property allows property sources, such as property sources created by EnvironmentPostProcessors to be retained as well.
|spring.cloud.refresh.enabled | `true` | Enables autoconfiguration for the refresh scope and associated features.
|spring.cloud.refresh.extra-refreshable | `true` | Additional class names for beans to post process into refresh scope.
|spring.cloud.refresh.never-refreshable | `true` | Comma separated list of class names for beans to never be refreshed or rebound.
|spring.cloud.service-registry.auto-registration.enabled | `true` | Whether service auto-registration is enabled. Defaults to true.
|spring.cloud.service-registry.auto-registration.fail-fast | `false` | Whether startup fails if there is no AutoServiceRegistration. Defaults to false.
|spring.cloud.service-registry.auto-registration.register-management | `true` | Whether to register the management as a service. Defaults to true.
|spring.cloud.util.enabled | `true` | Enables creation of Spring Cloud utility beans.
|===

330
docs/src/main/asciidoc/ghpages.sh

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

1
docs/src/main/asciidoc/index.adoc

@ -1 +0,0 @@ @@ -1 +0,0 @@
spring-cloud-commons.adoc

8
docs/src/main/asciidoc/jce.adoc

@ -1,8 +0,0 @@ @@ -1,8 +0,0 @@
If you get an exception due to "Illegal key size" and you use Sun's JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files.
See the following links for more information:
* https://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html[Java 6 JCE]
* https://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html[Java 7 JCE]
* https://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html[Java 8 JCE]
Extract the files into the JDK/jre/lib/security folder for whichever version of JRE/JDK x64/x86 you use.

1359
docs/src/main/asciidoc/spring-cloud-commons.adoc

File diff suppressed because it is too large Load Diff

199
mvnw vendored

@ -8,7 +8,7 @@ @@ -8,7 +8,7 @@
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
@ -19,7 +19,7 @@ @@ -19,7 +19,7 @@
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
@ -54,38 +54,16 @@ case "`uname`" in @@ -54,38 +54,16 @@ case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
#
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
# for the new JDKs provided by Oracle.
#
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
#
# Oracle JDKs
#
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
#
# Apple JDKs
#
export JAVA_HOME=`/usr/libexec/java_home`
fi
;;
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
@ -130,13 +108,12 @@ if $cygwin ; then @@ -130,13 +108,12 @@ if $cygwin ; then
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
@ -184,27 +161,28 @@ fi @@ -184,27 +161,28 @@ fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
local basedir=$(pwd)
local wdir=$(pwd)
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
wdir=$(cd "$wdir/.."; pwd)
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
@ -216,9 +194,108 @@ concat_lines() { @@ -216,9 +194,108 @@ concat_lines() {
fi
}
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
@ -226,28 +303,8 @@ export MAVEN_CMD_LINE_ARGS @@ -226,28 +303,8 @@ export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
echo "Running version check"
VERSION=$( sed '\!<parent!,\!</parent!d' `dirname $0`/pom.xml | grep '<version' | head -1 | sed -e 's/.*<version>//' -e 's!</version>.*$!!' )
echo "The found version is [${VERSION}]"
if echo $VERSION | egrep -q 'M|RC'; then
echo Activating \"milestone\" profile for version=\"$VERSION\"
echo $MAVEN_ARGS | grep -q milestone || MAVEN_ARGS="$MAVEN_ARGS -Pmilestone"
else
echo Deactivating \"milestone\" profile for version=\"$VERSION\"
echo $MAVEN_ARGS | grep -q milestone && MAVEN_ARGS=$(echo $MAVEN_ARGS | sed -e 's/-Pmilestone//')
fi
if echo $VERSION | egrep -q 'RELEASE'; then
echo Activating \"central\" profile for version=\"$VERSION\"
echo $MAVEN_ARGS | grep -q milestone || MAVEN_ARGS="$MAVEN_ARGS -Pcentral"
else
echo Deactivating \"central\" profile for version=\"$VERSION\"
echo $MAVEN_ARGS | grep -q central && MAVEN_ARGS=$(echo $MAVEN_ARGS | sed -e 's/-Pcentral//')
fi
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} ${MAVEN_ARGS} "$@"
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

55
mvnw.cmd vendored

@ -7,7 +7,7 @@ @@ -7,7 +7,7 @@
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@ -18,7 +18,7 @@ @@ -18,7 +18,7 @@
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@ -26,7 +26,7 @@ @@ -26,7 +26,7 @@
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@ -35,7 +35,9 @@ @@ -35,7 +35,9 @@
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
@ -80,8 +82,6 @@ goto error @@ -80,8 +82,6 @@ goto error
:init
set MAVEN_CMD_LINE_ARGS=%*
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
@ -117,11 +117,48 @@ for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do s @@ -117,11 +117,48 @@ for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do s
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end

41
pom.xml

@ -5,7 +5,7 @@ @@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons-parent</artifactId>
<version>3.0.7-SNAPSHOT</version>
<version>4.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Spring Cloud Commons Parent</name>
<description>Spring Cloud Commons Parent</description>
@ -13,7 +13,7 @@ @@ -13,7 +13,7 @@
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-build</artifactId>
<version>3.0.5</version>
<version>4.1.0-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<scm>
@ -66,6 +66,23 @@ @@ -66,6 +66,23 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
<configuration>
<ignoredDependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>
</ignoredDependencies>
</configuration>
</plugin>
</plugins>
</build>
@ -93,7 +110,7 @@ @@ -93,7 +110,7 @@
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
@ -122,7 +139,7 @@ @@ -122,7 +139,7 @@
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
@ -130,7 +147,7 @@ @@ -130,7 +147,7 @@
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release-local</url>
<url>https://repo.spring.io/release</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
@ -152,11 +169,21 @@ @@ -152,11 +169,21 @@
<artifactId>spring-cloud-test-support</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<!--<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>${spring-security-oauth2-autoconfigure.version}</version>
</dependency>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</exclusion>
</exclusions>
</dependency>-->
</dependencies>
</dependencyManagement>
<modules>

19
spring-cloud-commons-dependencies/pom.xml

@ -6,16 +6,16 @@ @@ -6,16 +6,16 @@
<parent>
<artifactId>spring-cloud-dependencies-parent</artifactId>
<groupId>org.springframework.cloud</groupId>
<version>3.0.6-SNAPSHOT</version>
<version>4.1.0-SNAPSHOT</version>
<relativePath/>
</parent>
<artifactId>spring-cloud-commons-dependencies</artifactId>
<version>3.0.7-SNAPSHOT</version>
<version>4.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>spring-cloud-commons-dependencies</name>
<description>Spring Cloud Commons Dependencies</description>
<properties>
<spring-security-rsa.version>1.0.11.RELEASE</spring-security-rsa.version>
<spring-security-rsa.version>1.1.1</spring-security-rsa.version>
</properties>
<dependencyManagement>
<dependencies>
@ -64,6 +64,11 @@ @@ -64,6 +64,11 @@
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-test-support</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<profiles>
@ -73,7 +78,7 @@ @@ -73,7 +78,7 @@
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-snapshot-local</url>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
@ -84,7 +89,7 @@ @@ -84,7 +89,7 @@
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
@ -102,7 +107,7 @@ @@ -102,7 +107,7 @@
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-snapshot-local</url>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
@ -113,7 +118,7 @@ @@ -113,7 +118,7 @@
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone-local</url>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>

89
spring-cloud-commons/pom.xml

@ -7,7 +7,7 @@ @@ -7,7 +7,7 @@
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons-parent</artifactId>
<version>3.0.7-SNAPSHOT</version>
<version>4.1.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<artifactId>spring-cloud-commons</artifactId>
@ -33,6 +33,44 @@ @@ -33,6 +33,44 @@
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
<configuration>
<ignoredDependencies>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<version>1.73</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.64</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk18on</artifactId>
<version>1.73</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.64</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.1.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
</ignoredDependencies>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
@ -108,11 +146,25 @@ @@ -108,11 +146,25 @@
<artifactId>spring-boot-starter-hateoas</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<!--<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<optional>true</optional>
</dependency>
<exclusions>
<exclusion>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.activation</groupId>
<artifactId>jakarta.activation</artifactId>
</exclusion>
<exclusion>
<groupId>javax.activation</groupId>
<artifactId>javax.activation-api</artifactId>
</exclusion>
</exclusions>
</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
@ -132,6 +184,10 @@ @@ -132,6 +184,10 @@
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
@ -140,18 +196,8 @@ @@ -140,18 +196,8 @@
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>logging-interceptor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<optional>true</optional>
</dependency>
<dependency>
@ -160,13 +206,13 @@ @@ -160,13 +206,13 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-test-support</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-test-support</artifactId>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@ -174,5 +220,10 @@ @@ -174,5 +220,10 @@
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-observation-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

3
spring-cloud-commons/src/main/java/org/springframework/cloud/client/CommonsClientAutoConfiguration.java

@ -46,6 +46,7 @@ import org.springframework.context.annotation.Configuration; @@ -46,6 +46,7 @@ import org.springframework.context.annotation.Configuration;
* @author Spencer Gibb
* @author Olga Maciaszek-Sharma
* @author Tim Ysewyn
* @author Omer Naci Soydemir
*/
@Configuration(proxyBeanMethods = false)
public class CommonsClientAutoConfiguration {
@ -75,7 +76,7 @@ public class CommonsClientAutoConfiguration { @@ -75,7 +76,7 @@ public class CommonsClientAutoConfiguration {
}
@Bean
public HasFeatures commonsFeatures() {
public HasFeatures springCloudCommonsFeatures() {
return HasFeatures.abstractFeatures(DiscoveryClient.class, LoadBalancerClient.class);
}

14
spring-cloud-commons/src/main/java/org/springframework/cloud/client/DefaultServiceInstance.java

@ -27,6 +27,7 @@ import java.util.Objects; @@ -27,6 +27,7 @@ import java.util.Objects;
* @author Spencer Gibb
* @author Tim Ysewyn
* @author Charu Covindane
* @author Neil Powell
*/
public class DefaultServiceInstance implements ServiceInstance {
@ -79,11 +80,16 @@ public class DefaultServiceInstance implements ServiceInstance { @@ -79,11 +80,16 @@ public class DefaultServiceInstance implements ServiceInstance {
/**
* Creates a URI from the given ServiceInstance's host:port.
* @param instance the ServiceInstance.
* @return URI of the form (secure)?https:http + "host:port".
* @return URI of the form (secure)?https:http + "host:port". Scheme port default used
* if port not set.
*/
public static URI getUri(ServiceInstance instance) {
String scheme = (instance.isSecure()) ? "https" : "http";
String uri = String.format("%s://%s:%s", scheme, instance.getHost(), instance.getPort());
int port = instance.getPort();
if (port <= 0) {
port = (instance.isSecure()) ? 443 : 80;
}
String uri = String.format("%s://%s:%s", scheme, instance.getHost(), port);
return URI.create(uri);
}
@ -138,6 +144,10 @@ public class DefaultServiceInstance implements ServiceInstance { @@ -138,6 +144,10 @@ public class DefaultServiceInstance implements ServiceInstance {
this.port = port;
}
public void setSecure(boolean secure) {
this.secure = secure;
}
public void setUri(URI uri) {
this.uri = uri;
this.host = this.uri.getHost();

5
spring-cloud-commons/src/main/java/org/springframework/cloud/client/HostInfoEnvironmentPostProcessor.java

@ -19,7 +19,6 @@ package org.springframework.cloud.client; @@ -19,7 +19,6 @@ package org.springframework.cloud.client;
import java.util.LinkedHashMap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.config.ConfigFileApplicationListener;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
@ -36,8 +35,8 @@ import org.springframework.core.env.MapPropertySource; @@ -36,8 +35,8 @@ import org.springframework.core.env.MapPropertySource;
*/
public class HostInfoEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
// Before ConfigFileApplicationListener
private int order = ConfigFileApplicationListener.DEFAULT_ORDER - 1;
// Before BootstrapConfigFileApplicationListener
private int order = Ordered.HIGHEST_PRECEDENCE + 9;
@Override
public int getOrder() {

46
spring-cloud-commons/src/main/java/org/springframework/cloud/client/SpringCloudApplication.java

@ -1,46 +0,0 @@ @@ -1,46 +0,0 @@
/*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author Spencer Gibb
* @deprecated This annotation has been deprecated as of the 3.0.1 release.
* <code>@EnableDiscoveryClient</code> is no longer needed, discovery client
* implementations are enabled as long as an implementation is on the classpath.
* <code>@EnableCircuitBreaker</code> is no longer used now that Hystrix has been removed
* from Spring Cloud.
*/
@Deprecated
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootApplication
@EnableDiscoveryClient
public @interface SpringCloudApplication {
}

9
spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/FeaturesEndpoint.java

@ -18,6 +18,7 @@ package org.springframework.cloud.client.actuator; @@ -18,6 +18,7 @@ package org.springframework.cloud.client.actuator;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
@ -152,16 +153,16 @@ public class FeaturesEndpoint implements ApplicationContextAware { @@ -152,16 +153,16 @@ public class FeaturesEndpoint implements ApplicationContextAware {
Feature feature = (Feature) o;
if (this.type != null ? !this.type.equals(feature.type) : feature.type != null) {
if (!Objects.equals(this.type, feature.type)) {
return false;
}
if (this.name != null ? !this.name.equals(feature.name) : feature.name != null) {
if (!Objects.equals(this.name, feature.name)) {
return false;
}
if (this.version != null ? !this.version.equals(feature.version) : feature.version != null) {
if (!Objects.equals(this.version, feature.version)) {
return false;
}
return this.vendor != null ? this.vendor.equals(feature.vendor) : feature.vendor == null;
return Objects.equals(this.vendor, feature.vendor);
}
@Override

4
spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/HasFeatures.java

@ -36,11 +36,11 @@ public class HasFeatures { @@ -36,11 +36,11 @@ public class HasFeatures {
}
public static HasFeatures abstractFeatures(Class<?>... abstractFeatures) {
return new HasFeatures(Arrays.asList(abstractFeatures), Collections.<NamedFeature>emptyList());
return new HasFeatures(Arrays.asList(abstractFeatures), Collections.emptyList());
}
public static HasFeatures namedFeatures(NamedFeature... namedFeatures) {
return new HasFeatures(Collections.<Class<?>>emptyList(), Arrays.asList(namedFeatures));
return new HasFeatures(Collections.emptyList(), Arrays.asList(namedFeatures));
}
public static HasFeatures namedFeature(String name, Class<?> type) {

2
spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/CircuitBreaker.java

@ -30,7 +30,7 @@ public interface CircuitBreaker { @@ -30,7 +30,7 @@ public interface CircuitBreaker {
return run(toRun, throwable -> {
throw new NoFallbackAvailableException("No fallback available.", throwable);
});
};
}
<T> T run(Supplier<T> toRun, Function<Throwable, T> fallback);

43
spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/EnableCircuitBreaker.java

@ -1,43 +0,0 @@ @@ -1,43 +0,0 @@
/*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.circuitbreaker;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
/**
* Annotation to enable a CircuitBreaker implementation.
* https://martinfowler.com/bliki/CircuitBreaker.html
* @deprecated as of the 3.0.1 release. Hystrix has been removed from Spring Cloud Netflix
* and it was the only implementation using this annotation.
* @author Spencer Gibb
*/
@Deprecated
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(EnableCircuitBreakerImportSelector.class)
public @interface EnableCircuitBreaker {
}

36
spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/EnableCircuitBreakerImportSelector.java

@ -1,36 +0,0 @@ @@ -1,36 +0,0 @@
/*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.circuitbreaker;
import org.springframework.cloud.commons.util.SpringFactoryImportSelector;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
/**
* Imports a single circuit breaker implementation configuration.
*
* @author Spencer Gibb
*/
@Order(Ordered.LOWEST_PRECEDENCE - 100)
public class EnableCircuitBreakerImportSelector extends SpringFactoryImportSelector<EnableCircuitBreaker> {
@Override
protected boolean isEnabled() {
return getEnvironment().getProperty("spring.cloud.circuit.breaker.enabled", Boolean.class, Boolean.TRUE);
}
}

64
spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/CircuitBreakerObservationContext.java

@ -0,0 +1,64 @@ @@ -0,0 +1,64 @@
/*
* Copyright 2018-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.circuitbreaker.observation;
import io.micrometer.observation.Observation;
/**
* Circuit Breaker {@link Observation.Context}.
*
* @author Marcin Grzejszczak
* @since 4.0.0
*/
public class CircuitBreakerObservationContext extends Observation.Context {
private final Type type;
/**
* Creates a new instance of {@link CircuitBreakerObservationDocumentation}.
* @param type type of wrapped object
*/
public CircuitBreakerObservationContext(Type type) {
this.type = type;
}
/**
* Gets the wrapped object type.
* @return type of wrapped object
*/
public Type getType() {
return type;
}
/**
* Describes the type of wrapped object.
*/
public enum Type {
/**
* Fallback function.
*/
FUNCTION,
/**
* Operation to run.
*/
SUPPLIER
}
}

35
spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/CircuitBreakerObservationConvention.java

@ -0,0 +1,35 @@ @@ -0,0 +1,35 @@
/*
* Copyright 2018-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.circuitbreaker.observation;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationConvention;
/**
* {@link ObservationConvention} for {@link CircuitBreakerObservationContext}.
*
* @author Marcin Grzejszczak
* @since 4.0.0
*/
public interface CircuitBreakerObservationConvention extends ObservationConvention<CircuitBreakerObservationContext> {
@Override
default boolean supportsContext(Observation.Context context) {
return context instanceof CircuitBreakerObservationContext;
}
}

83
spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/CircuitBreakerObservationDocumentation.java

@ -0,0 +1,83 @@ @@ -0,0 +1,83 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.circuitbreaker.observation;
import io.micrometer.common.docs.KeyName;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationConvention;
import io.micrometer.observation.docs.ObservationDocumentation;
enum CircuitBreakerObservationDocumentation implements ObservationDocumentation {
/**
* Observation created when we wrap a Supplier passed to the CircuitBreaker.
*/
CIRCUIT_BREAKER_SUPPLIER_OBSERVATION {
@Override
public Class<? extends ObservationConvention<? extends Observation.Context>> getDefaultConvention() {
return DefaultCircuitBreakerObservationConvention.class;
}
@Override
public KeyName[] getLowCardinalityKeyNames() {
return LowCardinalityTags.values();
}
@Override
public String getPrefix() {
return "spring.cloud.circuitbreaker";
}
},
/**
* Observation created when we wrap a Function passed to the CircuitBreaker as
* fallback.
*/
CIRCUIT_BREAKER_FUNCTION_OBSERVATION {
@Override
public Class<? extends ObservationConvention<? extends Observation.Context>> getDefaultConvention() {
return DefaultCircuitBreakerObservationConvention.class;
}
@Override
public KeyName[] getLowCardinalityKeyNames() {
return LowCardinalityTags.values();
}
@Override
public String getPrefix() {
return "spring.cloud.circuitbreaker";
}
};
public enum LowCardinalityTags implements KeyName {
/**
* Defines the type of wrapped lambda.
*/
OBJECT_TYPE {
@Override
public String asString() {
return "spring.cloud.circuitbreaker.type";
}
}
}
}

55
spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/DefaultCircuitBreakerObservationConvention.java

@ -0,0 +1,55 @@ @@ -0,0 +1,55 @@
/*
* Copyright 2018-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.circuitbreaker.observation;
import java.util.Locale;
import io.micrometer.common.KeyValues;
/**
* Default implementation of {@link CircuitBreakerObservationContext}.
*
* @author Marcin Grzejszczak
* @since 4.0.0
*/
public class DefaultCircuitBreakerObservationConvention implements CircuitBreakerObservationConvention {
/**
* Don't know why this needs to be public.
*/
public static final DefaultCircuitBreakerObservationConvention INSTANCE = new DefaultCircuitBreakerObservationConvention();
@Override
public KeyValues getLowCardinalityKeyValues(CircuitBreakerObservationContext context) {
return KeyValues.of(CircuitBreakerObservationDocumentation.LowCardinalityTags.OBJECT_TYPE
.withValue(context.getType().name().toLowerCase(Locale.ROOT)));
}
@Override
public String getName() {
return "spring.cloud.circuitbreaker";
}
@Override
public String getContextualName(CircuitBreakerObservationContext context) {
if (context.getType() == CircuitBreakerObservationContext.Type.SUPPLIER) {
return "circuit-breaker";
}
return "circuit-breaker fallback";
}
}

67
spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/ObservedCircuitBreaker.java

@ -0,0 +1,67 @@ @@ -0,0 +1,67 @@
/*
* Copyright 2018-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.circuitbreaker.observation;
import java.util.function.Function;
import java.util.function.Supplier;
import io.micrometer.observation.ObservationRegistry;
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
/**
* Observed Circuit Breaker.
*
* @author Marcin Grzejszczak
* @since 4.0.0
*/
public class ObservedCircuitBreaker implements CircuitBreaker {
private final CircuitBreaker delegate;
private final ObservationRegistry observationRegistry;
private CircuitBreakerObservationConvention customConvention;
public ObservedCircuitBreaker(CircuitBreaker delegate, ObservationRegistry observationRegistry) {
this.delegate = delegate;
this.observationRegistry = observationRegistry;
}
@Override
public <T> T run(Supplier<T> toRun, Function<Throwable, T> fallback) {
return this.delegate.run(
new ObservedSupplier<>(this.customConvention,
new CircuitBreakerObservationContext(CircuitBreakerObservationContext.Type.SUPPLIER),
"circuit-breaker", this.observationRegistry, toRun),
new ObservedFunction<>(this.customConvention,
new CircuitBreakerObservationContext(CircuitBreakerObservationContext.Type.FUNCTION),
"circuit-breaker fallback", this.observationRegistry, fallback));
}
@Override
public <T> T run(Supplier<T> toRun) {
return this.delegate.run(new ObservedSupplier<>(this.customConvention,
new CircuitBreakerObservationContext(CircuitBreakerObservationContext.Type.SUPPLIER), "circuit-breaker",
this.observationRegistry, toRun));
}
public void setCustomConvention(CircuitBreakerObservationConvention customConvention) {
this.customConvention = customConvention;
}
}

51
spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/ObservedFunction.java

@ -0,0 +1,51 @@ @@ -0,0 +1,51 @@
/*
* Copyright 2018-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.circuitbreaker.observation;
import java.util.function.Function;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationRegistry;
/**
* Observed {@link Function}.
*
* @param <T> type returned by the fallback
* @since 4.0.0
*/
class ObservedFunction<T> implements Function<Throwable, T> {
private final Function<Throwable, T> delegate;
private final Observation observation;
ObservedFunction(CircuitBreakerObservationConvention customConvention, CircuitBreakerObservationContext context,
String conextualName, ObservationRegistry observationRegistry, Function<Throwable, T> toRun) {
this.delegate = toRun;
this.observation = CircuitBreakerObservationDocumentation.CIRCUIT_BREAKER_SUPPLIER_OBSERVATION
.observation(customConvention, DefaultCircuitBreakerObservationConvention.INSTANCE, () -> context,
observationRegistry)
.parentObservation(observationRegistry.getCurrentObservation());
this.observation.contextualName(conextualName);
}
@Override
public T apply(Throwable throwable) {
return this.observation.observe(() -> this.delegate.apply(throwable));
}
}

51
spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/ObservedSupplier.java

@ -0,0 +1,51 @@ @@ -0,0 +1,51 @@
/*
* Copyright 2018-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.circuitbreaker.observation;
import java.util.function.Supplier;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationRegistry;
/**
* Observed {@link Supplier}.
*
* @param <T> type returned by the supplier
* @since 4.0.0
*/
class ObservedSupplier<T> implements Supplier<T> {
private final Supplier<T> delegate;
private final Observation observation;
ObservedSupplier(CircuitBreakerObservationConvention customConvention, CircuitBreakerObservationContext context,
String contextualName, ObservationRegistry observationRegistry, Supplier<T> toRun) {
this.delegate = toRun;
this.observation = CircuitBreakerObservationDocumentation.CIRCUIT_BREAKER_SUPPLIER_OBSERVATION
.observation(customConvention, DefaultCircuitBreakerObservationConvention.INSTANCE, () -> context,
observationRegistry)
.parentObservation(observationRegistry.getCurrentObservation());
this.observation.contextualName(contextualName);
}
@Override
public T get() {
return this.observation.observe(this.delegate);
}
}

3
spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelector.java

@ -52,8 +52,7 @@ public class EnableDiscoveryClientImportSelector extends SpringFactoryImportSele @@ -52,8 +52,7 @@ public class EnableDiscoveryClientImportSelector extends SpringFactoryImportSele
}
else {
Environment env = getEnvironment();
if (ConfigurableEnvironment.class.isInstance(env)) {
ConfigurableEnvironment configEnv = (ConfigurableEnvironment) env;
if (env instanceof ConfigurableEnvironment configEnv) {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
map.put("spring.cloud.service-registry.auto-registration.enabled", false);
MapPropertySource propertySource = new MapPropertySource("springCloudDiscoveryClient", map);

30
spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/ReactiveDiscoveryClient.java

@ -16,7 +16,10 @@ @@ -16,7 +16,10 @@
package org.springframework.cloud.client.discovery;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.core.Ordered;
@ -26,9 +29,12 @@ import org.springframework.core.Ordered; @@ -26,9 +29,12 @@ import org.springframework.core.Ordered;
* Eureka or consul.io.
*
* @author Tim Ysewyn
* @author Olga Maciaszek-Sharma
*/
public interface ReactiveDiscoveryClient extends Ordered {
Log LOG = LogFactory.getLog(ReactiveDiscoveryClient.class);
/**
* Default order of the discovery client.
*/
@ -60,11 +66,35 @@ public interface ReactiveDiscoveryClient extends Ordered { @@ -60,11 +66,35 @@ public interface ReactiveDiscoveryClient extends Ordered {
* <p>
* The default implementation simply calls {@link #getServices()} - client
* implementations can override with a lighter weight operation if they choose to.
* @deprecated in favour of {@link ReactiveDiscoveryClient#reactiveProbe()}. This
* method should not be used as is, as it contains a bug - the method called within
* returns a {@link Flux}, which is not accessible for subscription or blocking from
* within. We are leaving it with a deprecation in order not to bring downstream
* implementations.
*/
@Deprecated
default void probe() {
if (LOG.isWarnEnabled()) {
LOG.warn("ReactiveDiscoveryClient#probe has been called. If you're calling this method directly, "
+ "use ReactiveDiscoveryClient#reactiveProbe instead.");
}
getServices();
}
/**
* Can be used to verify the client is still valid and able to make calls.
* <p>
* A successful invocation with no exception thrown implies the client is able to make
* calls.
* <p>
* The default implementation simply calls {@link #getServices()} and wraps it with a
* {@link Mono} - client implementations can override with a lighter weight operation
* if they choose to.
*/
default Mono<Void> reactiveProbe() {
return getServices().then();
}
/**
* Default implementation for getting order of discovery clients.
* @return order

12
spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClient.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -31,6 +31,7 @@ import org.springframework.core.annotation.AnnotationAwareOrderComparator; @@ -31,6 +31,7 @@ import org.springframework.core.annotation.AnnotationAwareOrderComparator;
*
* @author Biju Kunjummen
* @author Olga Maciaszek-Sharma
* @author Sean Ruffatti
*/
public class CompositeDiscoveryClient implements DiscoveryClient {
@ -73,6 +74,15 @@ public class CompositeDiscoveryClient implements DiscoveryClient { @@ -73,6 +74,15 @@ public class CompositeDiscoveryClient implements DiscoveryClient {
return new ArrayList<>(services);
}
@Override
public void probe() {
if (this.discoveryClients != null) {
for (DiscoveryClient discoveryClient : this.discoveryClients) {
discoveryClient.probe();
}
}
}
public List<DiscoveryClient> getDiscoveryClients() {
return this.discoveryClients;
}

2
spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/InstanceRegisteredEvent.java

@ -22,8 +22,8 @@ import org.springframework.context.ApplicationEvent; @@ -22,8 +22,8 @@ import org.springframework.context.ApplicationEvent;
* Event to be published after the local service instance registers itself with a
* discovery service.
*
* @author Spencer Gibb
* @param <T> - type of configuration
* @author Spencer Gibb
*/
@SuppressWarnings("serial")
public class InstanceRegisteredEvent<T> extends ApplicationEvent {

8
spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorProperties.java

@ -63,12 +63,8 @@ public class DiscoveryClientHealthIndicatorProperties { @@ -63,12 +63,8 @@ public class DiscoveryClientHealthIndicatorProperties {
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("DiscoveryClientHealthIndicatorProperties{");
sb.append("enabled=").append(this.enabled);
sb.append(", includeDescription=").append(this.includeDescription);
sb.append(", useServicesQuery=").append(this.useServicesQuery);
sb.append('}');
return sb.toString();
return "DiscoveryClientHealthIndicatorProperties{" + "enabled=" + this.enabled + ", includeDescription="
+ this.includeDescription + ", useServicesQuery=" + this.useServicesQuery + '}';
}
}

2
spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthContributor.java

@ -57,7 +57,7 @@ public class DiscoveryCompositeHealthContributor implements CompositeHealthContr @@ -57,7 +57,7 @@ public class DiscoveryCompositeHealthContributor implements CompositeHealthContr
}
private NamedContributor<HealthContributor> asNamedContributor(DiscoveryHealthIndicator indicator) {
return new NamedContributor<HealthContributor>() {
return new NamedContributor<>() {
@Override
public String getName() {

49
spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/reactive/ReactiveDiscoveryClientHealthIndicator.java

@ -33,21 +33,21 @@ import org.springframework.core.Ordered; @@ -33,21 +33,21 @@ import org.springframework.core.Ordered;
import static java.util.Collections.emptyList;
/**
* A health indicator which indicates whether or not the discovery client has been
* initialized.
* A health indicator which indicates whether the discovery client has been initialized.
*
* @author Tim Ysewyn
* @author Chris Bono
* @author Olga Maciaszek-Sharma
*/
public class ReactiveDiscoveryClientHealthIndicator
implements ReactiveDiscoveryHealthIndicator, Ordered, ApplicationListener<InstanceRegisteredEvent<?>> {
private static final Log LOG = LogFactory.getLog(ReactiveDiscoveryClientHealthIndicator.class);
private final ReactiveDiscoveryClient discoveryClient;
private final DiscoveryClientHealthIndicatorProperties properties;
private final Log log = LogFactory.getLog(ReactiveDiscoveryClientHealthIndicator.class);
private AtomicBoolean discoveryInitialized = new AtomicBoolean(false);
private int order = Ordered.HIGHEST_PRECEDENCE;
@ -60,14 +60,14 @@ public class ReactiveDiscoveryClientHealthIndicator @@ -60,14 +60,14 @@ public class ReactiveDiscoveryClientHealthIndicator
@Override
public void onApplicationEvent(InstanceRegisteredEvent<?> event) {
if (this.discoveryInitialized.compareAndSet(false, true)) {
this.log.debug("Discovery Client has been initialized");
if (discoveryInitialized.compareAndSet(false, true)) {
LOG.debug("Discovery Client has been initialized");
}
}
@Override
public Mono<Health> health() {
if (this.discoveryInitialized.get()) {
if (discoveryInitialized.get()) {
return doHealthCheck();
}
else {
@ -78,38 +78,39 @@ public class ReactiveDiscoveryClientHealthIndicator @@ -78,38 +78,39 @@ public class ReactiveDiscoveryClientHealthIndicator
private Mono<Health> doHealthCheck() {
// @formatter:off
return Mono.just(this.properties.isUseServicesQuery())
return Mono.just(properties.isUseServicesQuery())
.flatMap(useServices -> useServices ? doHealthCheckWithServices() : doHealthCheckWithProbe())
.onErrorResume(exception -> {
this.log.error("Error", exception);
if (LOG.isErrorEnabled()) {
LOG.error("Error", exception);
}
return Mono.just(Health.down().withException(exception).build());
});
// @formatter:on
}
private Mono<Health> doHealthCheckWithProbe() {
// @formatter:off
return Mono.justOrEmpty(this.discoveryClient)
.flatMap(client -> {
client.probe();
return Mono.just(client);
})
.map(client -> {
String description = (this.properties.isIncludeDescription()) ? client.description() : "";
return Health.status(new Status("UP", description)).build();
});
// @formatter:on
return discoveryClient.reactiveProbe().doOnError(exception -> {
if (LOG.isErrorEnabled()) {
LOG.error("Probe has failed.", exception);
}
}).then(buildHealthUp(discoveryClient));
}
private Mono<Health> buildHealthUp(ReactiveDiscoveryClient discoveryClient) {
String description = (properties.isIncludeDescription()) ? discoveryClient.description() : "";
return Mono.just(Health.status(new Status("UP", description)).build());
}
private Mono<Health> doHealthCheckWithServices() {
// @formatter:off
return Mono.justOrEmpty(this.discoveryClient)
return Mono.justOrEmpty(discoveryClient)
.flatMapMany(ReactiveDiscoveryClient::getServices)
.collectList()
.defaultIfEmpty(emptyList())
.map(services -> {
String description = (this.properties.isIncludeDescription()) ?
this.discoveryClient.description() : "";
String description = (properties.isIncludeDescription()) ?
discoveryClient.description() : "";
return Health.status(new Status("UP", description))
.withDetail("services", services).build();
});
@ -123,7 +124,7 @@ public class ReactiveDiscoveryClientHealthIndicator @@ -123,7 +124,7 @@ public class ReactiveDiscoveryClientHealthIndicator
@Override
public int getOrder() {
return this.order;
return order;
}
public void setOrder(int order) {

2
spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/reactive/ReactiveDiscoveryCompositeHealthContributor.java

@ -54,7 +54,7 @@ public class ReactiveDiscoveryCompositeHealthContributor implements CompositeRea @@ -54,7 +54,7 @@ public class ReactiveDiscoveryCompositeHealthContributor implements CompositeRea
}
private NamedContributor<ReactiveHealthContributor> asNamedContributor(ReactiveDiscoveryHealthIndicator indicator) {
return new NamedContributor<ReactiveHealthContributor>() {
return new NamedContributor<>() {
@Override
public String getName() {

11
spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryProperties.java

@ -20,9 +20,9 @@ import java.util.HashMap; @@ -20,9 +20,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
@ -40,7 +40,7 @@ import org.springframework.cloud.client.discovery.DiscoveryClient; @@ -40,7 +40,7 @@ import org.springframework.cloud.client.discovery.DiscoveryClient;
*/
@ConfigurationProperties(prefix = "spring.cloud.discovery.client.simple")
public class SimpleDiscoveryProperties {
public class SimpleDiscoveryProperties implements InitializingBean {
private Map<String, List<DefaultServiceInstance>> instances = new HashMap<>();
@ -49,6 +49,7 @@ public class SimpleDiscoveryProperties { @@ -49,6 +49,7 @@ public class SimpleDiscoveryProperties {
* properties explicitly if they are exporting data (e.g. metrics) that need to be
* identified by the service instance.
*/
@NestedConfigurationProperty
private DefaultServiceInstance local = new DefaultServiceInstance(null, null, null, 0, false);
private int order = DiscoveryClient.DEFAULT_ORDER;
@ -73,8 +74,8 @@ public class SimpleDiscoveryProperties { @@ -73,8 +74,8 @@ public class SimpleDiscoveryProperties {
this.order = order;
}
@PostConstruct
public void init() {
@Override
public void afterPropertiesSet() {
for (String key : this.instances.keySet()) {
for (DefaultServiceInstance instance : this.instances.get(key)) {
instance.setServiceId(key);

9
spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/reactive/SimpleReactiveDiscoveryProperties.java

@ -20,10 +20,9 @@ import java.util.HashMap; @@ -20,10 +20,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import reactor.core.publisher.Flux;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
@ -43,7 +42,7 @@ import static java.util.Collections.emptyList; @@ -43,7 +42,7 @@ import static java.util.Collections.emptyList;
* @since 2.2.0
*/
@ConfigurationProperties(prefix = "spring.cloud.discovery.client.simple")
public class SimpleReactiveDiscoveryProperties {
public class SimpleReactiveDiscoveryProperties implements InitializingBean {
private Map<String, List<DefaultServiceInstance>> instances = new HashMap<>();
@ -80,8 +79,8 @@ public class SimpleReactiveDiscoveryProperties { @@ -80,8 +79,8 @@ public class SimpleReactiveDiscoveryProperties {
this.order = order;
}
@PostConstruct
public void init() {
@Override
public void afterPropertiesSet() {
for (String key : this.instances.keySet()) {
for (DefaultServiceInstance instance : this.instances.get(key)) {
instance.setServiceId(key);

10
spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResourceRefresher.java

@ -16,6 +16,7 @@ @@ -16,6 +16,7 @@
package org.springframework.cloud.client.hypermedia;
import java.time.Duration;
import java.util.List;
import org.springframework.scheduling.config.ContextLifecycleScheduledTaskRegistrar;
@ -52,13 +53,8 @@ public class RemoteResourceRefresher extends ContextLifecycleScheduledTaskRegist @@ -52,13 +53,8 @@ public class RemoteResourceRefresher extends ContextLifecycleScheduledTaskRegist
public void afterPropertiesSet() {
for (final RemoteResource resource : this.discoveredResources) {
addFixedDelayTask(new IntervalTask(new Runnable() {
@Override
public void run() {
resource.verifyOrDiscover();
}
}, this.fixedDelay, this.initialDelay));
addFixedDelayTask(new IntervalTask(resource::verifyOrDiscover, Duration.ofMillis(fixedDelay),
Duration.ofMillis(initialDelay)));
}
super.afterPropertiesSet();

83
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerAutoConfiguration.java

@ -1,83 +0,0 @@ @@ -1,83 +0,0 @@
/*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.AsyncClientHttpRequestInterceptor;
import org.springframework.web.client.AsyncRestTemplate;
/**
* Auto-configuration for blocking client-side load balancing.
*
* @author Rob Worsnop
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(LoadBalancerClient.class)
@ConditionalOnClass(AsyncRestTemplate.class)
public class AsyncLoadBalancerAutoConfiguration {
@Configuration(proxyBeanMethods = false)
static class AsyncRestTemplateCustomizerConfig {
@LoadBalanced
@Autowired(required = false)
private List<AsyncRestTemplate> restTemplates = Collections.emptyList();
@Bean
public SmartInitializingSingleton loadBalancedAsyncRestTemplateInitializer(
final List<AsyncRestTemplateCustomizer> customizers) {
return () -> {
for (AsyncRestTemplate restTemplate : AsyncRestTemplateCustomizerConfig.this.restTemplates) {
for (AsyncRestTemplateCustomizer customizer : customizers) {
customizer.customize(restTemplate);
}
}
};
}
}
@Configuration(proxyBeanMethods = false)
static class LoadBalancerInterceptorConfig {
@Bean
public AsyncLoadBalancerInterceptor asyncLoadBalancerInterceptor(LoadBalancerClient loadBalancerClient) {
return new AsyncLoadBalancerInterceptor(loadBalancerClient);
}
@Bean
public AsyncRestTemplateCustomizer asyncRestTemplateCustomizer(
final AsyncLoadBalancerInterceptor loadBalancerInterceptor) {
return restTemplate -> {
List<AsyncClientHttpRequestInterceptor> list = new ArrayList<>(restTemplate.getInterceptors());
list.add(loadBalancerInterceptor);
restTemplate.setInterceptors(list);
};
}
}
}

49
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerInterceptor.java

@ -1,49 +0,0 @@ @@ -1,49 +0,0 @@
/*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import java.io.IOException;
import java.net.URI;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.AsyncClientHttpRequestExecution;
import org.springframework.http.client.AsyncClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.concurrent.ListenableFuture;
/**
* @author Rob Worsnop
* @author Olga Maciaszek-Sharma
*/
public class AsyncLoadBalancerInterceptor implements AsyncClientHttpRequestInterceptor {
private LoadBalancerClient loadBalancer;
public AsyncLoadBalancerInterceptor(LoadBalancerClient loadBalancer) {
this.loadBalancer = loadBalancer;
}
@Override
public ListenableFuture<ClientHttpResponse> intercept(final HttpRequest request, final byte[] body,
final AsyncClientHttpRequestExecution execution) throws IOException {
final URI originalUri = request.getURI();
String serviceName = originalUri.getHost();
return loadBalancer.execute(serviceName, new AsyncLoadBalancerRequest(loadBalancer,
new AsyncLoadBalancerRequest.ClientHttpRequestData(request, body, execution)));
}
}

69
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerRequest.java

@ -1,69 +0,0 @@ @@ -1,69 +0,0 @@
/*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.AsyncClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.concurrent.ListenableFuture;
/**
* Default {@link LoadBalancerRequest} implementation for async use-cases.
*
* @author Olga Maciaszek-Sharma
* @since 3.1.2
*/
class AsyncLoadBalancerRequest implements HttpRequestLoadBalancerRequest<ListenableFuture<ClientHttpResponse>> {
private final LoadBalancerClient loadBalancer;
private final ClientHttpRequestData clientHttpRequestData;
AsyncLoadBalancerRequest(LoadBalancerClient loadBalancer, ClientHttpRequestData clientHttpRequestData) {
this.loadBalancer = loadBalancer;
this.clientHttpRequestData = clientHttpRequestData;
}
@Override
public ListenableFuture<ClientHttpResponse> apply(ServiceInstance instance) throws Exception {
HttpRequest serviceRequest = new ServiceRequestWrapper(clientHttpRequestData.request, instance, loadBalancer);
return clientHttpRequestData.execution.executeAsync(serviceRequest, clientHttpRequestData.body);
}
@Override
public HttpRequest getHttpRequest() {
return clientHttpRequestData.request;
}
static class ClientHttpRequestData {
private final HttpRequest request;
private final byte[] body;
private final AsyncClientHttpRequestExecution execution;
ClientHttpRequestData(HttpRequest request, byte[] body, AsyncClientHttpRequestExecution execution) {
this.request = request;
this.body = body;
this.execution = execution;
}
}
}

6
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeException.java

@ -43,7 +43,7 @@ public class ClientHttpResponseStatusCodeException extends RetryableStatusCodeEx @@ -43,7 +43,7 @@ public class ClientHttpResponseStatusCodeException extends RetryableStatusCodeEx
*/
public ClientHttpResponseStatusCodeException(String serviceId, ClientHttpResponse response, byte[] body)
throws IOException {
super(serviceId, response.getRawStatusCode(), response, null);
super(serviceId, response.getStatusCode().value(), response, null);
this.response = new ClientHttpResponseWrapper(response, body);
}
@ -65,7 +65,7 @@ public class ClientHttpResponseStatusCodeException extends RetryableStatusCodeEx @@ -65,7 +65,7 @@ public class ClientHttpResponseStatusCodeException extends RetryableStatusCodeEx
@Override
public int getRawStatusCode() throws IOException {
return this.response.getRawStatusCode();
return this.response.getStatusCode().value();
}
@Override
@ -79,7 +79,7 @@ public class ClientHttpResponseStatusCodeException extends RetryableStatusCodeEx @@ -79,7 +79,7 @@ public class ClientHttpResponseStatusCodeException extends RetryableStatusCodeEx
}
@Override
public InputStream getBody() throws IOException {
public InputStream getBody() {
return new ByteArrayInputStream(this.body);
}

3
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultRequest.java

@ -59,10 +59,9 @@ public class DefaultRequest<T> implements Request<T> { @@ -59,10 +59,9 @@ public class DefaultRequest<T> implements Request<T> {
if (this == o) {
return true;
}
if (!(o instanceof DefaultRequest)) {
if (!(o instanceof DefaultRequest<?> that)) {
return false;
}
DefaultRequest<?> that = (DefaultRequest<?>) o;
return Objects.equals(context, that.context);
}

3
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultRequestContext.java

@ -62,10 +62,9 @@ public class DefaultRequestContext extends HintRequestContext { @@ -62,10 +62,9 @@ public class DefaultRequestContext extends HintRequestContext {
if (this == o) {
return true;
}
if (!(o instanceof DefaultRequestContext)) {
if (!(o instanceof DefaultRequestContext that)) {
return false;
}
DefaultRequestContext that = (DefaultRequestContext) o;
return Objects.equals(clientRequest, that.clientRequest);
}

3
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultResponse.java

@ -55,10 +55,9 @@ public class DefaultResponse implements Response<ServiceInstance> { @@ -55,10 +55,9 @@ public class DefaultResponse implements Response<ServiceInstance> {
if (this == o) {
return true;
}
if (!(o instanceof DefaultResponse)) {
if (!(o instanceof DefaultResponse that)) {
return false;
}
DefaultResponse that = (DefaultResponse) o;
return Objects.equals(serviceInstance, that.serviceInstance);
}

3
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/HintRequestContext.java

@ -72,10 +72,9 @@ public class HintRequestContext implements TimedRequestContext { @@ -72,10 +72,9 @@ public class HintRequestContext implements TimedRequestContext {
if (this == o) {
return true;
}
if (!(o instanceof HintRequestContext)) {
if (!(o instanceof HintRequestContext that)) {
return false;
}
HintRequestContext that = (HintRequestContext) o;
return Objects.equals(hint, that.hint);
}

3
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/InterceptorRetryPolicy.java

@ -54,6 +54,9 @@ public class InterceptorRetryPolicy implements RetryPolicy { @@ -54,6 +54,9 @@ public class InterceptorRetryPolicy implements RetryPolicy {
@Override
public boolean canRetry(RetryContext context) {
if (!policy.retryableException(context.getLastThrowable())) {
return false;
}
LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context;
if (lbContext.getRetryCount() == 0 && lbContext.getServiceInstance() == null) {
// We haven't even tried to make the request yet so return true so we do

3
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRecoveryCallback.java

@ -45,8 +45,7 @@ public abstract class LoadBalancedRecoveryCallback<T, R> implements RecoveryCall @@ -45,8 +45,7 @@ public abstract class LoadBalancedRecoveryCallback<T, R> implements RecoveryCall
public T recover(RetryContext context) throws Exception {
Throwable lastThrowable = context.getLastThrowable();
if (lastThrowable != null) {
if (lastThrowable instanceof RetryableStatusCodeException) {
RetryableStatusCodeException ex = (RetryableStatusCodeException) lastThrowable;
if (lastThrowable instanceof RetryableStatusCodeException ex) {
return createResponse((R) ex.getResponse(), ex.getUri());
}
else if (lastThrowable instanceof Exception) {

8
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryPolicy.java

@ -20,6 +20,7 @@ package org.springframework.cloud.client.loadbalancer; @@ -20,6 +20,7 @@ package org.springframework.cloud.client.loadbalancer;
* Retry logic to use for the {@link LoadBalancerClient}.
*
* @author Ryan Baxter
* @author Olga Maciaszek-Sharma
*/
public interface LoadBalancedRetryPolicy {
@ -65,4 +66,11 @@ public interface LoadBalancedRetryPolicy { @@ -65,4 +66,11 @@ public interface LoadBalancedRetryPolicy {
*/
boolean retryableStatusCode(int statusCode);
/**
* Return <code>true</code> to retry if the provided exception is thrown.
* @param exception the {@link Throwable} to evaluate
* @return true to retry on the provided exception
*/
boolean retryableException(Throwable exception);
}

9
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfiguration.java

@ -51,7 +51,7 @@ import org.springframework.web.client.RestTemplate; @@ -51,7 +51,7 @@ import org.springframework.web.client.RestTemplate;
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RestTemplate.class)
@ConditionalOnBean(LoadBalancerClient.class)
@EnableConfigurationProperties(LoadBalancerProperties.class)
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
public class LoadBalancerAutoConfiguration {
@LoadBalanced
@ -147,11 +147,10 @@ public class LoadBalancerAutoConfiguration { @@ -147,11 +147,10 @@ public class LoadBalancerAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public RetryLoadBalancerInterceptor loadBalancerInterceptor(LoadBalancerClient loadBalancerClient,
LoadBalancerProperties properties, LoadBalancerRequestFactory requestFactory,
LoadBalancedRetryFactory loadBalancedRetryFactory,
LoadBalancerRequestFactory requestFactory, LoadBalancedRetryFactory loadBalancedRetryFactory,
ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory) {
return new RetryLoadBalancerInterceptor(loadBalancerClient, properties, requestFactory,
loadBalancedRetryFactory, loadBalancerFactory);
return new RetryLoadBalancerInterceptor(loadBalancerClient, requestFactory, loadBalancedRetryFactory,
loadBalancerFactory);
}
@Bean

43
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerClientsProperties.java

@ -0,0 +1,43 @@ @@ -0,0 +1,43 @@
/*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* A {@link ConfigurationProperties} bean for Spring Cloud Loadbalancer.
*
* Individual clients are configured via the {@link LoadBalancerClientsProperties#clients}
* field. Defaults and other properties are located in the {@link LoadBalancerProperties}
* base class.
*
* @author Spencer Gibb
* @since 3.1.0
*/
@ConfigurationProperties("spring.cloud.loadbalancer")
public class LoadBalancerClientsProperties extends LoadBalancerProperties {
private Map<String, LoadBalancerProperties> clients = new HashMap<>();
public Map<String, LoadBalancerProperties> getClients() {
return this.clients;
}
}

46
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerDefaultMappingsProviderAutoConfiguration.java

@ -0,0 +1,46 @@ @@ -0,0 +1,46 @@
/*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.client.loadbalancer;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.cloud.commons.config.DefaultsBindHandlerAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Spencer Gibb
* @since 3.1.0
*/
@Configuration(proxyBeanMethods = false)
@AutoConfigureBefore(name = "org.springframework.cloud.commons.config.CommonsConfigAutoConfiguration")
public class LoadBalancerDefaultMappingsProviderAutoConfiguration {
@Bean
public DefaultsBindHandlerAdvisor.MappingsProvider loadBalancerClientsDefaultsMappingsProvider() {
return () -> {
Map<ConfigurationPropertyName, ConfigurationPropertyName> mappings = new HashMap<>();
mappings.put(ConfigurationPropertyName.of("spring.cloud.loadbalancer.clients"),
ConfigurationPropertyName.of("spring.cloud.loadbalancer"));
return mappings;
};
}
}

27
spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientConnectionPoolFactory.java → spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerEagerLoadProperties.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -14,22 +14,27 @@ @@ -14,22 +14,27 @@
* limitations under the License.
*/
package org.springframework.cloud.commons.httpclient;
package org.springframework.cloud.client.loadbalancer;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import okhttp3.ConnectionPool;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Default implementation of {@link OkHttpClientConnectionPoolFactory}.
*
* @author Ryan Baxter
* @author Andrii Bohutskyi
*/
public class DefaultOkHttpClientConnectionPoolFactory implements OkHttpClientConnectionPoolFactory {
@ConfigurationProperties("spring.cloud.loadbalancer.eager-load")
public class LoadBalancerEagerLoadProperties {
private List<String> clients = new ArrayList<>();
public List<String> getClients() {
return clients;
}
@Override
public ConnectionPool create(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) {
return new ConnectionPool(maxIdleConnections, keepAliveDuration, timeUnit);
public void setClients(List<String> clients) {
this.clients = clients;
}
}

130
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerProperties.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,25 +16,32 @@ @@ -16,25 +16,32 @@
package org.springframework.cloud.client.loadbalancer;
import java.io.IOException;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import reactor.util.retry.RetryBackoffSpec;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.reactive.ReactiveLoadBalancer;
import org.springframework.http.HttpMethod;
import org.springframework.util.LinkedCaseInsensitiveMap;
/**
* A {@link ConfigurationProperties} bean for Spring Cloud LoadBalancer.
* The base configuration bean for Spring Cloud LoadBalancer.
*
* See {@link LoadBalancerClientsProperties} for the {@link ConfigurationProperties}
* annotation.
*
* @author Olga Maciaszek-Sharma
* @author Gandhimathi Velusamy
* @since 2.2.1
*/
@ConfigurationProperties("spring.cloud.loadbalancer")
public class LoadBalancerProperties {
/**
@ -65,6 +72,19 @@ public class LoadBalancerProperties { @@ -65,6 +72,19 @@ public class LoadBalancerProperties {
*/
private StickySession stickySession = new StickySession();
/**
* If this flag is set to {@code true},
* {@code ServiceInstanceListSupplier#get(Request request)} method will be implemented
* to call {@code delegate.get(request)} in classes assignable from
* {@code DelegatingServiceInstanceListSupplier} that don't already implement that
* method, with the exclusion of {@code CachingServiceInstanceListSupplier} and
* {@code HealthCheckServiceInstanceListSupplier}, which should be placed in the
* instance supplier hierarchy directly after the supplier performing instance
* retrieval over the network, before any request-based filtering is done,
* {@code true} by default.
*/
private boolean callGetWithRequestOnDelegates = true;
public HealthCheck getHealthCheck() {
return healthCheck;
}
@ -105,6 +125,27 @@ public class LoadBalancerProperties { @@ -105,6 +125,27 @@ public class LoadBalancerProperties {
this.hintHeaderName = hintHeaderName;
}
/**
* Enabling X-Forwarded Host and Proto Headers.
*/
private XForwarded xForwarded = new XForwarded();
public void setxForwarded(XForwarded xForwarded) {
this.xForwarded = xForwarded;
}
public XForwarded getXForwarded() {
return xForwarded;
}
public boolean isCallGetWithRequestOnDelegates() {
return callGetWithRequestOnDelegates;
}
public void setCallGetWithRequestOnDelegates(boolean callGetWithRequestOnDelegates) {
this.callGetWithRequestOnDelegates = callGetWithRequestOnDelegates;
}
public static class StickySession {
/**
@ -136,6 +177,23 @@ public class LoadBalancerProperties { @@ -136,6 +177,23 @@ public class LoadBalancerProperties {
}
public static class XForwarded {
/**
* To Enable X-Forwarded Headers.
*/
private boolean enabled = false;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
public static class HealthCheck {
/**
@ -153,8 +211,19 @@ public class LoadBalancerProperties { @@ -153,8 +211,19 @@ public class LoadBalancerProperties {
*/
private Duration refetchInstancesInterval = Duration.ofSeconds(25);
/**
* Path at which the health-check request should be made. Can be set up per
* <code>serviceId</code>. A <code>default</code> value can be set up as well. If
* none is set up, <code>/actuator/health</code> will be used.
*/
private Map<String, String> path = new LinkedCaseInsensitiveMap<>();
/**
* Port at which the health-check request should be made. If none is set, the port
* under which the requested service is available at the service instance.
*/
private Integer port;
/**
* Indicates whether the instances should be refetched by the
* <code>HealthCheckServiceInstanceListSupplier</code>. This can be used if the
@ -170,6 +239,14 @@ public class LoadBalancerProperties { @@ -170,6 +239,14 @@ public class LoadBalancerProperties {
*/
private boolean repeatHealthCheck = true;
/**
* Indicates whether the {@code healthCheckFlux} should emit on each alive
* {@link ServiceInstance} that has been retrieved. If set to {@code false}, the
* entire alive instances sequence is first collected into a list and only then
* emitted.
*/
private boolean updateResultsList = true;
public boolean getRefetchInstances() {
return refetchInstances;
}
@ -218,6 +295,22 @@ public class LoadBalancerProperties { @@ -218,6 +295,22 @@ public class LoadBalancerProperties {
this.interval = interval;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public boolean isUpdateResultsList() {
return updateResultsList;
}
public void setUpdateResultsList(boolean updateResultsList) {
this.updateResultsList = updateResultsList;
}
}
public static class Retry {
@ -230,6 +323,12 @@ public class LoadBalancerProperties { @@ -230,6 +323,12 @@ public class LoadBalancerProperties {
*/
private boolean retryOnAllOperations = false;
/**
* Indicates retries should be attempted for all exceptions, not only those
* specified in {@code retryableExceptions}.
*/
private boolean retryOnAllExceptions = false;
/**
* Number of retries to be executed on the same <code>ServiceInstance</code>.
*/
@ -246,6 +345,13 @@ public class LoadBalancerProperties { @@ -246,6 +345,13 @@ public class LoadBalancerProperties {
*/
private Set<Integer> retryableStatusCodes = new HashSet<>();
/**
* A {@link Set} of {@link Throwable} classes that should trigger a retry.
*/
private Set<Class<? extends Throwable>> retryableExceptions = new HashSet<>(
Arrays.asList(IOException.class, TimeoutException.class, RetryableStatusCodeException.class,
org.springframework.cloud.client.loadbalancer.reactive.RetryableStatusCodeException.class));
/**
* Properties for Reactor Retry backoffs in Spring Cloud LoadBalancer.
*/
@ -300,6 +406,16 @@ public class LoadBalancerProperties { @@ -300,6 +406,16 @@ public class LoadBalancerProperties {
this.retryableStatusCodes = retryableStatusCodes;
}
public Set<Class<? extends Throwable>> getRetryableExceptions() {
return retryableExceptions;
}
public void setRetryableExceptions(Set<Class<? extends Throwable>> retryableExceptions) {
retryableExceptions
.add(org.springframework.cloud.client.loadbalancer.reactive.RetryableStatusCodeException.class);
this.retryableExceptions = retryableExceptions;
}
public Backoff getBackoff() {
return backoff;
}
@ -308,6 +424,14 @@ public class LoadBalancerProperties { @@ -308,6 +424,14 @@ public class LoadBalancerProperties {
this.backoff = backoff;
}
public boolean isRetryOnAllExceptions() {
return retryOnAllExceptions;
}
public void setRetryOnAllExceptions(boolean retryOnAllExceptions) {
this.retryOnAllExceptions = retryOnAllExceptions;
}
public static class Backoff {
/**

8
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RequestData.java

@ -74,6 +74,11 @@ public class RequestData { @@ -74,6 +74,11 @@ public class RequestData {
new HashMap<>());
}
public RequestData(ServerHttpRequest request, Map<String, Object> attributes) {
this(request.getMethod(), request.getURI(), request.getHeaders(), buildCookies(request.getCookies()),
attributes);
}
private static MultiValueMap<String, String> buildCookies(MultiValueMap<String, HttpCookie> cookies) {
HttpHeaders newCookies = new HttpHeaders();
if (cookies != null) {
@ -136,10 +141,9 @@ public class RequestData { @@ -136,10 +141,9 @@ public class RequestData {
if (this == o) {
return true;
}
if (!(o instanceof RequestData)) {
if (!(o instanceof RequestData that)) {
return false;
}
RequestData that = (RequestData) o;
return httpMethod == that.httpMethod && Objects.equals(url, that.url) && Objects.equals(headers, that.headers)
&& Objects.equals(cookies, that.cookies) && Objects.equals(attributes, that.attributes);
}

11
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ResponseData.java

@ -23,7 +23,7 @@ import java.util.Objects; @@ -23,7 +23,7 @@ import java.util.Objects;
import org.springframework.core.style.ToStringCreator;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseCookie;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponse;
@ -40,7 +40,7 @@ import org.springframework.web.reactive.function.client.ClientResponse; @@ -40,7 +40,7 @@ import org.springframework.web.reactive.function.client.ClientResponse;
*/
public class ResponseData {
private final HttpStatus httpStatus;
private final HttpStatusCode httpStatus;
private final HttpHeaders headers;
@ -48,7 +48,7 @@ public class ResponseData { @@ -48,7 +48,7 @@ public class ResponseData {
private final RequestData requestData;
public ResponseData(HttpStatus httpStatus, HttpHeaders headers, MultiValueMap<String, ResponseCookie> cookies,
public ResponseData(HttpStatusCode httpStatus, HttpHeaders headers, MultiValueMap<String, ResponseCookie> cookies,
RequestData requestData) {
this.httpStatus = httpStatus;
this.headers = headers;
@ -69,7 +69,7 @@ public class ResponseData { @@ -69,7 +69,7 @@ public class ResponseData {
buildCookiesFromHeaders(clientHttpResponse.getHeaders()), requestData);
}
public HttpStatus getHttpStatus() {
public HttpStatusCode getHttpStatus() {
return httpStatus;
}
@ -121,10 +121,9 @@ public class ResponseData { @@ -121,10 +121,9 @@ public class ResponseData {
if (this == o) {
return true;
}
if (!(o instanceof ResponseData)) {
if (!(o instanceof ResponseData that)) {
return false;
}
ResponseData that = (ResponseData) o;
return httpStatus == that.httpStatus && Objects.equals(headers, that.headers)
&& Objects.equals(cookies, that.cookies) && Objects.equals(requestData, that.requestData);
}

33
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java

@ -18,6 +18,7 @@ package org.springframework.cloud.client.loadbalancer; @@ -18,6 +18,7 @@ package org.springframework.cloud.client.loadbalancer;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
@ -50,19 +51,16 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto @@ -50,19 +51,16 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto
private final LoadBalancerClient loadBalancer;
private final LoadBalancerProperties properties;
private final LoadBalancerRequestFactory requestFactory;
private final LoadBalancedRetryFactory lbRetryFactory;
private final ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory;
public RetryLoadBalancerInterceptor(LoadBalancerClient loadBalancer, LoadBalancerProperties properties,
LoadBalancerRequestFactory requestFactory, LoadBalancedRetryFactory lbRetryFactory,
public RetryLoadBalancerInterceptor(LoadBalancerClient loadBalancer, LoadBalancerRequestFactory requestFactory,
LoadBalancedRetryFactory lbRetryFactory,
ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory) {
this.loadBalancer = loadBalancer;
this.properties = properties;
this.requestFactory = requestFactory;
this.lbRetryFactory = lbRetryFactory;
this.loadBalancerFactory = loadBalancerFactory;
@ -78,8 +76,7 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto @@ -78,8 +76,7 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto
RetryTemplate template = createRetryTemplate(serviceName, request, retryPolicy);
return template.execute(context -> {
ServiceInstance serviceInstance = null;
if (context instanceof LoadBalancedRetryContext) {
LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context;
if (context instanceof LoadBalancedRetryContext lbContext) {
serviceInstance = lbContext.getServiceInstance();
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Retrieved service instance from LoadBalancedRetryContext: %s",
@ -97,8 +94,7 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto @@ -97,8 +94,7 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto
+ "Reattempting service instance selection");
}
ServiceInstance previousServiceInstance = null;
if (context instanceof LoadBalancedRetryContext) {
LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context;
if (context instanceof LoadBalancedRetryContext lbContext) {
previousServiceInstance = lbContext.getPreviousServiceInstance();
}
DefaultRequest<RetryableRequestContext> lbRequest = new DefaultRequest<>(
@ -108,8 +104,7 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto @@ -108,8 +104,7 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Selected service instance: %s", serviceInstance));
}
if (context instanceof LoadBalancedRetryContext) {
LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context;
if (context instanceof LoadBalancedRetryContext lbContext) {
lbContext.setServiceInstance(serviceInstance);
}
Response<ServiceInstance> lbResponse = new DefaultResponse(serviceInstance);
@ -126,9 +121,8 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto @@ -126,9 +121,8 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto
requestFactory.createRequest(request, body, execution),
new RetryableRequestContext(null, new RequestData(request), hint));
ServiceInstance finalServiceInstance = serviceInstance;
ClientHttpResponse response = RetryLoadBalancerInterceptor.this.loadBalancer.execute(serviceName,
finalServiceInstance, lbRequest);
int statusCode = response.getRawStatusCode();
ClientHttpResponse response = loadBalancer.execute(serviceName, finalServiceInstance, lbRequest);
int statusCode = response.getStatusCode().value();
if (retryPolicy != null && retryPolicy.retryableStatusCode(statusCode)) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Retrying on status code: %d", statusCode));
@ -159,14 +153,17 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto @@ -159,14 +153,17 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto
if (retryListeners != null && retryListeners.length != 0) {
template.setListeners(retryListeners);
}
template.setRetryPolicy(!properties.getRetry().isEnabled() || retryPolicy == null ? new NeverRetryPolicy()
: new InterceptorRetryPolicy(request, retryPolicy, loadBalancer, serviceName));
template.setRetryPolicy(
!loadBalancerFactory.getProperties(serviceName).getRetry().isEnabled() || retryPolicy == null
? new NeverRetryPolicy()
: new InterceptorRetryPolicy(request, retryPolicy, loadBalancer, serviceName));
return template;
}
private String getHint(String serviceId) {
String defaultHint = properties.getHint().getOrDefault("default", "default");
String hintPropertyValue = properties.getHint().get(serviceId);
Map<String, String> hint = loadBalancerFactory.getProperties(serviceId).getHint();
String defaultHint = hint.getOrDefault("default", "default");
String hintPropertyValue = hint.get(serviceId);
return hintPropertyValue != null ? hintPropertyValue : defaultHint;
}

3
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryableRequestContext.java

@ -66,13 +66,12 @@ public class RetryableRequestContext extends RequestDataContext { @@ -66,13 +66,12 @@ public class RetryableRequestContext extends RequestDataContext {
if (this == o) {
return true;
}
if (!(o instanceof RetryableRequestContext)) {
if (!(o instanceof RetryableRequestContext context)) {
return false;
}
if (!super.equals(o)) {
return false;
}
RetryableRequestContext context = (RetryableRequestContext) o;
return Objects.equals(previousServiceInstance, context.previousServiceInstance);
}

69
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerRetryContext.java

@ -16,6 +16,7 @@ @@ -16,6 +16,7 @@
package org.springframework.cloud.client.loadbalancer.reactive;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.http.HttpMethod;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ClientResponse;
@ -26,7 +27,7 @@ import org.springframework.web.reactive.function.client.ClientResponse; @@ -26,7 +27,7 @@ import org.springframework.web.reactive.function.client.ClientResponse;
* @author Olga Maciaszek-Sharma
* @since 3.0.0
*/
class LoadBalancerRetryContext {
public class LoadBalancerRetryContext {
private final ClientRequest request;
@ -36,47 +37,91 @@ class LoadBalancerRetryContext { @@ -36,47 +37,91 @@ class LoadBalancerRetryContext {
private Integer retriesNextServiceInstance = 0;
LoadBalancerRetryContext(ClientRequest request) {
protected LoadBalancerRetryContext(ClientRequest request) {
this.request = request;
}
ClientRequest getRequest() {
/**
* Returns the {@link ClientRequest} that is being load-balanced.
* @return the request that is being load-balanced.
*/
protected ClientRequest getRequest() {
return request;
}
ClientResponse getClientResponse() {
/**
* Returns the {@link ClientResponse} returned for load-balanced request.
* @return the response for the load-balanced request.
*/
protected ClientResponse getClientResponse() {
return clientResponse;
}
void setClientResponse(ClientResponse clientResponse) {
/**
* Sets the {@link ClientResponse} returned for load-balanced request.
* @param clientResponse the response for the load-balanced request.
*/
protected void setClientResponse(ClientResponse clientResponse) {
this.clientResponse = clientResponse;
}
Integer getRetriesSameServiceInstance() {
/**
* Returns the number of times a load-balanced request should be retried on the same
* {@link ServiceInstance}.
* @return the number of retries
*/
protected Integer getRetriesSameServiceInstance() {
return retriesSameServiceInstance;
}
void incrementRetriesSameServiceInstance() {
/**
* Increments the counter for the retries executed against the same
* {@link ServiceInstance}.
*/
protected void incrementRetriesSameServiceInstance() {
retriesSameServiceInstance++;
}
void resetRetriesSameServiceInstance() {
/**
* Resets the counter for the retries executed against the same
* {@link ServiceInstance}.
*/
protected void resetRetriesSameServiceInstance() {
retriesSameServiceInstance = 0;
}
Integer getRetriesNextServiceInstance() {
/**
* Returns the number of times a load-balanced request should be retried on the next
* {@link ServiceInstance}.
* @return the number of retries
*/
protected Integer getRetriesNextServiceInstance() {
return retriesNextServiceInstance;
}
void incrementRetriesNextServiceInstance() {
/**
* Increments the counter for the retries executed against the same
* {@link ServiceInstance}.
*/
protected void incrementRetriesNextServiceInstance() {
retriesNextServiceInstance++;
}
Integer getResponseStatusCode() {
/**
* Returns the status code from the {@link ClientResponse} returned for load-balanced
* request.
* @return the status code from the response for the load-balanced request.
*/
protected Integer getResponseStatusCode() {
return clientResponse.statusCode().value();
}
HttpMethod getRequestMethod() {
/**
* Returns the {@link HttpMethod} of the {@link ClientRequest} that is being
* load-balanced.
* @return the HTTP method of the request that is being load-balanced.
*/
protected HttpMethod getRequestMethod() {
return request.method();
}

12
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerRetryPolicy.java

@ -16,6 +16,7 @@ @@ -16,6 +16,7 @@
package org.springframework.cloud.client.loadbalancer.reactive;
import org.springframework.cglib.core.internal.Function;
import org.springframework.http.HttpMethod;
/**
@ -48,6 +49,13 @@ public interface LoadBalancerRetryPolicy { @@ -48,6 +49,13 @@ public interface LoadBalancerRetryPolicy {
*/
boolean retryableStatusCode(int statusCode);
/**
* Return <code>true</code> to retry if the provided exception is thrown.
* @param exception the {@link Throwable} to evaluate
* @return true to retry on the provided exception
*/
boolean retryableException(Throwable exception);
/**
* Return <code>true</code> to retry on the provided HTTP method.
* @param method the HTTP request method
@ -55,4 +63,8 @@ public interface LoadBalancerRetryPolicy { @@ -55,4 +63,8 @@ public interface LoadBalancerRetryPolicy {
*/
boolean canRetryOnMethod(HttpMethod method);
interface Factory extends Function<String, LoadBalancerRetryPolicy> {
}
}

5
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancer.java

@ -22,6 +22,7 @@ import org.reactivestreams.Publisher; @@ -22,6 +22,7 @@ import org.reactivestreams.Publisher;
import org.springframework.cloud.client.loadbalancer.DefaultRequest;
import org.springframework.cloud.client.loadbalancer.DefaultRequestContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
@ -53,6 +54,10 @@ public interface ReactiveLoadBalancer<T> { @@ -53,6 +54,10 @@ public interface ReactiveLoadBalancer<T> {
interface Factory<T> {
default LoadBalancerProperties getProperties(String serviceId) {
return null;
}
ReactiveLoadBalancer<T> getInstance(String serviceId);
/**

19
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerClientAutoConfiguration.java

@ -24,9 +24,10 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -24,9 +24,10 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;
@ -42,6 +43,7 @@ import org.springframework.web.reactive.function.client.WebClient; @@ -42,6 +43,7 @@ import org.springframework.web.reactive.function.client.WebClient;
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(WebClient.class)
@ConditionalOnBean(ReactiveLoadBalancer.Factory.class)
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
public class ReactorLoadBalancerClientAutoConfiguration {
@ConditionalOnMissingBean
@ -49,9 +51,9 @@ public class ReactorLoadBalancerClientAutoConfiguration { @@ -49,9 +51,9 @@ public class ReactorLoadBalancerClientAutoConfiguration {
matchIfMissing = true)
@Bean
public ReactorLoadBalancerExchangeFilterFunction loadBalancerExchangeFilterFunction(
ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory, LoadBalancerProperties properties,
ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory,
ObjectProvider<List<LoadBalancerClientRequestTransformer>> transformers) {
return new ReactorLoadBalancerExchangeFilterFunction(loadBalancerFactory, properties,
return new ReactorLoadBalancerExchangeFilterFunction(loadBalancerFactory,
transformers.getIfAvailable(Collections::emptyList));
}
@ -59,18 +61,19 @@ public class ReactorLoadBalancerClientAutoConfiguration { @@ -59,18 +61,19 @@ public class ReactorLoadBalancerClientAutoConfiguration {
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true")
@Bean
public RetryableLoadBalancerExchangeFilterFunction retryableLoadBalancerExchangeFilterFunction(
ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory, LoadBalancerProperties properties,
LoadBalancerRetryPolicy retryPolicy,
ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory,
LoadBalancerRetryPolicy.Factory retryPolicyFactory,
ObjectProvider<List<LoadBalancerClientRequestTransformer>> transformers) {
return new RetryableLoadBalancerExchangeFilterFunction(retryPolicy, loadBalancerFactory, properties,
return new RetryableLoadBalancerExchangeFilterFunction(retryPolicyFactory, loadBalancerFactory,
transformers.getIfAvailable(Collections::emptyList));
}
@ConditionalOnMissingBean
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true")
@Bean
public LoadBalancerRetryPolicy loadBalancerRetryPolicy(LoadBalancerProperties properties) {
return new RetryableExchangeFilterFunctionLoadBalancerRetryPolicy(properties);
public LoadBalancerRetryPolicy.Factory loadBalancerRetryPolicy(
ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory) {
return new RetryableExchangeFilterFunctionLoadBalancerRetryPolicy.Factory(loadBalancerFactory);
}
}

25
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerExchangeFilterFunction.java

@ -17,7 +17,6 @@ @@ -17,7 +17,6 @@
package org.springframework.cloud.client.loadbalancer.reactive;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Set;
@ -61,26 +60,11 @@ public class ReactorLoadBalancerExchangeFilterFunction implements LoadBalancedEx @@ -61,26 +60,11 @@ public class ReactorLoadBalancerExchangeFilterFunction implements LoadBalancedEx
private final ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory;
private final LoadBalancerProperties properties;
private final List<LoadBalancerClientRequestTransformer> transformers;
/**
* @deprecated Deprecated in favor of
* {@link #ReactorLoadBalancerExchangeFilterFunction(ReactiveLoadBalancer.Factory, LoadBalancerProperties, List)}.
* @param loadBalancerFactory the loadbalancer factory
* @param properties the properties for SC LoadBalancer
*/
@Deprecated
public ReactorLoadBalancerExchangeFilterFunction(ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory,
LoadBalancerProperties properties) {
this(loadBalancerFactory, properties, Collections.emptyList());
}
public ReactorLoadBalancerExchangeFilterFunction(ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory,
LoadBalancerProperties properties, List<LoadBalancerClientRequestTransformer> transformers) {
List<LoadBalancerClientRequestTransformer> transformers) {
this.loadBalancerFactory = loadBalancerFactory;
this.properties = properties;
this.transformers = transformers;
}
@ -89,7 +73,7 @@ public class ReactorLoadBalancerExchangeFilterFunction implements LoadBalancedEx @@ -89,7 +73,7 @@ public class ReactorLoadBalancerExchangeFilterFunction implements LoadBalancedEx
URI originalUrl = clientRequest.url();
String serviceId = originalUrl.getHost();
if (serviceId == null) {
String message = String.format("Request URI does not contain a valid hostname: %s", originalUrl.toString());
String message = String.format("Request URI does not contain a valid hostname: %s", originalUrl);
if (LOG.isWarnEnabled()) {
LOG.warn(message);
}
@ -99,7 +83,7 @@ public class ReactorLoadBalancerExchangeFilterFunction implements LoadBalancedEx @@ -99,7 +83,7 @@ public class ReactorLoadBalancerExchangeFilterFunction implements LoadBalancedEx
.getSupportedLifecycleProcessors(
loadBalancerFactory.getInstances(serviceId, LoadBalancerLifecycle.class),
RequestDataContext.class, ResponseData.class, ServiceInstance.class);
String hint = getHint(serviceId, properties.getHint());
String hint = getHint(serviceId, loadBalancerFactory.getProperties(serviceId).getHint());
RequestData requestData = new RequestData(clientRequest);
DefaultRequest<RequestDataContext> lbRequest = new DefaultRequest<>(new RequestDataContext(requestData, hint));
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStart(lbRequest));
@ -120,7 +104,8 @@ public class ReactorLoadBalancerExchangeFilterFunction implements LoadBalancedEx @@ -120,7 +104,8 @@ public class ReactorLoadBalancerExchangeFilterFunction implements LoadBalancedEx
LOG.debug(String.format("LoadBalancer has retrieved the instance for service %s: %s", serviceId,
instance.getUri()));
}
LoadBalancerProperties.StickySession stickySessionProperties = properties.getStickySession();
LoadBalancerProperties.StickySession stickySessionProperties = loadBalancerFactory.getProperties(serviceId)
.getStickySession();
ClientRequest newRequest = buildClientRequest(clientRequest, instance,
stickySessionProperties.getInstanceIdCookieName(),
stickySessionProperties.isAddServiceInstanceCookie(), transformers);

27
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableExchangeFilterFunctionLoadBalancerRetryPolicy.java

@ -16,6 +16,7 @@ @@ -16,6 +16,7 @@
package org.springframework.cloud.client.loadbalancer.reactive;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties;
import org.springframework.http.HttpMethod;
@ -48,9 +49,35 @@ public class RetryableExchangeFilterFunctionLoadBalancerRetryPolicy implements L @@ -48,9 +49,35 @@ public class RetryableExchangeFilterFunctionLoadBalancerRetryPolicy implements L
return properties.getRetry().getRetryableStatusCodes().contains(statusCode);
}
@Override
public boolean retryableException(Throwable throwable) {
if (properties.getRetry().isRetryOnAllExceptions()) {
return true;
}
return properties.getRetry().getRetryableExceptions().stream()
.anyMatch(exception -> exception.isInstance(throwable)
|| throwable != null && exception.isInstance(throwable.getCause()));
}
@Override
public boolean canRetryOnMethod(HttpMethod method) {
return HttpMethod.GET.equals(method) || properties.getRetry().isRetryOnAllOperations();
}
static class Factory implements LoadBalancerRetryPolicy.Factory {
final ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory;
Factory(ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory) {
this.loadBalancerFactory = loadBalancerFactory;
}
@Override
public LoadBalancerRetryPolicy apply(String serviceId) {
return new RetryableExchangeFilterFunctionLoadBalancerRetryPolicy(
loadBalancerFactory.getProperties(serviceId));
}
}
}

77
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableLoadBalancerExchangeFilterFunction.java

@ -16,13 +16,9 @@ @@ -16,13 +16,9 @@
package org.springframework.cloud.client.loadbalancer.reactive;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -66,52 +62,41 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced @@ -66,52 +62,41 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced
private static final Log LOG = LogFactory.getLog(RetryableLoadBalancerExchangeFilterFunction.class);
private static final List<Class<? extends Throwable>> exceptions = Arrays.asList(IOException.class,
TimeoutException.class, RetryableStatusCodeException.class);
private final LoadBalancerRetryPolicy retryPolicy;
private final LoadBalancerProperties properties;
private final LoadBalancerRetryPolicy.Factory retryPolicyFactory;
private final ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory;
private final List<LoadBalancerClientRequestTransformer> transformers;
/**
* @deprecated Deprecated in favor of
* {@link #RetryableLoadBalancerExchangeFilterFunction(LoadBalancerRetryPolicy, ReactiveLoadBalancer.Factory, LoadBalancerProperties, List)}.
*/
@Deprecated
public RetryableLoadBalancerExchangeFilterFunction(LoadBalancerRetryPolicy retryPolicy,
ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory, LoadBalancerProperties properties) {
this(retryPolicy, loadBalancerFactory, properties, Collections.emptyList());
}
public RetryableLoadBalancerExchangeFilterFunction(LoadBalancerRetryPolicy retryPolicy,
ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory, LoadBalancerProperties properties,
public RetryableLoadBalancerExchangeFilterFunction(LoadBalancerRetryPolicy.Factory retryPolicyFactory,
ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory,
List<LoadBalancerClientRequestTransformer> transformers) {
this.retryPolicy = retryPolicy;
this.retryPolicyFactory = retryPolicyFactory;
this.loadBalancerFactory = loadBalancerFactory;
this.properties = properties;
this.transformers = transformers;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Mono<ClientResponse> filter(ClientRequest clientRequest, ExchangeFunction next) {
LoadBalancerRetryContext loadBalancerRetryContext = new LoadBalancerRetryContext(clientRequest);
Retry exchangeRetry = buildRetrySpec(properties.getRetry().getMaxRetriesOnSameServiceInstance(), true);
Retry filterRetry = buildRetrySpec(properties.getRetry().getMaxRetriesOnNextServiceInstance(), false);
URI originalUrl = clientRequest.url();
String serviceId = originalUrl.getHost();
if (serviceId == null) {
String message = String.format("Request URI does not contain a valid hostname: %s", originalUrl.toString());
String message = String.format("Request URI does not contain a valid hostname: %s", originalUrl);
if (LOG.isWarnEnabled()) {
LOG.warn(message);
}
return Mono.just(ClientResponse.create(HttpStatus.BAD_REQUEST).body(message).build());
}
LoadBalancerRetryContext loadBalancerRetryContext = new LoadBalancerRetryContext(clientRequest);
LoadBalancerProperties properties = loadBalancerFactory.getProperties(serviceId);
LoadBalancerRetryPolicy retryPolicy = retryPolicyFactory.apply(serviceId);
Retry exchangeRetry = buildRetrySpec(properties.getRetry().getMaxRetriesOnSameServiceInstance(), true,
properties.getRetry(), retryPolicy);
Retry filterRetry = buildRetrySpec(properties.getRetry().getMaxRetriesOnNextServiceInstance(), false,
properties.getRetry(), retryPolicy);
Set<LoadBalancerLifecycle> supportedLifecycleProcessors = LoadBalancerLifecycleValidator
.getSupportedLifecycleProcessors(
loadBalancerFactory.getInstances(serviceId, LoadBalancerLifecycle.class),
@ -154,7 +139,7 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced @@ -154,7 +139,7 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced
lbRequest, lbResponse, new ResponseData(clientResponse, requestData)))))
.map(clientResponse -> {
loadBalancerRetryContext.setClientResponse(clientResponse);
if (shouldRetrySameServiceInstance(loadBalancerRetryContext)) {
if (shouldRetrySameServiceInstance(retryPolicy, loadBalancerRetryContext)) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Retrying on status code: %d",
clientResponse.statusCode().value()));
@ -166,7 +151,7 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced @@ -166,7 +151,7 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced
});
}).map(clientResponse -> {
loadBalancerRetryContext.setClientResponse(clientResponse);
if (shouldRetryNextServiceInstance(loadBalancerRetryContext)) {
if (shouldRetryNextServiceInstance(retryPolicy, loadBalancerRetryContext)) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Retrying on status code: %d", clientResponse.statusCode().value()));
}
@ -177,17 +162,25 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced @@ -177,17 +162,25 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced
}).retryWhen(exchangeRetry)).retryWhen(filterRetry);
}
private Retry buildRetrySpec(int max, boolean transientErrors) {
LoadBalancerProperties.Retry.Backoff backoffProperties = properties.getRetry().getBackoff();
private Retry buildRetrySpec(int max, boolean transientErrors, LoadBalancerProperties.Retry retry,
LoadBalancerRetryPolicy retryPolicy) {
if (!retry.isEnabled()) {
return Retry.max(0).filter(throwable -> isRetryException(throwable, retryPolicy))
.transientErrors(transientErrors);
}
LoadBalancerProperties.Retry.Backoff backoffProperties = retry.getBackoff();
if (backoffProperties.isEnabled()) {
return RetrySpec.backoff(max, backoffProperties.getMinBackoff()).filter(this::isRetryException)
return RetrySpec.backoff(max, backoffProperties.getMinBackoff())
.filter(throwable -> isRetryException(throwable, retryPolicy))
.maxBackoff(backoffProperties.getMaxBackoff()).jitter(backoffProperties.getJitter())
.transientErrors(transientErrors);
}
return RetrySpec.max(max).filter(this::isRetryException).transientErrors(transientErrors);
return RetrySpec.max(max).filter(throwable -> isRetryException(throwable, retryPolicy))
.transientErrors(transientErrors);
}
private boolean shouldRetrySameServiceInstance(LoadBalancerRetryContext loadBalancerRetryContext) {
private boolean shouldRetrySameServiceInstance(LoadBalancerRetryPolicy retryPolicy,
LoadBalancerRetryContext loadBalancerRetryContext) {
boolean shouldRetry = retryPolicy.retryableStatusCode(loadBalancerRetryContext.getResponseStatusCode())
&& retryPolicy.canRetryOnMethod(loadBalancerRetryContext.getRequestMethod())
&& retryPolicy.canRetrySameServiceInstance(loadBalancerRetryContext);
@ -197,7 +190,8 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced @@ -197,7 +190,8 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced
return shouldRetry;
}
private boolean shouldRetryNextServiceInstance(LoadBalancerRetryContext loadBalancerRetryContext) {
private boolean shouldRetryNextServiceInstance(LoadBalancerRetryPolicy retryPolicy,
LoadBalancerRetryContext loadBalancerRetryContext) {
boolean shouldRetry = retryPolicy.retryableStatusCode(loadBalancerRetryContext.getResponseStatusCode())
&& retryPolicy.canRetryOnMethod(loadBalancerRetryContext.getRequestMethod())
&& retryPolicy.canRetryNextServiceInstance(loadBalancerRetryContext);
@ -208,11 +202,10 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced @@ -208,11 +202,10 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced
return shouldRetry;
}
private boolean isRetryException(Throwable throwable) {
return exceptions.stream()
.anyMatch(exception -> exception.isInstance(throwable)
|| throwable != null && exception.isInstance(throwable.getCause())
|| Exceptions.isRetryExhausted(throwable));
private boolean isRetryException(Throwable throwable, LoadBalancerRetryPolicy retryPolicy) {
return retryPolicy.retryableException(throwable)
|| (throwable != null && retryPolicy.retryableException(throwable.getCause()))
|| Exceptions.isRetryExhausted(throwable);
}
protected Mono<Response<ServiceInstance>> choose(String serviceId, Request<RetryableRequestContext> request) {

2
spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableStatusCodeException.java

@ -23,6 +23,6 @@ package org.springframework.cloud.client.loadbalancer.reactive; @@ -23,6 +23,6 @@ package org.springframework.cloud.client.loadbalancer.reactive;
* @author Olga Maciaszek-Sharma
* @since 3.0.0
*/
class RetryableStatusCodeException extends IllegalStateException {
public class RetryableStatusCodeException extends IllegalStateException {
}

75
spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistration.java

@ -16,11 +16,12 @@ @@ -16,11 +16,12 @@
package org.springframework.cloud.client.serviceregistry;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PreDestroy;
import jakarta.annotation.PreDestroy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -43,6 +44,7 @@ import org.springframework.core.env.Environment; @@ -43,6 +44,7 @@ import org.springframework.core.env.Environment;
*
* @param <R> Registration type passed to the {@link ServiceRegistry}.
* @author Spencer Gibb
* @author Zen Huifer
*/
public abstract class AbstractAutoServiceRegistration<R extends Registration>
implements AutoServiceRegistration, ApplicationContextAware, ApplicationListener<WebServerInitializedEvent> {
@ -51,29 +53,53 @@ public abstract class AbstractAutoServiceRegistration<R extends Registration> @@ -51,29 +53,53 @@ public abstract class AbstractAutoServiceRegistration<R extends Registration>
private final ServiceRegistry<R> serviceRegistry;
private boolean autoStartup = true;
private final boolean autoStartup = true;
private final AtomicBoolean running = new AtomicBoolean(false);
private AtomicBoolean running = new AtomicBoolean(false);
private final int order = 0;
private int order = 0;
private final AtomicInteger port = new AtomicInteger(0);
private ApplicationContext context;
private Environment environment;
private AtomicInteger port = new AtomicInteger(0);
private AutoServiceRegistrationProperties properties;
@Deprecated
protected AbstractAutoServiceRegistration(ServiceRegistry<R> serviceRegistry) {
private List<RegistrationManagementLifecycle<R>> registrationManagementLifecycles = new ArrayList<>();
private List<RegistrationLifecycle<R>> registrationLifecycles = new ArrayList<>();
protected AbstractAutoServiceRegistration(ServiceRegistry<R> serviceRegistry,
AutoServiceRegistrationProperties properties) {
this.serviceRegistry = serviceRegistry;
this.properties = properties;
}
protected AbstractAutoServiceRegistration(ServiceRegistry<R> serviceRegistry,
AutoServiceRegistrationProperties properties) {
AutoServiceRegistrationProperties properties,
List<RegistrationManagementLifecycle<R>> registrationManagementLifecycles,
List<RegistrationLifecycle<R>> registrationLifecycles) {
this.serviceRegistry = serviceRegistry;
this.properties = properties;
this.registrationManagementLifecycles = registrationManagementLifecycles;
this.registrationLifecycles = registrationLifecycles;
}
protected AbstractAutoServiceRegistration(ServiceRegistry<R> serviceRegistry,
AutoServiceRegistrationProperties properties, List<RegistrationLifecycle<R>> registrationLifecycles) {
this.serviceRegistry = serviceRegistry;
this.properties = properties;
this.registrationLifecycles = registrationLifecycles;
}
public void addRegistrationManagementLifecycle(RegistrationManagementLifecycle<R> registrationManagementLifecycle) {
this.registrationManagementLifecycles.add(registrationManagementLifecycle);
}
public void addRegistrationLifecycle(RegistrationLifecycle<R> registrationLifecycle) {
this.registrationLifecycles.add(registrationLifecycle);
}
protected ApplicationContext getContext() {
@ -83,11 +109,6 @@ public abstract class AbstractAutoServiceRegistration<R extends Registration> @@ -83,11 +109,6 @@ public abstract class AbstractAutoServiceRegistration<R extends Registration>
@Override
@SuppressWarnings("deprecation")
public void onApplicationEvent(WebServerInitializedEvent event) {
bind(event);
}
@Deprecated
public void bind(WebServerInitializedEvent event) {
ApplicationContext context = event.getApplicationContext();
if (context instanceof ConfigurableWebServerApplicationContext) {
if ("management".equals(((ConfigurableWebServerApplicationContext) context).getServerNamespace())) {
@ -130,9 +151,20 @@ public abstract class AbstractAutoServiceRegistration<R extends Registration> @@ -130,9 +151,20 @@ public abstract class AbstractAutoServiceRegistration<R extends Registration>
// because of containerPortInitializer below
if (!this.running.get()) {
this.context.publishEvent(new InstancePreRegisteredEvent(this, getRegistration()));
registrationLifecycles.forEach(
registrationLifecycle -> registrationLifecycle.postProcessBeforeStartRegister(getRegistration()));
register();
this.registrationLifecycles.forEach(
registrationLifecycle -> registrationLifecycle.postProcessAfterStartRegister(getRegistration()));
if (shouldRegisterManagement()) {
registerManagement();
this.registrationManagementLifecycles
.forEach(registrationManagementLifecycle -> registrationManagementLifecycle
.postProcessBeforeStartRegisterManagement(getManagementRegistration()));
this.registerManagement();
registrationManagementLifecycles
.forEach(registrationManagementLifecycle -> registrationManagementLifecycle
.postProcessAfterStartRegisterManagement(getManagementRegistration()));
}
this.context.publishEvent(new InstanceRegisteredEvent<>(this, getConfiguration()));
this.running.compareAndSet(false, true);
@ -261,9 +293,20 @@ public abstract class AbstractAutoServiceRegistration<R extends Registration> @@ -261,9 +293,20 @@ public abstract class AbstractAutoServiceRegistration<R extends Registration>
public void stop() {
if (this.getRunning().compareAndSet(true, false) && isEnabled()) {
this.registrationLifecycles.forEach(
registrationLifecycle -> registrationLifecycle.postProcessBeforeStopRegister(getRegistration()));
deregister();
this.registrationLifecycles.forEach(
registrationLifecycle -> registrationLifecycle.postProcessAfterStopRegister(getRegistration()));
if (shouldRegisterManagement()) {
this.registrationManagementLifecycles
.forEach(registrationManagementLifecycle -> registrationManagementLifecycle
.postProcessBeforeStopRegisterManagement(getManagementRegistration()));
deregisterManagement();
this.registrationManagementLifecycles
.forEach(registrationManagementLifecycle -> registrationManagementLifecycle
.postProcessAfterStopRegisterManagement(getManagementRegistration()));
}
this.serviceRegistry.close();
}

9
spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationAutoConfiguration.java

@ -16,8 +16,7 @@ @@ -16,8 +16,7 @@
package org.springframework.cloud.client.serviceregistry;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
@ -29,7 +28,7 @@ import org.springframework.context.annotation.Import; @@ -29,7 +28,7 @@ import org.springframework.context.annotation.Import;
@Configuration(proxyBeanMethods = false)
@Import(AutoServiceRegistrationConfiguration.class)
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
public class AutoServiceRegistrationAutoConfiguration {
public class AutoServiceRegistrationAutoConfiguration implements InitializingBean {
@Autowired(required = false)
private AutoServiceRegistration autoServiceRegistration;
@ -37,8 +36,8 @@ public class AutoServiceRegistrationAutoConfiguration { @@ -37,8 +36,8 @@ public class AutoServiceRegistrationAutoConfiguration {
@Autowired
private AutoServiceRegistrationProperties properties;
@PostConstruct
protected void init() {
@Override
public void afterPropertiesSet() {
if (this.autoServiceRegistration == null && this.properties.isFailFast()) {
throw new IllegalStateException(
"Auto Service Registration has " + "been requested, but there is no AutoServiceRegistration bean");

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

Loading…
Cancel
Save