├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── LICENSE ├── README.md ├── cron-service-leader ├── .springBeans ├── README.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── CronServiceLeaderApplication.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── example │ └── CronServiceLeaderApplicationTests.java ├── cron-service-locks ├── README.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── CronServiceApplication.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── example │ └── CronServiceApplicationTests.java ├── cron-service-optimist ├── .springBeans ├── README.md ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── CronServiceOptimistApplication.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── example │ └── CronServiceOptimistApplicationTests.java ├── docker-compose.yml ├── extra.md ├── images ├── fencing-a-lock.png ├── fencing-a-lock.txt ├── lizard-protection.png ├── lizard-protection.txt ├── locks-basic-sequence-0.png ├── locks-basic-sequence-0.wsd ├── locks-basic-sequence-1.png ├── locks-basic-sequence-1.wsd ├── locks-basic-sequence-2.png ├── locks-basic-sequence-2.wsd ├── locks-basic-sequence-3.png ├── locks-basic-sequence-3.wsd ├── locks-basic-sequence-4.png ├── locks-basic-sequence-4.wsd ├── locks-basic-sequence-5.png ├── locks-basic-sequence-5.wsd ├── writing-stale-data.png └── writing-stale-data.txt ├── mvnw ├── mvnw.cmd └── pom.xml /.gitignore: -------------------------------------------------------------------------------- 1 | *# 2 | .#* 3 | *~ 4 | .idea 5 | *.iml 6 | classes 7 | target 8 | .metadata 9 | .recommenders/ 10 | .classpath 11 | .project 12 | .settings/ 13 | RemoteSystemFiles 14 | node 15 | node_modules 16 | etc 17 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpringOnePlatform2016/dsyer-locks-and-leaders/b0e9f3210df8a7e1c29a3b1e4a611bb0115822f4/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2015-Present Pivotal Software Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | 205 | 206 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Locks and Leaders 3 | layout: plain 4 | theme: spring 5 | --- 6 | # Locks and Leaders with Spring Integration 7 | 8 | Dave Syer, 2016 9 | Twitter: @david_syer (see also @artem_bilan, @gprussell) 10 | Email: `dsyer@pivotal.io` 11 | 12 | ## Agenda 13 | 14 | * What is a distributed lock? 15 | * What is a leader election? 16 | * What is it good for? 17 | * How do I do it? 18 | * Some tools for thinking about failure 19 | 20 | 21 | 22 | > Warning: Here be Dragons! 23 | 24 | ## A Simple Distributed Operation 25 | 26 | ![basic-sequence-0](images/locks-basic-sequence-0.png) 27 | 28 | ## Two Clients 29 | 30 | ![basic-sequence-1](images/locks-basic-sequence-1.png) 31 | 32 | ## Shuffle! 33 | 34 | ![basic-sequence-2](images/locks-basic-sequence-2.png) 35 | 36 | ## Shuffle! 37 | 38 | ![basic-sequence-3](images/locks-basic-sequence-3.png) 39 | 40 | ## Shuffle! 41 | 42 | ![basic-sequence-4](images/locks-basic-sequence-4.png) 43 | 44 | ## Shuffle! 45 | 46 | ![basic-sequence-4](images/locks-basic-sequence-2.png) 47 | 48 | ## Shuffle! 49 | 50 | ![basic-sequence-4](images/locks-basic-sequence-1.png) 51 | 52 | ## Shuffle! 53 | 54 | ![basic-sequence-4](images/locks-basic-sequence-3.png) 55 | 56 | ## Scary, Eh? 57 | 58 | ![basic-sequence-5](images/locks-basic-sequence-5.png) 59 | 60 | ## Locks 61 | 62 | Example code using `java.util.concurrent.locks.Lock`: 63 | 64 | ```java 65 | boolean acquired = false; 66 | try { 67 | acquired = lock.tryLock(10, TimeUnit.SECONDS); 68 | if (acquired) { 69 | // Do something unique! 70 | } 71 | } catch (InterruptedException e) { 72 | Thread.currentThread().interrupt(); 73 | throw new RuntimeException("Interrupted"); 74 | } finally { 75 | if (acquired) { 76 | lock.unlock(); 77 | } 78 | } 79 | ``` 80 | 81 | 82 | ## Spring Integration: LockRegistry 83 | 84 | ```java 85 | public interface LockRegistry { 86 | Lock obtain(Object lockKey); 87 | } 88 | ``` 89 | 90 | ## Locks with Spring Integration 91 | 92 | Example code using `LockRegistry`: 93 | 94 | ```java 95 | boolean acquired = false; 96 | try { 97 | acquired = lock.tryLock(10, TimeUnit.SECONDS); 98 | if (acquired) { 99 | // Do something unique! 100 | } 101 | } catch (InterruptedException e) { 102 | Thread.currentThread().interrupt(); 103 | throw new RuntimeException("Interrupted"); 104 | } finally { 105 | if (acquired) { 106 | lock.unlock(); 107 | } 108 | } 109 | ``` 110 | 111 | (same code) 112 | 113 | ## Locks and Leases 114 | 115 | A distributed lock nearly always has a shelf life (it expires). 116 | 117 | Technically, that makes it a "lease". 118 | 119 | Without expiry system can't make progress when a lock holder dies. 120 | 121 | ## Dragons 122 | 123 | (At least) two problems are lurking: 124 | 125 | 1. Acquiring a lock requires consensus. 126 | 2. Leases expire and holder can never be sure when that happens. 127 | 128 | **Read this**: 129 | [http://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html](http://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html) 130 | 131 | TL;DR If using a lock for "correctness" not "efficiency" be *very* careful. 132 | 133 | ## Public Service Announcement 134 | 135 | > Important: you can tune the system to adjust the probability, or how 136 | > long it lasts, but fundamentally you cannot prevent the system from 137 | > ever allowing more than one holder of a lock. 138 | 139 | ## Leader Elections 140 | 141 | > Simple idea: if you hold a lock you are the leader. 142 | 143 | What can you do with it? 144 | 145 | > Highly available globally unique things, often with messages 146 | 147 | * sequences 148 | * message aggregation 149 | * scheduling, e.g. cron service 150 | 151 | ## Spring Integration: Leader Initiator 152 | 153 | Implementations of leader election need to be able to start an 154 | election and fire events on granted and revoked. 155 | 156 | * Zookeeper 157 | * Hazelcast 158 | * Etcd(*) 159 | * Generic (lock-based) 160 | 161 | For a user it looks like this (create a new bean which is a `SmartLifecycle`): 162 | 163 | ```java 164 | @Bean 165 | public LeaderInitiator leaderInitiator(CuratorFramework client, 166 | Candidate candidate) { 167 | return new LeaderInitiator(client, candidate); 168 | } 169 | ``` 170 | 171 | (*) No support for etcd v3. Probably dead. 172 | 173 | ## Spring Integration: Callbacks 174 | 175 | Callbacks on leadership events: 176 | 177 | ```java 178 | public interface Candidate { 179 | void onGranted(Context ctx) throws InterruptedException; 180 | void onRevoked(Context ctx); 181 | ... 182 | } 183 | ``` 184 | 185 | See also: 186 | 187 | ```java 188 | @EventListener(OnGrantedEvent.class) 189 | public void start() { 190 | 191 | } 192 | 193 | @EventListener(OnRevokedEvent.class) 194 | public void stop() { 195 | 196 | } 197 | ``` 198 | 199 | ## Closing 200 | 201 | * When to use locks and leaders: HA active/passive failover 202 | 203 | * How to avoid it: latency from restarting a failed app might be fine 204 | 205 | * Otherwise, be idempotent. For correctness, de-duplication store has to be ACID. 206 | 207 | * Relational databases can be really useful, as is Zookeeper. 208 | 209 | * Careful with the physics. 210 | 211 | ## Links 212 | 213 | * http://presos.dsyer.com/decks/locks-and-leaders.html 214 | * Sample code: [https://github.com/SpringOnePlatform2016/dsyer-locks-and-leaders](https://github.com/SpringOnePlatform2016/dsyer-locks-and-leaders) 215 | * Spring Integration: [https://github.com/spring-projects/spring-integration](https://github.com/spring-projects/spring-integration) 216 | * Spring Cloud Cluster: [https://github.com/spring-cloud/spring-cloud-cluster](https://github.com/spring-cloud/spring-cloud-cluster) 217 | 218 | -------------------------------------------------------------------------------- /cron-service-leader/.springBeans: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | 10 | java:com.example.fraud.CronServiceLeaderApplication 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /cron-service-leader/README.md: -------------------------------------------------------------------------------- 1 | A basic ping-a-web-hook-on-a-cron service using explicit leader 2 | election to ensure only one instance does the ping. The hooks are 3 | stored in a relational database, and in this sample the same database 4 | is used to manage the leader, via Spring Integration. It will work 5 | with any relational database that supports transaction isolation (see 6 | the Spring Integration user guide for more detail). 7 | 8 | The default profile just uses in-memory (java.util.concurrent) locks, 9 | so it only works for a single node. There is a "cloud" profile that 10 | you can run to enable the JDBC locks (e.g. this would be activated 11 | automatically in Cloud Foundry). The database is not explicitly 12 | configured, except for the schema to run on startup. To run on Cloud 13 | Foundry just bind to a MySQL service called "mysql". To run locally 14 | with multiple nodes set `spring.datasource.url` to a local h2 server 15 | (or use `DATABASE_PLATFORM=mysql` if using MySQL) and activate 16 | the "cloud" profile. 17 | 18 | There is a `docker-compose.yml` to run MySQL locally in the parent 19 | directory. Or you can run h2 really easily with `spring cloud h2` 20 | (using the spring cloud CLI launcher plugin). 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /cron-service-leader/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | cron-service-leader 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | cron-service-leader 12 | Demo 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.4.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | 1.8 24 | 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-actuator 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-data-jpa 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-starter-data-rest 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-integration 42 | 43 | 44 | org.springframework.integration 45 | spring-integration-jdbc 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-web 50 | 51 | 52 | 53 | com.h2database 54 | h2 55 | runtime 56 | 57 | 58 | mysql 59 | mysql-connector-java 60 | runtime 61 | 62 | 63 | org.springframework.boot 64 | spring-boot-starter-test 65 | test 66 | 67 | 68 | org.springframework.cloud 69 | spring-cloud-starter 70 | 71 | 72 | 73 | 74 | 75 | 76 | org.springframework.boot 77 | spring-boot-maven-plugin 78 | 79 | 80 | 81 | 82 | 83 | 84 | spring-snapshots 85 | Spring Snapshots 86 | https://repo.spring.io/snapshot 87 | 88 | true 89 | 90 | 91 | 92 | spring-milestones 93 | Spring Milestones 94 | https://repo.spring.io/milestone 95 | 96 | false 97 | 98 | 99 | 100 | 101 | 102 | spring-snapshots 103 | Spring Snapshots 104 | https://repo.spring.io/snapshot 105 | 106 | true 107 | 108 | 109 | 110 | spring-milestones 111 | Spring Milestones 112 | https://repo.spring.io/milestone 113 | 114 | false 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | org.springframework.cloud 123 | spring-cloud-dependencies 124 | Brixton.SR4 125 | pom 126 | import 127 | 128 | 129 | 130 | 131 | -------------------------------------------------------------------------------- /cron-service-leader/src/main/java/com/example/CronServiceLeaderApplication.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import java.io.Closeable; 4 | import java.io.IOException; 5 | import java.util.HashSet; 6 | import java.util.Map; 7 | import java.util.Set; 8 | import java.util.concurrent.ExecutorService; 9 | import java.util.concurrent.Executors; 10 | 11 | import javax.persistence.Entity; 12 | import javax.persistence.GeneratedValue; 13 | import javax.persistence.Id; 14 | 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | import org.springframework.boot.CommandLineRunner; 18 | import org.springframework.boot.SpringApplication; 19 | import org.springframework.boot.autoconfigure.SpringBootApplication; 20 | import org.springframework.context.ApplicationEventPublisher; 21 | import org.springframework.context.annotation.Bean; 22 | import org.springframework.context.annotation.ComponentScan; 23 | import org.springframework.context.annotation.Configuration; 24 | import org.springframework.context.annotation.Profile; 25 | import org.springframework.data.repository.PagingAndSortingRepository; 26 | import org.springframework.data.rest.core.annotation.RepositoryRestResource; 27 | import org.springframework.http.HttpMethod; 28 | import org.springframework.integration.jdbc.lock.JdbcLockRegistry; 29 | import org.springframework.integration.jdbc.lock.LockRepository; 30 | import org.springframework.integration.leader.Candidate; 31 | import org.springframework.integration.leader.Context; 32 | import org.springframework.integration.leader.DefaultCandidate; 33 | import org.springframework.integration.leader.event.DefaultLeaderEventPublisher; 34 | import org.springframework.integration.support.leader.LockRegistryLeaderInitiator; 35 | import org.springframework.integration.support.locks.DefaultLockRegistry; 36 | import org.springframework.integration.support.locks.LockRegistry; 37 | import org.springframework.scheduling.annotation.SchedulingConfigurer; 38 | import org.springframework.scheduling.config.CronTask; 39 | import org.springframework.scheduling.config.ScheduledTaskRegistrar; 40 | import org.springframework.stereotype.Component; 41 | import org.springframework.web.client.RestTemplate; 42 | 43 | @SpringBootApplication 44 | public class CronServiceLeaderApplication { 45 | 46 | @Bean 47 | public LockRegistryLeaderInitiator leaderInitiator(LockRegistry locks, 48 | Candidate candidate, ApplicationEventPublisher applicationEventPublisher) { 49 | LockRegistryLeaderInitiator initiator = new LockRegistryLeaderInitiator(locks, 50 | candidate); 51 | initiator.setLeaderEventPublisher( 52 | new DefaultLeaderEventPublisher(applicationEventPublisher)); 53 | return initiator; 54 | } 55 | 56 | public static void main(String[] args) { 57 | SpringApplication.run(CronServiceLeaderApplication.class, args); 58 | } 59 | } 60 | 61 | @Configuration 62 | @Profile("!cloud") 63 | class DefaultLockConfiguration { 64 | @Bean 65 | public DefaultLockRegistry defaultLockRegistry() { 66 | return new DefaultLockRegistry(); 67 | } 68 | } 69 | 70 | @Configuration 71 | @Profile("cloud") 72 | @ComponentScan(basePackageClasses = LockRepository.class) 73 | class JdbcLockConfiguration { 74 | 75 | @Bean 76 | public JdbcLockRegistry jdbcLockRegistry(LockRepository lockRepository) { 77 | return new JdbcLockRegistry(lockRepository); 78 | } 79 | 80 | } 81 | 82 | @Component 83 | class Scheduler implements SchedulingConfigurer, Closeable { 84 | 85 | private volatile ScheduledTaskRegistrar taskRegistrar; 86 | private volatile ExecutorService pool; 87 | private volatile boolean running = false; 88 | 89 | @Override 90 | public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { 91 | this.taskRegistrar = taskRegistrar; 92 | } 93 | 94 | public void addTask(Runnable task, String expression) { 95 | if (running) { 96 | taskRegistrar.scheduleCronTask(new CronTask(task, expression)); 97 | } 98 | else { 99 | taskRegistrar.addCronTask(new CronTask(task, expression)); 100 | } 101 | } 102 | 103 | public void start() { 104 | running = true; 105 | if (taskRegistrar != null) { 106 | pool = Executors.newScheduledThreadPool(10); 107 | taskRegistrar.setScheduler(pool); 108 | taskRegistrar.afterPropertiesSet(); 109 | } 110 | } 111 | 112 | public void stop() { 113 | if (taskRegistrar != null) { 114 | taskRegistrar.destroy(); 115 | pool.shutdown(); 116 | pool = null; 117 | } 118 | running = false; 119 | } 120 | 121 | @Override 122 | public void close() throws IOException { 123 | stop(); 124 | } 125 | 126 | } 127 | 128 | @Component 129 | class HookPinger extends DefaultCandidate implements CommandLineRunner { 130 | 131 | private static Logger logger = LoggerFactory.getLogger(HookPinger.class); 132 | 133 | private final HookRepository repository; 134 | private Scheduler scheduler; 135 | private RestTemplate restTemplate = new RestTemplate(); 136 | private Set hooks = new HashSet<>(); 137 | 138 | public HookPinger(HookRepository repository, Scheduler scheduler) { 139 | this.repository = repository; 140 | this.scheduler = scheduler; 141 | } 142 | 143 | @Override 144 | public void onGranted(Context ctx) { 145 | super.onGranted(ctx); 146 | scheduler.start(); 147 | } 148 | 149 | @Override 150 | public void onRevoked(Context ctx) { 151 | scheduler.stop(); 152 | super.onRevoked(ctx); 153 | } 154 | 155 | @Override 156 | public void run(String... args) throws Exception { 157 | if (repository.count() == 0) { 158 | repository.save(new Hook(HttpMethod.GET, "http://localhost:8080/health", 159 | "*/10 * * * * *")); 160 | } 161 | for (Hook hook : repository.findAll()) { 162 | if (!hooks.contains(hook.getId())) { 163 | hooks.add(hook.getId()); 164 | scheduler.addTask(getTask(hook.getId()), hook.getCron()); 165 | } 166 | } 167 | } 168 | 169 | private Runnable getTask(Long id) { 170 | return () -> { 171 | Hook hook = repository.findOne(id); 172 | long version = hook.getVersion(); 173 | try { 174 | checkVersion(hook, version); 175 | logger.info("Pinging: " + hook); 176 | restTemplate.exchange(hook.getUri(), hook.getMethod(), null, Map.class); 177 | updateVersion(hook, version); 178 | } 179 | catch (Exception e) { 180 | // Don't care 181 | logger.info("Missed: " + e.getMessage()); 182 | } 183 | }; 184 | } 185 | 186 | private void checkVersion(Hook hook, long version) { 187 | Hook check = repository.findOne(hook.getId()); 188 | if (check.getVersion() != version) { 189 | throw new RuntimeException("Version does not match: expected " + version 190 | + " but found " + check.getVersion()); 191 | } 192 | } 193 | 194 | private void updateVersion(Hook hook, long version) { 195 | hook.setVersion(version + 1); 196 | repository.save(hook); 197 | } 198 | 199 | } 200 | 201 | @RepositoryRestResource 202 | interface HookRepository extends PagingAndSortingRepository { 203 | } 204 | 205 | @Entity 206 | class Hook { 207 | 208 | @Id 209 | @GeneratedValue 210 | private Long id; 211 | 212 | @SuppressWarnings("unused") 213 | private Hook() { 214 | } 215 | 216 | public Hook(HttpMethod method, String uri, String cron) { 217 | this.method = method; 218 | this.uri = uri; 219 | this.cron = cron; 220 | } 221 | 222 | private String cron; 223 | 224 | private String uri; 225 | 226 | private HttpMethod method = HttpMethod.POST; 227 | 228 | private long version = 0L; 229 | 230 | public long getVersion() { 231 | return version; 232 | } 233 | 234 | public void setVersion(long version) { 235 | this.version = version; 236 | } 237 | 238 | public Long getId() { 239 | return id; 240 | } 241 | 242 | public String getCron() { 243 | return cron; 244 | } 245 | 246 | public void setCron(String cron) { 247 | this.cron = cron; 248 | } 249 | 250 | public String getUri() { 251 | return uri; 252 | } 253 | 254 | public void setUri(String uri) { 255 | this.uri = uri; 256 | } 257 | 258 | public HttpMethod getMethod() { 259 | return method; 260 | } 261 | 262 | public void setMethod(HttpMethod method) { 263 | this.method = method; 264 | } 265 | 266 | @Override 267 | public String toString() { 268 | return method + " [id=" + id + ", uri=" + uri + "]"; 269 | } 270 | 271 | } -------------------------------------------------------------------------------- /cron-service-leader/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | schema: classpath:org/springframework/integration/jdbc/schema-${spring.datasource.platform}.sql 4 | continue-on-error: true 5 | platform: ${DATABASE_PLATFORM:${vcap.services.mysql.name:h2}} 6 | jpa: 7 | generate-ddl: false 8 | -------------------------------------------------------------------------------- /cron-service-leader/src/test/java/com/example/CronServiceLeaderApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | import java.util.concurrent.locks.Lock; 5 | import java.util.concurrent.locks.ReentrantLock; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | @RunWith(SpringRunner.class) 13 | @SpringBootTest 14 | public class CronServiceLeaderApplicationTests { 15 | 16 | @Test 17 | public void contextLoads() { 18 | // Simple lock API usage 19 | Lock lock = new ReentrantLock(); 20 | boolean acquired = false; 21 | try { 22 | acquired = lock.tryLock(10, TimeUnit.SECONDS); 23 | if (acquired) { 24 | // Do something unique! 25 | } 26 | } 27 | catch (InterruptedException e) { 28 | Thread.currentThread().interrupt(); 29 | throw new RuntimeException("Interrupted"); 30 | } 31 | finally { 32 | if (acquired) { 33 | lock.unlock(); 34 | } 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /cron-service-locks/README.md: -------------------------------------------------------------------------------- 1 | A basic ping-a-web-hook-on-a-cron service using explicit locks to 2 | ensure only one instance does the ping. The hooks are stored in a 3 | relational database, and in this sample the same database is used to 4 | manage the locks, via Spring Integration. It will work with any 5 | relational database that supports transaction isolation (see the 6 | Spring Integration user guide for more detail). 7 | 8 | The default profile just uses in-memory (java.util.concurrent) locks, 9 | so it only works for a single node. There is a "cloud" profile that 10 | you can run to enable the JDBC locks (e.g. this would be activated 11 | automatically in Cloud Foundry). The database is not explicitly 12 | configured, except for the schema to run on startup. To run on Cloud 13 | Foundry just bind to a MySQL service called "mysql". To run locally 14 | with multiple nodes set `spring.datasource.url` to a local h2 server 15 | (or use `DATABASE_PLATFORM=mysql` if using MySQL) and activate 16 | the "cloud" profile. 17 | 18 | There is a `docker-compose.yml` to run MySQL locally in the parent 19 | directory. Or you can run h2 really easily with `spring cloud h2` 20 | (using the spring cloud CLI launcher plugin). 21 | 22 | -------------------------------------------------------------------------------- /cron-service-locks/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | cron-service-locks 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | cron-service-locks 12 | Demo 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.4.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | 1.8 24 | 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-actuator 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-data-jpa 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-starter-data-rest 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-integration 42 | 43 | 44 | org.springframework.integration 45 | spring-integration-jdbc 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-web 50 | 51 | 52 | 53 | com.h2database 54 | h2 55 | runtime 56 | 57 | 58 | mysql 59 | mysql-connector-java 60 | runtime 61 | 62 | 63 | org.springframework.boot 64 | spring-boot-starter-test 65 | test 66 | 67 | 68 | 69 | 70 | 71 | 72 | org.springframework.boot 73 | spring-boot-maven-plugin 74 | 75 | 76 | 77 | 78 | 79 | 80 | spring-snapshots 81 | Spring Snapshots 82 | https://repo.spring.io/snapshot 83 | 84 | true 85 | 86 | 87 | 88 | spring-milestones 89 | Spring Milestones 90 | https://repo.spring.io/milestone 91 | 92 | false 93 | 94 | 95 | 96 | 97 | 98 | spring-snapshots 99 | Spring Snapshots 100 | https://repo.spring.io/snapshot 101 | 102 | true 103 | 104 | 105 | 106 | spring-milestones 107 | Spring Milestones 108 | https://repo.spring.io/milestone 109 | 110 | false 111 | 112 | 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /cron-service-locks/src/main/java/com/example/CronServiceApplication.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import java.io.Closeable; 4 | import java.io.IOException; 5 | import java.util.HashSet; 6 | import java.util.Map; 7 | import java.util.Set; 8 | import java.util.concurrent.ExecutorService; 9 | import java.util.concurrent.Executors; 10 | import java.util.concurrent.locks.Lock; 11 | 12 | import javax.persistence.Entity; 13 | import javax.persistence.GeneratedValue; 14 | import javax.persistence.Id; 15 | 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | import org.springframework.boot.CommandLineRunner; 19 | import org.springframework.boot.SpringApplication; 20 | import org.springframework.boot.autoconfigure.SpringBootApplication; 21 | import org.springframework.context.annotation.Bean; 22 | import org.springframework.context.annotation.ComponentScan; 23 | import org.springframework.context.annotation.Configuration; 24 | import org.springframework.context.annotation.Profile; 25 | import org.springframework.data.repository.PagingAndSortingRepository; 26 | import org.springframework.data.rest.core.annotation.RepositoryRestResource; 27 | import org.springframework.http.HttpMethod; 28 | import org.springframework.integration.jdbc.lock.JdbcLockRegistry; 29 | import org.springframework.integration.jdbc.lock.LockRepository; 30 | import org.springframework.integration.support.locks.DefaultLockRegistry; 31 | import org.springframework.integration.support.locks.LockRegistry; 32 | import org.springframework.scheduling.annotation.SchedulingConfigurer; 33 | import org.springframework.scheduling.config.ScheduledTaskRegistrar; 34 | import org.springframework.stereotype.Component; 35 | import org.springframework.web.client.RestTemplate; 36 | 37 | @SpringBootApplication 38 | public class CronServiceApplication { 39 | 40 | public static void main(String[] args) { 41 | SpringApplication.run(CronServiceApplication.class, args); 42 | } 43 | } 44 | 45 | @Configuration 46 | @Profile("!cloud") 47 | class DefaultLockConfiguration { 48 | @Bean 49 | public DefaultLockRegistry defaultLockRegistry() { 50 | return new DefaultLockRegistry(); 51 | } 52 | } 53 | 54 | @Configuration 55 | @Profile("cloud") 56 | @ComponentScan(basePackageClasses = LockRepository.class) 57 | class JdbcLockConfiguration { 58 | 59 | @Bean 60 | public JdbcLockRegistry jdbcLockRegistry(LockRepository lockRepository) { 61 | return new JdbcLockRegistry(lockRepository); 62 | } 63 | 64 | } 65 | 66 | @Component 67 | class Scheduler implements SchedulingConfigurer, Closeable { 68 | 69 | private ScheduledTaskRegistrar taskRegistrar; 70 | private ExecutorService pool; 71 | 72 | @Override 73 | public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { 74 | this.taskRegistrar = taskRegistrar; 75 | } 76 | 77 | public void addTask(Runnable task, String expression) { 78 | taskRegistrar.addCronTask(task, expression); 79 | } 80 | 81 | public void start() { 82 | pool = Executors.newScheduledThreadPool(10); 83 | taskRegistrar.setScheduler(pool); 84 | taskRegistrar.afterPropertiesSet(); 85 | } 86 | 87 | public void stop() { 88 | taskRegistrar.destroy(); 89 | pool.shutdown(); 90 | } 91 | 92 | @Override 93 | public void close() throws IOException { 94 | stop(); 95 | } 96 | 97 | } 98 | 99 | @Component 100 | class HookPinger implements CommandLineRunner { 101 | 102 | private static Logger logger = LoggerFactory.getLogger(HookPinger.class); 103 | 104 | private final HookRepository repository; 105 | private final LockRegistry locks; 106 | private Scheduler scheduler; 107 | private RestTemplate restTemplate = new RestTemplate(); 108 | private Set hooks = new HashSet<>(); 109 | 110 | public HookPinger(LockRegistry locks, HookRepository repository, 111 | Scheduler scheduler) { 112 | this.locks = locks; 113 | this.repository = repository; 114 | this.scheduler = scheduler; 115 | } 116 | 117 | @Override 118 | public void run(String... args) throws Exception { 119 | if (repository.count() == 0) { 120 | repository.save(new Hook(HttpMethod.GET, "http://localhost:8080/health", 121 | "*/10 * * * * *")); 122 | } 123 | for (Hook hook : repository.findAll()) { 124 | if (!hooks.contains(hook.getId())) { 125 | hooks.add(hook.getId()); 126 | scheduler.addTask(getTask(hook.getId()), hook.getCron()); 127 | } 128 | } 129 | scheduler.start(); 130 | } 131 | 132 | private Runnable getTask(Long id) { 133 | return () -> { 134 | Hook hook = repository.findOne(id); 135 | long version = hook.getVersion(); 136 | Lock lock = locks.obtain("hooks/" + hook.getId()); 137 | try { 138 | if (lock.tryLock()) { 139 | checkVersion(hook, version); 140 | logger.info("Pinging: " + hook); 141 | restTemplate.exchange(hook.getUri(), hook.getMethod(), null, 142 | Map.class); 143 | updateVersion(hook, version); 144 | } 145 | else { 146 | logger.info("Missed: lock not taken"); 147 | } 148 | } 149 | catch (Exception e) { 150 | // Don't care (even if it's InterruptedException, no one is blocking 151 | // upstream waiting for an interrupt). 152 | logger.info("Missed: " + e.getMessage()); 153 | } 154 | finally { 155 | try { 156 | lock.unlock(); 157 | } 158 | catch (Exception e) { 159 | } 160 | } 161 | }; 162 | } 163 | 164 | private void checkVersion(Hook hook, long version) { 165 | Hook check = repository.findOne(hook.getId()); 166 | if (check.getVersion() != version) { 167 | throw new RuntimeException("Version does not match: expected " + version 168 | + " but found " + check.getVersion()); 169 | } 170 | } 171 | 172 | private void updateVersion(Hook hook, long version) { 173 | hook.setVersion(version + 1); 174 | repository.save(hook); 175 | } 176 | 177 | } 178 | 179 | @RepositoryRestResource 180 | interface HookRepository extends PagingAndSortingRepository { 181 | } 182 | 183 | @Entity 184 | class Hook { 185 | 186 | @Id 187 | @GeneratedValue 188 | private Long id; 189 | 190 | @SuppressWarnings("unused") 191 | private Hook() { 192 | } 193 | 194 | public Hook(HttpMethod method, String uri, String cron) { 195 | this.method = method; 196 | this.uri = uri; 197 | this.cron = cron; 198 | } 199 | 200 | private String cron; 201 | 202 | private String uri; 203 | 204 | private HttpMethod method = HttpMethod.POST; 205 | 206 | private long version = 0L; 207 | 208 | public long getVersion() { 209 | return version; 210 | } 211 | 212 | public void setVersion(long version) { 213 | this.version = version; 214 | } 215 | 216 | public Long getId() { 217 | return id; 218 | } 219 | 220 | public String getCron() { 221 | return cron; 222 | } 223 | 224 | public void setCron(String cron) { 225 | this.cron = cron; 226 | } 227 | 228 | public String getUri() { 229 | return uri; 230 | } 231 | 232 | public void setUri(String uri) { 233 | this.uri = uri; 234 | } 235 | 236 | public HttpMethod getMethod() { 237 | return method; 238 | } 239 | 240 | public void setMethod(HttpMethod method) { 241 | this.method = method; 242 | } 243 | 244 | @Override 245 | public String toString() { 246 | return method + " [id=" + id + ", uri=" + uri + "]"; 247 | } 248 | 249 | } -------------------------------------------------------------------------------- /cron-service-locks/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | schema: classpath:org/springframework/integration/jdbc/schema-${spring.datasource.platform}.sql 4 | continue-on-error: true 5 | platform: ${DATABASE_PLATFORM:${vcap.services.mysql.name:h2}} 6 | jpa: 7 | generate-ddl: false -------------------------------------------------------------------------------- /cron-service-locks/src/test/java/com/example/CronServiceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class CronServiceApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /cron-service-optimist/.springBeans: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | 10 | java:com.example.fraud.CronServiceOptimistApplication 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /cron-service-optimist/README.md: -------------------------------------------------------------------------------- 1 | A basic ping-a-web-hook-on-a-cron service using optimistic locks to 2 | ensure only one instance does the ping. The hooks are stored in a 3 | relational database, and in this sample the same database is used to 4 | manage the locks, via Spring Integration and Spring Data. 5 | 6 | The database is not explicitly configured, except for the schema to 7 | run on startup. To run on Cloud Foundry just bind to a MySQL service 8 | called "mysql". To run locally with multiple nodes set 9 | `spring.datasource.url` to a local h2 server (or use 10 | `DATABASE_PLATFORM=mysql` if using MySQL). 11 | -------------------------------------------------------------------------------- /cron-service-optimist/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | cron-service-optimist 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | cron-service-optimist 12 | Demo 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.4.0.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | 1.8 24 | 25 | 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-starter-actuator 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-data-jpa 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-starter-data-rest 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-web 42 | 43 | 44 | 45 | com.h2database 46 | h2 47 | runtime 48 | 49 | 50 | mysql 51 | mysql-connector-java 52 | runtime 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-starter-test 57 | test 58 | 59 | 60 | org.springframework.cloud 61 | spring-cloud-starter 62 | 63 | 64 | 65 | 66 | 67 | 68 | org.springframework.boot 69 | spring-boot-maven-plugin 70 | 71 | 72 | 73 | 74 | 75 | 76 | spring-snapshots 77 | Spring Snapshots 78 | https://repo.spring.io/snapshot 79 | 80 | true 81 | 82 | 83 | 84 | spring-milestones 85 | Spring Milestones 86 | https://repo.spring.io/milestone 87 | 88 | false 89 | 90 | 91 | 92 | 93 | 94 | spring-snapshots 95 | Spring Snapshots 96 | https://repo.spring.io/snapshot 97 | 98 | true 99 | 100 | 101 | 102 | spring-milestones 103 | Spring Milestones 104 | https://repo.spring.io/milestone 105 | 106 | false 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | org.springframework.cloud 115 | spring-cloud-dependencies 116 | Brixton.SR4 117 | pom 118 | import 119 | 120 | 121 | 122 | 123 | -------------------------------------------------------------------------------- /cron-service-optimist/src/main/java/com/example/CronServiceOptimistApplication.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import java.io.Closeable; 4 | import java.io.IOException; 5 | import java.util.HashSet; 6 | import java.util.Map; 7 | import java.util.Set; 8 | import java.util.concurrent.ExecutorService; 9 | import java.util.concurrent.Executors; 10 | 11 | import javax.persistence.Entity; 12 | import javax.persistence.GeneratedValue; 13 | import javax.persistence.Id; 14 | import javax.persistence.Version; 15 | import javax.transaction.Transactional; 16 | 17 | import org.slf4j.Logger; 18 | import org.slf4j.LoggerFactory; 19 | import org.springframework.boot.CommandLineRunner; 20 | import org.springframework.boot.SpringApplication; 21 | import org.springframework.boot.autoconfigure.SpringBootApplication; 22 | import org.springframework.data.repository.PagingAndSortingRepository; 23 | import org.springframework.data.rest.core.annotation.RepositoryRestResource; 24 | import org.springframework.http.HttpMethod; 25 | import org.springframework.scheduling.annotation.SchedulingConfigurer; 26 | import org.springframework.scheduling.config.CronTask; 27 | import org.springframework.scheduling.config.ScheduledTaskRegistrar; 28 | import org.springframework.stereotype.Component; 29 | import org.springframework.stereotype.Service; 30 | import org.springframework.web.client.RestTemplate; 31 | 32 | import com.example.Hook.State; 33 | 34 | @SpringBootApplication 35 | public class CronServiceOptimistApplication { 36 | 37 | public static void main(String[] args) { 38 | SpringApplication.run(CronServiceOptimistApplication.class, args); 39 | } 40 | } 41 | 42 | @Component 43 | class Scheduler implements SchedulingConfigurer, Closeable { 44 | 45 | private volatile ScheduledTaskRegistrar taskRegistrar; 46 | private volatile ExecutorService pool; 47 | private volatile boolean running = false; 48 | 49 | @Override 50 | public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { 51 | this.taskRegistrar = taskRegistrar; 52 | } 53 | 54 | public void addTask(Runnable task, String expression) { 55 | if (running) { 56 | taskRegistrar.scheduleCronTask(new CronTask(task, expression)); 57 | } 58 | else { 59 | taskRegistrar.addCronTask(new CronTask(task, expression)); 60 | } 61 | } 62 | 63 | public void start() { 64 | running = true; 65 | if (taskRegistrar != null) { 66 | pool = Executors.newScheduledThreadPool(10); 67 | taskRegistrar.setScheduler(pool); 68 | taskRegistrar.afterPropertiesSet(); 69 | } 70 | } 71 | 72 | public void stop() { 73 | if (taskRegistrar != null) { 74 | taskRegistrar.destroy(); 75 | pool.shutdown(); 76 | pool = null; 77 | } 78 | running = false; 79 | } 80 | 81 | @Override 82 | public void close() throws IOException { 83 | stop(); 84 | } 85 | 86 | } 87 | 88 | @Component 89 | class HookPinger implements CommandLineRunner { 90 | 91 | private static Logger logger = LoggerFactory.getLogger(HookPinger.class); 92 | 93 | private final HookService service; 94 | private final HookRepository hooks; 95 | private Scheduler scheduler; 96 | private RestTemplate restTemplate = new RestTemplate(); 97 | private Set cache = new HashSet<>(); 98 | 99 | public HookPinger(HookService service, HookRepository repository, 100 | Scheduler scheduler) { 101 | this.service = service; 102 | this.hooks = repository; 103 | this.scheduler = scheduler; 104 | } 105 | 106 | @Override 107 | public void run(String... args) throws Exception { 108 | if (hooks.count() == 0) { 109 | hooks.save(new Hook(HttpMethod.GET, "http://localhost:8080/health", 110 | "*/10 * * * * *")); 111 | } 112 | for (Hook hook : hooks.findAll()) { 113 | if (!cache.contains(hook.getId())) { 114 | cache.add(hook.getId()); 115 | scheduler.addTask(getTask(hook.getId()), hook.getCron()); 116 | } 117 | } 118 | scheduler.start(); 119 | } 120 | 121 | private Runnable getTask(Long id) { 122 | return () -> { 123 | Hook hook = null; 124 | try { 125 | hook = service.start(id); 126 | logger.info("Pinging: " + hook); 127 | restTemplate.exchange(hook.getUri(), hook.getMethod(), null, Map.class); 128 | hook.setState(State.COMPLETE); 129 | } 130 | catch (AlreadyRunningException e) { 131 | logger.info(e.getMessage()); 132 | } 133 | catch (Exception e) { 134 | // Don't care 135 | if (hook != null) { 136 | hook.setState(State.FAILED); 137 | logger.info("Failed: " + hook + " (" + e.getMessage() + ")"); 138 | } else { 139 | logger.info("Missed: " + e.getMessage()); 140 | } 141 | } 142 | finally { 143 | try { 144 | service.update(hook, id); 145 | } 146 | catch (Exception e) { 147 | // Don't care 148 | } 149 | } 150 | }; 151 | } 152 | 153 | } 154 | 155 | @SuppressWarnings("serial") 156 | class AlreadyRunningException extends RuntimeException { 157 | 158 | public AlreadyRunningException(String message) { 159 | super(message); 160 | } 161 | 162 | } 163 | 164 | @Service 165 | @Transactional 166 | class HookService { 167 | 168 | private final HookRepository hooks; 169 | 170 | public HookService(HookRepository hooks) { 171 | this.hooks = hooks; 172 | } 173 | 174 | public Hook update(Hook hook, Long id) { 175 | if (hook != null) { 176 | return hooks.save(hook); 177 | } else { 178 | hook = hooks.findOne(id); 179 | hook.setState(State.FAILED); 180 | hooks.save(hook); 181 | } 182 | return null; 183 | } 184 | 185 | public Hook start(Long id) { 186 | Hook hook = hooks.findOne(id); 187 | if (hook.getState() == State.RUNNING) { 188 | throw new RuntimeException("Already running: " + hook); 189 | } 190 | hook.setState(State.RUNNING); 191 | return hooks.save(hook); 192 | } 193 | 194 | } 195 | 196 | @RepositoryRestResource 197 | interface HookRepository extends PagingAndSortingRepository { 198 | } 199 | 200 | @Entity 201 | class Hook { 202 | 203 | enum State { 204 | COMPLETE, RUNNING, FAILED; 205 | } 206 | 207 | private State state = State.COMPLETE; 208 | 209 | @Id 210 | @GeneratedValue 211 | private Long id; 212 | 213 | @SuppressWarnings("unused") 214 | private Hook() { 215 | } 216 | 217 | public Hook(HttpMethod method, String uri, String cron) { 218 | this.method = method; 219 | this.uri = uri; 220 | this.cron = cron; 221 | } 222 | 223 | private String cron; 224 | 225 | private String uri; 226 | 227 | private HttpMethod method = HttpMethod.POST; 228 | 229 | @Version 230 | private long version = 0L; 231 | 232 | public long getVersion() { 233 | return version; 234 | } 235 | 236 | public Long getId() { 237 | return id; 238 | } 239 | 240 | public String getCron() { 241 | return cron; 242 | } 243 | 244 | public void setCron(String cron) { 245 | this.cron = cron; 246 | } 247 | 248 | public String getUri() { 249 | return uri; 250 | } 251 | 252 | public void setUri(String uri) { 253 | this.uri = uri; 254 | } 255 | 256 | public HttpMethod getMethod() { 257 | return method; 258 | } 259 | 260 | public void setMethod(HttpMethod method) { 261 | this.method = method; 262 | } 263 | 264 | public State getState() { 265 | return state; 266 | } 267 | 268 | public void setState(State state) { 269 | this.state = state; 270 | } 271 | 272 | @Override 273 | public String toString() { 274 | return method + " [id=" + id + ", uri=" + uri + ", state=" + state + "]"; 275 | } 276 | 277 | } -------------------------------------------------------------------------------- /cron-service-optimist/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | schema: classpath:org/springframework/integration/jdbc/schema-${spring.datasource.platform}.sql 4 | continue-on-error: true 5 | platform: ${DATABASE_PLATFORM:${vcap.services.mysql.name:h2}} 6 | jpa: 7 | generate-ddl: false 8 | h2: 9 | console: 10 | enabled: true -------------------------------------------------------------------------------- /cron-service-optimist/src/test/java/com/example/CronServiceOptimistApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import javax.transaction.Transactional; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | @RunWith(SpringRunner.class) 14 | @SpringBootTest 15 | public class CronServiceOptimistApplicationTests { 16 | 17 | @Autowired 18 | private HookRepository hooks; 19 | 20 | @Test 21 | @Transactional 22 | public void contextLoads() { 23 | Hook hook = hooks.findOne(1L); 24 | assertThat(hook).isNotNull(); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | mysql: 2 | image: mysql 3 | ports: 4 | - "3306:3306" 5 | environment: 6 | - MYSQL_ROOT_PASSWORD=root 7 | - MYSQL_DATABASE=test 8 | volumes: 9 | - "./conf.d:/etc/mysql/conf.d:ro" -------------------------------------------------------------------------------- /extra.md: -------------------------------------------------------------------------------- 1 | ## Links 2 | 3 | Optimistic Locks fencing and ping: 4 | 5 | [Client1 Wins](https://www.websequencediagrams.com/?lz=CkNsaWVudDEtPlN0b3JhZ2VTZXJ2aWNlOiByZWFkKDMzKQAbBzIAASEyLT4rADUQc3RhcnRpbmcoMzQpCgBUDi0-LQBTBzogb2sAXApXZWJob29rOiBwaW5nAD8cdWNjZXNzADIoMQBnNzE6IGZhaWwKZGVzdHJveSAAgikHCgo&s=roundgreen) 6 | 7 | [CLient2 Wins](https://www.websequencediagrams.com/?lz=CkNsaWVudDEtPlN0b3JhZ2VTZXJ2aWNlOiByZWFkKDMzKQAbBzIAASExLT4rADUQc3RhcnRpbmcoMzQpCgBUDi0-LQB1Bzogb2sAfgpXZWJob29rOiBwaW5nAD8cdWNjZXNzADIoMgBnNzI6IGZhaWwKZGVzdHJveSAAggcHCg&s=roundgreen) 8 | 9 | [Oops](https://www.websequencediagrams.com/?lz=CkNsaWVudDEtPlN0b3JhZ2VTZXJ2aWNlOiByZWFkKDMzKQAYCisAExBzdGFydGluZygzNCkKADIOLT4tAFMHOiBvawBfBzIAThg0KQpub3RlIHJpZ2h0IG9mIAApBzogcmVzdWx0IG5vdCByZWNvcmRlZApkZXN0cm95AB0IAIE5CldlYmhvb2s6IHBpbmcAgRwcdWNjZXNzAIEVIg&s=roundgreen) 10 | 11 | ## Gotcha 12 | 13 | ```java 14 | ... 15 | if (acquired) { 16 | // Don't assume only one process can do this 17 | } 18 | ... 19 | ``` 20 | 21 | All threads/processes are competing for the lock. If one 22 | drops it, accidentally or on purpose, another will grab it. 23 | 24 | > Tip: You need to guard the work inside the lock to make 25 | > it idempotent anyway. (More later...) 26 | 27 | ## What? 28 | 29 | ```java 30 | ... 31 | if (acquired) { 32 | // Who is watching? How do they let you know 33 | // if a lock expires? 34 | } 35 | ... 36 | ``` 37 | 38 | The lock has to be a shared resource across multiple processes. Laws 39 | of physics prevent the lock holder from being immediately aware of a 40 | lock being broken, even supposing he is able to detect it. 41 | 42 | ## Writing Stale Data 43 | 44 | ![writing-stale-data](images/writing-stale-data.png) 45 | 46 | ## Fencing 47 | 48 | ```java 49 | MyData data = getDataIncludingVersion(); 50 | ... 51 | if (acquired) { 52 | checkVersion(data); // Throw exception here if someone else updated the data 53 | update(data); 54 | } 55 | ... 56 | ``` 57 | 58 | N.B. The version is not necessarily part of the lock; it's stored and 59 | checked in the shared resource that needs to be updated. 60 | 61 | ## Fencing a Lock 62 | 63 | From Martin Kleppmann: 64 | 65 | ![fencing-a-lock](images/fencing-a-lock.png) 66 | 67 | > BUT: The storage service has to be fully consistent. 68 | 69 | ## Alternative View 70 | 71 | ![lizard-protection](images/lizard-protection.png) 72 | 73 | > BUT: Now the storage service has to have isolation guarantees as 74 | > well (ACID). 75 | 76 | -------------------------------------------------------------------------------- /images/fencing-a-lock.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpringOnePlatform2016/dsyer-locks-and-leaders/b0e9f3210df8a7e1c29a3b1e4a611bb0115822f4/images/fencing-a-lock.png -------------------------------------------------------------------------------- /images/fencing-a-lock.txt: -------------------------------------------------------------------------------- 1 | title Fencing a Lock 2 | 3 | Client1->+LockService: getLock 4 | LockService->Client1: lock (token:33) 5 | Client1-->+Client1: GC start 6 | LockService->-Client1: expire 7 | Client2->+LockService: getLock 8 | LockService->Client2: lock (token:34) 9 | Client2->+StorageService: write (token:34) 10 | StorageService->-Client2: ok 11 | Client1-->-Client1: GC end 12 | Client1->+StorageService: write (token:33) 13 | StorageService->-Client1: fail 14 | -------------------------------------------------------------------------------- /images/lizard-protection.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpringOnePlatform2016/dsyer-locks-and-leaders/b0e9f3210df8a7e1c29a3b1e4a611bb0115822f4/images/lizard-protection.png -------------------------------------------------------------------------------- /images/lizard-protection.txt: -------------------------------------------------------------------------------- 1 | 2 | Client1->+LockService: getLock 3 | Client1->+StorageService: read(33) 4 | Client1-->+Client1: GC start 5 | LockService->-Client1: expire 6 | Client2->+LockService: getLock 7 | Client2->StorageService: read(33) 8 | Client2->StorageService: write(34) 9 | StorageService->Client2: ok 10 | Client1-->-Client1: GC end 11 | Client1->StorageService: write(34) 12 | StorageService->-Client1: fail 13 | -------------------------------------------------------------------------------- /images/locks-basic-sequence-0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpringOnePlatform2016/dsyer-locks-and-leaders/b0e9f3210df8a7e1c29a3b1e4a611bb0115822f4/images/locks-basic-sequence-0.png -------------------------------------------------------------------------------- /images/locks-basic-sequence-0.wsd: -------------------------------------------------------------------------------- 1 | Client1->StorageService: read 2 | Client1->StorageService: starting 3 | Client1->Webhook: ping 4 | Client1->+StorageService: success 5 | StorageService->-Client1: ok 6 | -------------------------------------------------------------------------------- /images/locks-basic-sequence-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpringOnePlatform2016/dsyer-locks-and-leaders/b0e9f3210df8a7e1c29a3b1e4a611bb0115822f4/images/locks-basic-sequence-1.png -------------------------------------------------------------------------------- /images/locks-basic-sequence-1.wsd: -------------------------------------------------------------------------------- 1 | participant Client1 2 | participant Client2 3 | Client1->StorageService: read 4 | Client1->StorageService: starting 5 | Client1->Webhook: ping 6 | Client1->+StorageService: success 7 | StorageService->-Client1: ok 8 | Client2->StorageService: read 9 | Client2->StorageService: starting 10 | Client2->Webhook: ping 11 | Client2->+StorageService: success 12 | StorageService->-Client2: ok 13 | -------------------------------------------------------------------------------- /images/locks-basic-sequence-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpringOnePlatform2016/dsyer-locks-and-leaders/b0e9f3210df8a7e1c29a3b1e4a611bb0115822f4/images/locks-basic-sequence-2.png -------------------------------------------------------------------------------- /images/locks-basic-sequence-2.wsd: -------------------------------------------------------------------------------- 1 | participant Client1 2 | participant Client2 3 | Client1->StorageService: read 4 | Client2->StorageService: read 5 | Client1->StorageService: starting 6 | Client1->Webhook: ping 7 | Client1->+StorageService: success 8 | StorageService->-Client1: ok 9 | Client2->StorageService: starting 10 | Client2->Webhook: ping 11 | Client2->+StorageService: success 12 | StorageService->-Client2: ok 13 | -------------------------------------------------------------------------------- /images/locks-basic-sequence-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpringOnePlatform2016/dsyer-locks-and-leaders/b0e9f3210df8a7e1c29a3b1e4a611bb0115822f4/images/locks-basic-sequence-3.png -------------------------------------------------------------------------------- /images/locks-basic-sequence-3.wsd: -------------------------------------------------------------------------------- 1 | participant Client1 2 | participant Client2 3 | Client1->StorageService: read 4 | Client2->StorageService: read 5 | Client1->StorageService: starting 6 | Client1->Webhook: ping 7 | Client2->StorageService: starting 8 | Client2->Webhook: ping 9 | Client1->+StorageService: success 10 | StorageService->-Client1: ok 11 | Client2->+StorageService: success 12 | StorageService->-Client2: ok 13 | -------------------------------------------------------------------------------- /images/locks-basic-sequence-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpringOnePlatform2016/dsyer-locks-and-leaders/b0e9f3210df8a7e1c29a3b1e4a611bb0115822f4/images/locks-basic-sequence-4.png -------------------------------------------------------------------------------- /images/locks-basic-sequence-4.wsd: -------------------------------------------------------------------------------- 1 | participant Client1 2 | participant Client2 3 | Client1->StorageService: read 4 | Client2->StorageService: read 5 | Client1->StorageService: starting 6 | Client2->StorageService: starting 7 | Client2->Webhook: ping 8 | Client2->+StorageService: success 9 | StorageService->-Client2: ok 10 | Client1->Webhook: ping 11 | Client1->+StorageService: success 12 | StorageService->-Client1: ok 13 | -------------------------------------------------------------------------------- /images/locks-basic-sequence-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpringOnePlatform2016/dsyer-locks-and-leaders/b0e9f3210df8a7e1c29a3b1e4a611bb0115822f4/images/locks-basic-sequence-5.png -------------------------------------------------------------------------------- /images/locks-basic-sequence-5.wsd: -------------------------------------------------------------------------------- 1 | participant Client1 2 | participant Client2 3 | Client1->StorageService: read 4 | Client2->StorageService: read 5 | Client1->StorageService: starting 6 | Client2->StorageService: starting 7 | Client2->Webhook: ping 8 | Client1->Webhook: ping 9 | Client1->+StorageService: success 10 | Client2->+StorageService: success 11 | StorageService->-Client1: ok 12 | StorageService->-Client2: ok 13 | -------------------------------------------------------------------------------- /images/writing-stale-data.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SpringOnePlatform2016/dsyer-locks-and-leaders/b0e9f3210df8a7e1c29a3b1e4a611bb0115822f4/images/writing-stale-data.png -------------------------------------------------------------------------------- /images/writing-stale-data.txt: -------------------------------------------------------------------------------- 1 | title Writing Stale Data 2 | 3 | Client1->+LockService: getLock 4 | LockService->Client1: lock 5 | Client1-->+Client1: GC start 6 | LockService->-Client1: expire 7 | Client2->+LockService: getLock 8 | LockService->Client2: lock 9 | Client2->+StorageService: write 10 | StorageService->-Client2: ok 11 | Client1-->-Client1: GC end 12 | Client1->+StorageService: write 13 | note over StorageService: stale data 14 | StorageService->-Client1: ok 15 | 16 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # 58 | # Look for the Apple JDKs first to preserve the existing behaviour, and then look 59 | # for the new JDKs provided by Oracle. 60 | # 61 | if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then 62 | # 63 | # Apple JDKs 64 | # 65 | export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home 66 | fi 67 | 68 | if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then 69 | # 70 | # Apple JDKs 71 | # 72 | export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home 73 | fi 74 | 75 | if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then 76 | # 77 | # Oracle JDKs 78 | # 79 | export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home 80 | fi 81 | 82 | if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then 83 | # 84 | # Apple JDKs 85 | # 86 | export JAVA_HOME=`/usr/libexec/java_home` 87 | fi 88 | ;; 89 | esac 90 | 91 | if [ -z "$JAVA_HOME" ] ; then 92 | if [ -r /etc/gentoo-release ] ; then 93 | JAVA_HOME=`java-config --jre-home` 94 | fi 95 | fi 96 | 97 | if [ -z "$M2_HOME" ] ; then 98 | ## resolve links - $0 may be a link to maven's home 99 | PRG="$0" 100 | 101 | # need this for relative symlinks 102 | while [ -h "$PRG" ] ; do 103 | ls=`ls -ld "$PRG"` 104 | link=`expr "$ls" : '.*-> \(.*\)$'` 105 | if expr "$link" : '/.*' > /dev/null; then 106 | PRG="$link" 107 | else 108 | PRG="`dirname "$PRG"`/$link" 109 | fi 110 | done 111 | 112 | saveddir=`pwd` 113 | 114 | M2_HOME=`dirname "$PRG"`/.. 115 | 116 | # make it fully qualified 117 | M2_HOME=`cd "$M2_HOME" && pwd` 118 | 119 | cd "$saveddir" 120 | # echo Using m2 at $M2_HOME 121 | fi 122 | 123 | # For Cygwin, ensure paths are in UNIX format before anything is touched 124 | if $cygwin ; then 125 | [ -n "$M2_HOME" ] && 126 | M2_HOME=`cygpath --unix "$M2_HOME"` 127 | [ -n "$JAVA_HOME" ] && 128 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 129 | [ -n "$CLASSPATH" ] && 130 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 131 | fi 132 | 133 | # For Migwn, ensure paths are in UNIX format before anything is touched 134 | if $mingw ; then 135 | [ -n "$M2_HOME" ] && 136 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 137 | [ -n "$JAVA_HOME" ] && 138 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 139 | # TODO classpath? 140 | fi 141 | 142 | if [ -z "$JAVA_HOME" ]; then 143 | javaExecutable="`which javac`" 144 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 145 | # readlink(1) is not available as standard on Solaris 10. 146 | readLink=`which readlink` 147 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 148 | if $darwin ; then 149 | javaHome="`dirname \"$javaExecutable\"`" 150 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 151 | else 152 | javaExecutable="`readlink -f \"$javaExecutable\"`" 153 | fi 154 | javaHome="`dirname \"$javaExecutable\"`" 155 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 156 | JAVA_HOME="$javaHome" 157 | export JAVA_HOME 158 | fi 159 | fi 160 | fi 161 | 162 | if [ -z "$JAVACMD" ] ; then 163 | if [ -n "$JAVA_HOME" ] ; then 164 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 165 | # IBM's JDK on AIX uses strange locations for the executables 166 | JAVACMD="$JAVA_HOME/jre/sh/java" 167 | else 168 | JAVACMD="$JAVA_HOME/bin/java" 169 | fi 170 | else 171 | JAVACMD="`which java`" 172 | fi 173 | fi 174 | 175 | if [ ! -x "$JAVACMD" ] ; then 176 | echo "Error: JAVA_HOME is not defined correctly." >&2 177 | echo " We cannot execute $JAVACMD" >&2 178 | exit 1 179 | fi 180 | 181 | if [ -z "$JAVA_HOME" ] ; then 182 | echo "Warning: JAVA_HOME environment variable is not set." 183 | fi 184 | 185 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 186 | 187 | # For Cygwin, switch paths to Windows format before running java 188 | if $cygwin; then 189 | [ -n "$M2_HOME" ] && 190 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 191 | [ -n "$JAVA_HOME" ] && 192 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 193 | [ -n "$CLASSPATH" ] && 194 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 195 | fi 196 | 197 | # traverses directory structure from process work directory to filesystem root 198 | # first directory with .mvn subdirectory is considered project base directory 199 | find_maven_basedir() { 200 | local basedir=$(pwd) 201 | local wdir=$(pwd) 202 | while [ "$wdir" != '/' ] ; do 203 | if [ -d "$wdir"/.mvn ] ; then 204 | basedir=$wdir 205 | break 206 | fi 207 | wdir=$(cd "$wdir/.."; pwd) 208 | done 209 | echo "${basedir}" 210 | } 211 | 212 | # concatenates all lines of a file 213 | concat_lines() { 214 | if [ -f "$1" ]; then 215 | echo "$(tr -s '\n' ' ' < "$1")" 216 | fi 217 | } 218 | 219 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} 220 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 221 | 222 | # Provide a "standardized" way to retrieve the CLI args that will 223 | # work with both Windows and non-Windows executions. 224 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 225 | export MAVEN_CMD_LINE_ARGS 226 | 227 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 228 | 229 | exec "$JAVACMD" \ 230 | $MAVEN_OPTS \ 231 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 232 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 233 | ${WRAPPER_LAUNCHER} "$@" 234 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | set MAVEN_CMD_LINE_ARGS=%* 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | 121 | set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" 122 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 123 | 124 | %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% 125 | if ERRORLEVEL 1 goto error 126 | goto end 127 | 128 | :error 129 | set ERROR_CODE=1 130 | 131 | :end 132 | @endlocal & set ERROR_CODE=%ERROR_CODE% 133 | 134 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 135 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 136 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 137 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 138 | :skipRcPost 139 | 140 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 141 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 142 | 143 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 144 | 145 | exit /B %ERROR_CODE% -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 1.3.5.RELEASE 9 | 10 | 11 | com.example 12 | parent-demo 13 | 0.0.1-SNAPSHOT 14 | pom 15 | Parent Demo 16 | 17 | 18 | cron-service-leader 19 | cron-service-locks 20 | cron-service-optimist 21 | 22 | 23 | 24 | 1.8 25 | 26 | 27 | 28 | 29 | spring-libs-snapshot 30 | http://repo.spring.io/libs-snapshot 31 | 32 | true 33 | 34 | 35 | true 36 | 37 | 38 | 39 | 40 | 41 | 42 | spring-libs-snapshot 43 | http://repo.spring.io/libs-snapshot 44 | 45 | true 46 | 47 | 48 | true 49 | 50 | 51 | 52 | 53 | 54 | --------------------------------------------------------------------------------