├── .gitignore ├── LICENSE ├── README.md ├── doc └── img │ ├── 使用示例.png │ └── 锁超时处理逻辑.jpg ├── pom.xml └── src ├── main ├── java │ └── org │ │ └── springframework │ │ └── boot │ │ └── autoconfigure │ │ └── klock │ │ ├── KlockAutoConfiguration.java │ │ ├── KlockConfiguration.java │ │ ├── annotation │ │ ├── Klock.java │ │ └── KlockKey.java │ │ ├── config │ │ └── KlockConfig.java │ │ ├── core │ │ ├── BusinessKeyProvider.java │ │ ├── KlockAspectHandler.java │ │ └── LockInfoProvider.java │ │ ├── handler │ │ ├── KlockInvocationException.java │ │ ├── KlockTimeoutException.java │ │ ├── lock │ │ │ └── LockTimeoutHandler.java │ │ └── release │ │ │ └── ReleaseTimeoutHandler.java │ │ ├── lock │ │ ├── FairLock.java │ │ ├── Lock.java │ │ ├── LockFactory.java │ │ ├── ReadLock.java │ │ ├── ReentrantLock.java │ │ └── WriteLock.java │ │ └── model │ │ ├── LockInfo.java │ │ ├── LockTimeoutStrategy.java │ │ ├── LockType.java │ │ └── ReleaseTimeoutStrategy.java └── resources │ └── META-INF │ ├── spring.factories │ └── spring │ └── org.springframework.boot.autoconfigure.AutoConfiguration.imports └── test ├── java └── org │ └── springframework │ └── boot │ └── autoconfigure │ └── klock │ └── test │ ├── KlockTestApplication.java │ ├── KlockTests.java │ ├── TestService.java │ ├── TimeoutService.java │ └── User.java └── resources └── application.properties /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ 26 | 27 | # for Mac OS X System Files 28 | .DS_Store 29 | Thumbs.db 30 | 31 | # Compiled class file 32 | *.class 33 | 34 | # Log file 35 | *.log 36 | 37 | # BlueJ files 38 | *.ctxt 39 | 40 | # Mobile Tools for Java (J2ME) 41 | .mtj.tmp/ 42 | 43 | # Package Files # 44 | *.jar 45 | *.war 46 | *.ear 47 | *.zip 48 | *.tar.gz 49 | *.rar 50 | 51 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 52 | hs_err_pid* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spring-boot-klock-starter 2 | 基于redis的分布式锁spring-boot starter组件,使得项目拥有分布式锁能力变得异常简单,支持spring boot,和spirng mvc等spring相关项目 3 | 4 | 5 | # 快速开始 6 | 7 | > spring boot项目接入 8 | 9 | 10 | 1.添加klock starter组件依赖 11 | ``` 12 | 13 | cn.keking 14 | spring-boot-klock-starter 15 | 1.5-RELEASE 16 | 17 | 18 | ``` 19 | 20 | 2.application.properties配置redis链接:`spring.klock.address=redis://127.0.0.1:6379` 21 | 22 | 23 | 3.在需要加分布式锁的方法上,添加注解@Klock,如: 24 | ```java 25 | @Service 26 | public class TestService { 27 | 28 | @Klock(waitTime = Long.MAX_VALUE) 29 | public String getValue(String param) throws Exception { 30 | if ("sleep".equals(param)) {//线程休眠或者断点阻塞,达到一直占用锁的测试效果 31 | Thread.sleep(1000 * 50); 32 | } 33 | return "success"; 34 | } 35 | } 36 | 37 | ``` 38 | 39 | 4.支持锁指定的业务key,如同一个方法ID入参相同的加锁,其他的放行。业务key的获取支持Spel,具体使用方式如下 40 | ![使用示例](./doc/img/使用示例.png "使用示例.png") 41 | 42 | 43 | 44 | > spring mvc项目接入 45 | 46 | 其他步骤和spring boot步骤一样,只需要spring-xx.xml配置中添加KlockAutoConfiguration类扫描即可,如: 47 | ```xml 48 | 49 | ``` 50 | 51 | # 使用参数说明 52 | 53 | > 配置参数说明 54 | 55 | ```properties 56 | spring.klock.address : redis链接地址 如 redis://127.0.0.1:6379 57 | spring.klock.password : redis密码 58 | spring.klock.database : redis数据索引 59 | spring.klock.waitTime : 获取锁最长阻塞时间(默认:60,单位:秒) 60 | spring.klock.leaseTime: 已获取锁后自动释放时间(默认:60,单位:秒) 61 | spring.klock.cluster-server.node-addresses : redis集群配置 如 redis://127.0.0.1:7000,redis://127.0.0.1:7001,redis://127.0.0.1:7002 62 | #spring.klock.address 和 spring.klock.cluster-server.node-addresses 选其一即可 63 | ``` 64 | > @Klock注解参数说明 65 | 66 | @Klock可以标注四个参数,作用分别如下 67 | name:lock的name,对应redis的key值。默认为:类名+方法名 68 | lockType:锁的类型,目前支持(可重入锁,公平锁,读写锁)。默认为:公平锁 69 | waitTime:获取锁最长等待时间。默认为:60s。同时也可通过spring.klock.waitTime统一配置 70 | leaseTime:获得锁后,自动释放锁的时间。默认为:60s。同时也可通过spring.klock.leaseTime统一配置 71 | lockTimeoutStrategy: 加锁超时的处理策略,可配置为不做处理、快速失败、阻塞等待的处理策略,默认策略为不做处理 72 | 73 | customLockTimeoutStrategy: 自定义加锁超时的处理策略,需指定自定义处理的方法的方法名,并保持入参一致 74 | releaseTimeoutStrategy: 释放锁时,持有的锁已超时的处理策略,可配置为不做处理、快速失败的处理策略,默认策略为不做处理 75 | customReleaseTimeoutStrategy: 自定义释放锁时,需指定自定义处理的方法的方法名,并保持入参一致 76 | 77 | # 锁超时说明 78 | 因为基于redis实现分布式锁,如果使用不当,会在以下场景下遇到锁超时的问题: 79 | ![锁超时处理逻辑](./doc/img/锁超时处理逻辑.jpg "锁超时处理逻辑.jpg") 80 | 81 | 加锁超时处理策略(**LockTimeoutStrategy**): 82 | - **NO_OPERATION** 不做处理,继续执行业务逻辑 83 | - **FAIL_FAST** 快速失败,会抛出KlockTimeoutException 84 | - **KEEP_ACQUIRE** 阻塞等待,一直阻塞,直到获得锁,但在太多的尝试后,会停止获取锁并报错,此时很有可能是发生了死锁。 85 | - **自定义(customLockTimeoutStrategy)** 需指定自定义处理的方法的方法名,并保持入参一致,指定自定义处理方法后,会覆盖上述三种策略,且会拦截业务逻辑的运行。 86 | 87 | 释放锁时超时处理策略(**ReleaseTimeoutStrategy**): 88 | - **NO_OPERATION** 不做处理,继续执行业务逻辑 89 | - **FAIL_FAST** 快速失败,会抛出KlockTimeoutException 90 | - **自定义(customReleaseTimeoutStrategy)** 需指定自定义处理的方法的方法名,并保持入参一致,指定自定义处理方法后,会覆盖上述两种策略, 执行自定义处理方法时,业务逻辑已经执行完毕,会在方法返回前和throw异常前执行。 91 | 92 | **希望使用者清楚的意识到,如果没有对加锁超时进行有效设置,那么设置释放锁时超时处理策略是没有意义的。** 93 | 94 | *在测试模块中已集成锁超时策略的使用用例* 95 | # 关于测试 96 | 工程test模块下,为分布式锁的测试模块。可以快速体验分布式锁的效果。 97 | 98 | # 使用登记 99 | 如果这个项目解决了你的实际问题,可在 https://gitee.com/kekingcn/spring-boot-klock-starter/issues/IH4NE 登记下,如果节省了你的研发时间,也愿意支持下的话,可点击下方【捐助】请作者喝杯咖啡,也是非常感谢 100 | -------------------------------------------------------------------------------- /doc/img/使用示例.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kekingcn/spring-boot-klock-starter/8700bc0f1512e501845c30127cdcb4c66c6aceea/doc/img/使用示例.png -------------------------------------------------------------------------------- /doc/img/锁超时处理逻辑.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kekingcn/spring-boot-klock-starter/8700bc0f1512e501845c30127cdcb4c66c6aceea/doc/img/锁超时处理逻辑.jpg -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | cn.keking 8 | spring-boot-klock-starter 9 | 1.5-RELEASE 10 | spring-boot-klock-starter 11 | The kLock Project 12 | https://github.com/kekingcn/spring-boot-klock-starter 13 | 14 | 15 | 1.5.6.RELEASE 16 | 3.18.0 17 | 3.10.1 18 | 3.2.1 19 | 3.4.1 20 | 3.0.1 21 | UTF-8 22 | UTF-8 23 | 1.8 24 | 25 | 26 | 27 | 28 | Apache 2 29 | http://www.apache.org/licenses/LICENSE-2.0.txt 30 | 31 | 32 | 33 | 34 | https://github.com/kekingcn/spring-boot-klock-starter 35 | scm:git:https://github.com/kekingcn/spring-boot-klock-starter.git 36 | scm:git:https://github.com/kekingcn/spring-boot-klock-starter.git 37 | HEAD 38 | 39 | 40 | 41 | 42 | kl 43 | 632104866@qq.com 44 | 凯京集团 45 | https://www.keking.com/ 46 | http://www.kailing.pub/ 47 | 48 | 49 | 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-configuration-processor 54 | ${spring-boot.version} 55 | true 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-autoconfigure 60 | ${spring-boot.version} 61 | 62 | 63 | org.springframework.boot 64 | spring-boot-starter-test 65 | ${spring-boot.version} 66 | test 67 | 68 | 69 | org.springframework.boot 70 | spring-boot-starter-web 71 | ${spring-boot.version} 72 | true 73 | test 74 | 75 | 76 | org.springframework.boot 77 | spring-boot-starter 78 | ${spring-boot.version} 79 | true 80 | test 81 | 82 | 83 | org.springframework.boot 84 | spring-boot-starter-aop 85 | ${spring-boot.version} 86 | 87 | 88 | org.redisson 89 | redisson 90 | ${redisson.version} 91 | 92 | 93 | 94 | 95 | 96 | sonatype-nexus-snapshots 97 | Sonatype Nexus Snapshots 98 | https://oss.sonatype.org/content/repositories/snapshots/ 99 | 100 | 101 | sonatype-nexus-staging 102 | Nexus Release Repository 103 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 104 | 105 | 106 | 107 | 108 | 109 | 110 | org.apache.maven.plugins 111 | maven-compiler-plugin 112 | ${maven-compiler-plugin.version} 113 | 114 | ${project.build.sourceEncoding} 115 | ${java.version} 116 | ${java.version} 117 | true 118 | 119 | 120 | 121 | org.apache.maven.plugins 122 | maven-source-plugin 123 | ${maven-source-plugin.version} 124 | 125 | 126 | attach-sources 127 | 128 | jar-no-fork 129 | 130 | 131 | 132 | 133 | 134 | org.apache.maven.plugins 135 | maven-javadoc-plugin 136 | ${maven-javadoc-plugin.version} 137 | 138 | 139 | attach-javadocs 140 | 141 | jar 142 | 143 | 144 | 145 | 146 | 147 | org.apache.maven.plugins 148 | maven-gpg-plugin 149 | ${maven-gpg-plugin.version} 150 | 151 | 152 | sign-artifacts 153 | verify 154 | 155 | sign 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/KlockAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock; 2 | 3 | import io.netty.channel.nio.NioEventLoopGroup; 4 | import org.redisson.Redisson; 5 | import org.redisson.api.RedissonClient; 6 | import org.redisson.client.codec.Codec; 7 | import org.redisson.config.Config; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.autoconfigure.AutoConfigureAfter; 10 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 11 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 12 | import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; 13 | import org.springframework.boot.autoconfigure.klock.config.KlockConfig; 14 | import org.springframework.boot.autoconfigure.klock.core.BusinessKeyProvider; 15 | import org.springframework.boot.autoconfigure.klock.core.KlockAspectHandler; 16 | import org.springframework.boot.autoconfigure.klock.core.LockInfoProvider; 17 | import org.springframework.boot.autoconfigure.klock.lock.LockFactory; 18 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 19 | import org.springframework.context.annotation.Bean; 20 | import org.springframework.context.annotation.Configuration; 21 | import org.springframework.context.annotation.Import; 22 | import org.springframework.util.ClassUtils; 23 | 24 | /** 25 | * 26 | * @author kl 27 | * @since 2017/12/29 28 | * Content :klock自动装配 29 | */ 30 | @Configuration 31 | @ConditionalOnProperty(prefix = KlockConfig.PREFIX, name = "enable", havingValue = "true", matchIfMissing = true) 32 | @AutoConfigureAfter(RedisAutoConfiguration.class) 33 | @EnableConfigurationProperties(KlockConfig.class) 34 | @Import({KlockAspectHandler.class}) 35 | public class KlockAutoConfiguration { 36 | 37 | @Autowired 38 | private KlockConfig klockConfig; 39 | 40 | @Bean(destroyMethod = "shutdown") 41 | @ConditionalOnMissingBean 42 | RedissonClient redisson() throws Exception { 43 | Config config = new Config(); 44 | if(klockConfig.getClusterServer()!=null){ 45 | config.useClusterServers().setPassword(klockConfig.getPassword()) 46 | .addNodeAddress(klockConfig.getClusterServer().getNodeAddresses()); 47 | }else { 48 | config.useSingleServer().setAddress(klockConfig.getAddress()) 49 | .setDatabase(klockConfig.getDatabase()) 50 | .setPassword(klockConfig.getPassword()); 51 | } 52 | config.setEventLoopGroup(new NioEventLoopGroup()); 53 | return Redisson.create(config); 54 | } 55 | 56 | @Bean 57 | public LockInfoProvider lockInfoProvider(){ 58 | return new LockInfoProvider(); 59 | } 60 | 61 | @Bean 62 | public BusinessKeyProvider businessKeyProvider(){ 63 | return new BusinessKeyProvider(); 64 | } 65 | 66 | @Bean 67 | public LockFactory lockFactory(){ 68 | return new LockFactory(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/KlockConfiguration.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock; 2 | 3 | import org.springframework.boot.autoconfigure.klock.config.KlockConfig; 4 | import org.springframework.boot.autoconfigure.klock.core.BusinessKeyProvider; 5 | import org.springframework.boot.autoconfigure.klock.core.KlockAspectHandler; 6 | import org.springframework.boot.autoconfigure.klock.core.LockInfoProvider; 7 | import org.springframework.boot.autoconfigure.klock.lock.LockFactory; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.context.annotation.Import; 11 | 12 | /** 13 | * Created by kl on 2017/12/29. 14 | * Content :适用于内部低版本spring mvc项目配置,redisson外化配置 15 | */ 16 | @Configuration 17 | @Import({KlockAspectHandler.class}) 18 | public class KlockConfiguration { 19 | @Bean 20 | public LockInfoProvider lockInfoProvider(){ 21 | return new LockInfoProvider(); 22 | } 23 | 24 | @Bean 25 | public BusinessKeyProvider businessKeyProvider(){ 26 | return new BusinessKeyProvider(); 27 | } 28 | 29 | @Bean 30 | public LockFactory lockFactory(){ 31 | return new LockFactory(); 32 | } 33 | @Bean 34 | public KlockConfig klockConfig(){ 35 | return new KlockConfig(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/annotation/Klock.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.annotation; 2 | 3 | import org.springframework.boot.autoconfigure.klock.model.LockTimeoutStrategy; 4 | import org.springframework.boot.autoconfigure.klock.model.LockType; 5 | import org.springframework.boot.autoconfigure.klock.model.ReleaseTimeoutStrategy; 6 | 7 | import java.lang.annotation.ElementType; 8 | import java.lang.annotation.Retention; 9 | import java.lang.annotation.RetentionPolicy; 10 | import java.lang.annotation.Target; 11 | 12 | /** 13 | * 14 | * @author kl 15 | * @since 2017/12/29 16 | * Content :加锁注解 17 | */ 18 | @Target(value = {ElementType.METHOD}) 19 | @Retention(value = RetentionPolicy.RUNTIME) 20 | public @interface Klock { 21 | /** 22 | * 锁的名称 23 | * @return name 24 | */ 25 | String name() default ""; 26 | /** 27 | * 锁类型,默认可重入锁 28 | * @return lockType 29 | */ 30 | LockType lockType() default LockType.Reentrant; 31 | /** 32 | * 尝试加锁,最多等待时间 33 | * @return waitTime 34 | */ 35 | long waitTime() default Long.MIN_VALUE; 36 | /** 37 | *上锁以后xxx秒自动解锁 38 | * @return leaseTime 39 | */ 40 | long leaseTime() default Long.MIN_VALUE; 41 | 42 | /** 43 | * 自定义业务key 44 | * @return keys 45 | */ 46 | String [] keys() default {}; 47 | 48 | /** 49 | * 加锁超时的处理策略 50 | * @return lockTimeoutStrategy 51 | */ 52 | LockTimeoutStrategy lockTimeoutStrategy() default LockTimeoutStrategy.NO_OPERATION; 53 | 54 | /** 55 | * 自定义加锁超时的处理策略 56 | * @return customLockTimeoutStrategy 57 | */ 58 | String customLockTimeoutStrategy() default ""; 59 | 60 | /** 61 | * 释放锁时已超时的处理策略 62 | * @return releaseTimeoutStrategy 63 | */ 64 | ReleaseTimeoutStrategy releaseTimeoutStrategy() default ReleaseTimeoutStrategy.NO_OPERATION; 65 | 66 | /** 67 | * 自定义释放锁时已超时的处理策略 68 | * @return customReleaseTimeoutStrategy 69 | */ 70 | String customReleaseTimeoutStrategy() default ""; 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/annotation/KlockKey.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * 10 | * @author kl 11 | * @since 2018/1/24 12 | * Content : 13 | */ 14 | @Target(value = {ElementType.PARAMETER, ElementType.TYPE}) 15 | @Retention(value = RetentionPolicy.RUNTIME) 16 | public @interface KlockKey { 17 | String value() default ""; 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/config/KlockConfig.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.config; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | /** 6 | * Created by kl on 2017/12/29. 7 | */ 8 | @ConfigurationProperties(prefix = KlockConfig.PREFIX) 9 | public class KlockConfig { 10 | 11 | public static final String PREFIX = "spring.klock"; 12 | //redisson 13 | private String address; 14 | private String password; 15 | private int database=15; 16 | private ClusterServer clusterServer; 17 | private long waitTime = 60; 18 | private long leaseTime = 60; 19 | 20 | public String getAddress() { 21 | return address; 22 | } 23 | 24 | public void setAddress(String address) { 25 | this.address = address; 26 | } 27 | 28 | public String getPassword() { 29 | return password; 30 | } 31 | 32 | public void setPassword(String password) { 33 | this.password = password; 34 | } 35 | 36 | public long getWaitTime() { 37 | return waitTime; 38 | } 39 | 40 | public void setWaitTime(long waitTime) { 41 | this.waitTime = waitTime; 42 | } 43 | 44 | public long getLeaseTime() { 45 | return leaseTime; 46 | } 47 | 48 | public void setLeaseTime(long leaseTime) { 49 | this.leaseTime = leaseTime; 50 | } 51 | 52 | public int getDatabase() { 53 | return database; 54 | } 55 | 56 | public void setDatabase(int database) { 57 | this.database = database; 58 | } 59 | 60 | public ClusterServer getClusterServer() { 61 | return clusterServer; 62 | } 63 | 64 | public void setClusterServer(ClusterServer clusterServer) { 65 | this.clusterServer = clusterServer; 66 | } 67 | 68 | public static class ClusterServer{ 69 | 70 | private String[] nodeAddresses; 71 | 72 | public String[] getNodeAddresses() { 73 | return nodeAddresses; 74 | } 75 | 76 | public void setNodeAddresses(String[] nodeAddresses) { 77 | this.nodeAddresses = nodeAddresses; 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/core/BusinessKeyProvider.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.core; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.aspectj.lang.ProceedingJoinPoint; 5 | import org.aspectj.lang.reflect.MethodSignature; 6 | import org.springframework.boot.autoconfigure.klock.annotation.Klock; 7 | import org.springframework.boot.autoconfigure.klock.annotation.KlockKey; 8 | import org.springframework.context.expression.MethodBasedEvaluationContext; 9 | import org.springframework.core.DefaultParameterNameDiscoverer; 10 | import org.springframework.core.ParameterNameDiscoverer; 11 | import org.springframework.expression.EvaluationContext; 12 | import org.springframework.expression.ExpressionParser; 13 | import org.springframework.expression.spel.standard.SpelExpressionParser; 14 | import org.springframework.expression.spel.support.StandardEvaluationContext; 15 | import org.springframework.util.ObjectUtils; 16 | import org.springframework.util.StringUtils; 17 | 18 | import java.lang.reflect.Method; 19 | import java.lang.reflect.Parameter; 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | 23 | /** 24 | * Created by kl on 2018/1/24. 25 | * Content :获取用户定义业务key 26 | */ 27 | public class BusinessKeyProvider { 28 | 29 | private ParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer(); 30 | 31 | private ExpressionParser parser = new SpelExpressionParser(); 32 | 33 | public String getKeyName(JoinPoint joinPoint, Klock klock) { 34 | List keyList = new ArrayList<>(); 35 | Method method = getMethod(joinPoint); 36 | List definitionKeys = getSpelDefinitionKey(klock.keys(), method, joinPoint.getArgs()); 37 | keyList.addAll(definitionKeys); 38 | List parameterKeys = getParameterKey(method.getParameters(), joinPoint.getArgs()); 39 | keyList.addAll(parameterKeys); 40 | return StringUtils.collectionToDelimitedString(keyList,"","-",""); 41 | } 42 | 43 | private Method getMethod(JoinPoint joinPoint) { 44 | MethodSignature signature = (MethodSignature) joinPoint.getSignature(); 45 | Method method = signature.getMethod(); 46 | if (method.getDeclaringClass().isInterface()) { 47 | try { 48 | method = joinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(), 49 | method.getParameterTypes()); 50 | } catch (Exception e) { 51 | e.printStackTrace(); 52 | } 53 | } 54 | return method; 55 | } 56 | 57 | private List getSpelDefinitionKey(String[] definitionKeys, Method method, Object[] parameterValues) { 58 | List definitionKeyList = new ArrayList<>(); 59 | for (String definitionKey : definitionKeys) { 60 | if (!ObjectUtils.isEmpty(definitionKey)) { 61 | EvaluationContext context = new MethodBasedEvaluationContext(null, method, parameterValues, nameDiscoverer); 62 | Object objKey = parser.parseExpression(definitionKey).getValue(context); 63 | definitionKeyList.add(ObjectUtils.nullSafeToString(objKey)); 64 | } 65 | } 66 | return definitionKeyList; 67 | } 68 | 69 | private List getParameterKey(Parameter[] parameters, Object[] parameterValues) { 70 | List parameterKey = new ArrayList<>(); 71 | for (int i = 0; i < parameters.length; i++) { 72 | if (parameters[i].getAnnotation(KlockKey.class) != null) { 73 | KlockKey keyAnnotation = parameters[i].getAnnotation(KlockKey.class); 74 | if (keyAnnotation.value().isEmpty()) { 75 | Object parameterValue = parameterValues[i]; 76 | parameterKey.add(ObjectUtils.nullSafeToString(parameterValue)); 77 | } else { 78 | StandardEvaluationContext context = new StandardEvaluationContext(parameterValues[i]); 79 | Object key = parser.parseExpression(keyAnnotation.value()).getValue(context); 80 | parameterKey.add(ObjectUtils.nullSafeToString(key)); 81 | } 82 | } 83 | } 84 | return parameterKey; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/core/KlockAspectHandler.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.core; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.aspectj.lang.ProceedingJoinPoint; 5 | import org.aspectj.lang.annotation.AfterReturning; 6 | import org.aspectj.lang.annotation.AfterThrowing; 7 | import org.aspectj.lang.annotation.Around; 8 | import org.aspectj.lang.annotation.Aspect; 9 | import org.aspectj.lang.reflect.MethodSignature; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.boot.autoconfigure.klock.annotation.Klock; 14 | import org.springframework.boot.autoconfigure.klock.handler.KlockInvocationException; 15 | import org.springframework.boot.autoconfigure.klock.lock.Lock; 16 | import org.springframework.boot.autoconfigure.klock.lock.LockFactory; 17 | import org.springframework.boot.autoconfigure.klock.model.LockInfo; 18 | import org.springframework.core.annotation.Order; 19 | import org.springframework.stereotype.Component; 20 | import org.springframework.util.StringUtils; 21 | 22 | import java.lang.reflect.InvocationTargetException; 23 | import java.lang.reflect.Method; 24 | import java.util.Map; 25 | import java.util.Objects; 26 | import java.util.concurrent.ConcurrentHashMap; 27 | 28 | /** 29 | * Created by kl on 2017/12/29. 30 | * Content :给添加@KLock切面加锁处理 31 | */ 32 | @Aspect 33 | @Component 34 | @Order(0) 35 | public class KlockAspectHandler { 36 | 37 | private static final Logger logger = LoggerFactory.getLogger(KlockAspectHandler.class); 38 | 39 | @Autowired 40 | LockFactory lockFactory; 41 | 42 | @Autowired 43 | private LockInfoProvider lockInfoProvider; 44 | 45 | private final Map currentThreadLock = new ConcurrentHashMap<>(); 46 | 47 | 48 | @Around(value = "@annotation(klock)") 49 | public Object around(ProceedingJoinPoint joinPoint, Klock klock) throws Throwable { 50 | LockInfo lockInfo = lockInfoProvider.get(joinPoint,klock); 51 | String curentLock = this.getCurrentLockId(joinPoint,klock); 52 | currentThreadLock.put(curentLock,new LockRes(lockInfo, false)); 53 | Lock lock = lockFactory.getLock(lockInfo); 54 | boolean lockRes = lock.acquire(); 55 | 56 | //如果获取锁失败了,则进入失败的处理逻辑 57 | if(!lockRes) { 58 | if(logger.isWarnEnabled()) { 59 | logger.warn("Timeout while acquiring Lock({})", lockInfo.getName()); 60 | } 61 | //如果自定义了获取锁失败的处理策略,则执行自定义的降级处理策略 62 | if(!StringUtils.isEmpty(klock.customLockTimeoutStrategy())) { 63 | 64 | return handleCustomLockTimeout(klock.customLockTimeoutStrategy(), joinPoint); 65 | 66 | } else { 67 | //否则执行预定义的执行策略 68 | //注意:如果没有指定预定义的策略,默认的策略为静默啥不做处理 69 | klock.lockTimeoutStrategy().handle(lockInfo, lock, joinPoint); 70 | } 71 | } 72 | 73 | currentThreadLock.get(curentLock).setLock(lock); 74 | currentThreadLock.get(curentLock).setRes(true); 75 | 76 | return joinPoint.proceed(); 77 | } 78 | 79 | @AfterReturning(value = "@annotation(klock)") 80 | public void afterReturning(JoinPoint joinPoint, Klock klock) throws Throwable { 81 | String curentLock = this.getCurrentLockId(joinPoint,klock); 82 | releaseLock(klock, joinPoint,curentLock); 83 | cleanUpThreadLocal(curentLock); 84 | } 85 | 86 | @AfterThrowing(value = "@annotation(klock)", throwing = "ex") 87 | public void afterThrowing (JoinPoint joinPoint, Klock klock, Throwable ex) throws Throwable { 88 | String curentLock = this.getCurrentLockId(joinPoint,klock); 89 | releaseLock(klock, joinPoint,curentLock); 90 | cleanUpThreadLocal(curentLock); 91 | throw ex; 92 | } 93 | 94 | /** 95 | * 处理自定义加锁超时 96 | */ 97 | private Object handleCustomLockTimeout(String lockTimeoutHandler, JoinPoint joinPoint) throws Throwable { 98 | 99 | // prepare invocation context 100 | Method currentMethod = ((MethodSignature)joinPoint.getSignature()).getMethod(); 101 | Object target = joinPoint.getTarget(); 102 | Method handleMethod = null; 103 | try { 104 | handleMethod = joinPoint.getTarget().getClass().getDeclaredMethod(lockTimeoutHandler, currentMethod.getParameterTypes()); 105 | handleMethod.setAccessible(true); 106 | } catch (NoSuchMethodException e) { 107 | throw new IllegalArgumentException("Illegal annotation param customLockTimeoutStrategy",e); 108 | } 109 | Object[] args = joinPoint.getArgs(); 110 | 111 | // invoke 112 | Object res = null; 113 | try { 114 | res = handleMethod.invoke(target, args); 115 | } catch (IllegalAccessException e) { 116 | throw new KlockInvocationException("Fail to invoke custom lock timeout handler: " + lockTimeoutHandler ,e); 117 | } catch (InvocationTargetException e) { 118 | throw e.getTargetException(); 119 | } 120 | 121 | return res; 122 | } 123 | 124 | /** 125 | * 释放锁 126 | */ 127 | private void releaseLock(Klock klock, JoinPoint joinPoint,String curentLock) throws Throwable { 128 | LockRes lockRes = currentThreadLock.get(curentLock); 129 | if(Objects.isNull(lockRes)){ 130 | throw new NullPointerException("Please check whether the input parameter used as the lock key value has been modified in the method, which will cause the acquire and release locks to have different key values and throw null pointers.curentLockKey:" + curentLock); 131 | } 132 | if (lockRes.getRes()) { 133 | boolean releaseRes = currentThreadLock.get(curentLock).getLock().release(); 134 | // avoid release lock twice when exception happens below 135 | lockRes.setRes(false); 136 | if (!releaseRes) { 137 | handleReleaseTimeout(klock, lockRes.getLockInfo(), joinPoint); 138 | } 139 | } 140 | } 141 | 142 | // avoid memory leak 143 | private void cleanUpThreadLocal(String curentLock) { 144 | currentThreadLock.remove(curentLock); 145 | } 146 | 147 | /** 148 | * 获取当前锁在map中的key 149 | * @param joinPoint 150 | * @param klock 151 | * @return 152 | */ 153 | private String getCurrentLockId(JoinPoint joinPoint , Klock klock){ 154 | LockInfo lockInfo = lockInfoProvider.get(joinPoint,klock); 155 | String curentLock= Thread.currentThread().getId() + lockInfo.getName(); 156 | return curentLock; 157 | } 158 | 159 | /** 160 | * 处理释放锁时已超时 161 | */ 162 | private void handleReleaseTimeout(Klock klock, LockInfo lockInfo, JoinPoint joinPoint) throws Throwable { 163 | 164 | if(logger.isWarnEnabled()) { 165 | logger.warn("Timeout while release Lock({})", lockInfo.getName()); 166 | } 167 | 168 | if(!StringUtils.isEmpty(klock.customReleaseTimeoutStrategy())) { 169 | 170 | handleCustomReleaseTimeout(klock.customReleaseTimeoutStrategy(), joinPoint); 171 | 172 | } else { 173 | klock.releaseTimeoutStrategy().handle(lockInfo); 174 | } 175 | 176 | } 177 | 178 | /** 179 | * 处理自定义释放锁时已超时 180 | */ 181 | private void handleCustomReleaseTimeout(String releaseTimeoutHandler, JoinPoint joinPoint) throws Throwable { 182 | 183 | Method currentMethod = ((MethodSignature)joinPoint.getSignature()).getMethod(); 184 | Object target = joinPoint.getTarget(); 185 | Method handleMethod = null; 186 | try { 187 | handleMethod = joinPoint.getTarget().getClass().getDeclaredMethod(releaseTimeoutHandler, currentMethod.getParameterTypes()); 188 | handleMethod.setAccessible(true); 189 | } catch (NoSuchMethodException e) { 190 | throw new IllegalArgumentException("Illegal annotation param customReleaseTimeoutStrategy",e); 191 | } 192 | Object[] args = joinPoint.getArgs(); 193 | 194 | try { 195 | handleMethod.invoke(target, args); 196 | } catch (IllegalAccessException e) { 197 | throw new KlockInvocationException("Fail to invoke custom release timeout handler: " + releaseTimeoutHandler, e); 198 | } catch (InvocationTargetException e) { 199 | throw e.getTargetException(); 200 | } 201 | } 202 | 203 | private class LockRes { 204 | 205 | private LockInfo lockInfo; 206 | private Lock lock; 207 | private Boolean res; 208 | 209 | LockRes(LockInfo lockInfo, Boolean res) { 210 | this.lockInfo = lockInfo; 211 | this.res = res; 212 | } 213 | 214 | LockInfo getLockInfo() { 215 | return lockInfo; 216 | } 217 | 218 | public Lock getLock() { 219 | return lock; 220 | } 221 | 222 | public void setLock(Lock lock) { 223 | this.lock = lock; 224 | } 225 | 226 | Boolean getRes() { 227 | return res; 228 | } 229 | 230 | void setRes(Boolean res) { 231 | this.res = res; 232 | } 233 | 234 | void setLockInfo(LockInfo lockInfo) { 235 | this.lockInfo = lockInfo; 236 | } 237 | } 238 | 239 | 240 | } 241 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/core/LockInfoProvider.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.core; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.aspectj.lang.reflect.MethodSignature; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.autoconfigure.klock.annotation.Klock; 9 | import org.springframework.boot.autoconfigure.klock.config.KlockConfig; 10 | import org.springframework.boot.autoconfigure.klock.model.LockInfo; 11 | import org.aspectj.lang.ProceedingJoinPoint; 12 | import org.springframework.boot.autoconfigure.klock.model.LockType; 13 | 14 | /** 15 | * Created by kl on 2017/12/29. 16 | */ 17 | public class LockInfoProvider { 18 | 19 | private static final String LOCK_NAME_PREFIX = "lock"; 20 | private static final String LOCK_NAME_SEPARATOR = "."; 21 | 22 | 23 | @Autowired 24 | private KlockConfig klockConfig; 25 | 26 | @Autowired 27 | private BusinessKeyProvider businessKeyProvider; 28 | 29 | private static final Logger logger = LoggerFactory.getLogger(LockInfoProvider.class); 30 | 31 | LockInfo get(JoinPoint joinPoint, Klock klock) { 32 | MethodSignature signature = (MethodSignature) joinPoint.getSignature(); 33 | LockType type= klock.lockType(); 34 | String businessKeyName=businessKeyProvider.getKeyName(joinPoint,klock); 35 | //锁的名字,锁的粒度就是这里控制的 36 | String lockName = LOCK_NAME_PREFIX + LOCK_NAME_SEPARATOR + getName(klock.name(), signature) + businessKeyName; 37 | long waitTime = getWaitTime(klock); 38 | long leaseTime = getLeaseTime(klock); 39 | //如果占用锁的时间设计不合理,则打印相应的警告提示 40 | if(leaseTime == -1 && logger.isWarnEnabled()) { 41 | logger.warn("Trying to acquire Lock({}) with no expiration, " + 42 | "Klock will keep prolong the lock expiration while the lock is still holding by current thread. " + 43 | "This may cause dead lock in some circumstances.", lockName); 44 | } 45 | return new LockInfo(type,lockName,waitTime,leaseTime); 46 | } 47 | 48 | /** 49 | * 获取锁的name,如果没有指定,则按全类名拼接方法名处理 50 | * @param annotationName 51 | * @param signature 52 | * @return 53 | */ 54 | private String getName(String annotationName, MethodSignature signature) { 55 | if (annotationName.isEmpty()) { 56 | return String.format("%s.%s", signature.getDeclaringTypeName(), signature.getMethod().getName()); 57 | } else { 58 | return annotationName; 59 | } 60 | } 61 | 62 | 63 | private long getWaitTime(Klock lock) { 64 | return lock.waitTime() == Long.MIN_VALUE ? 65 | klockConfig.getWaitTime() : lock.waitTime(); 66 | } 67 | 68 | private long getLeaseTime(Klock lock) { 69 | return lock.leaseTime() == Long.MIN_VALUE ? 70 | klockConfig.getLeaseTime() : lock.leaseTime(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/handler/KlockInvocationException.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.handler; 2 | 3 | /** 4 | * @author wanglaomo 5 | * @since 2019/4/16 6 | **/ 7 | public class KlockInvocationException extends RuntimeException { 8 | 9 | public KlockInvocationException() { 10 | } 11 | 12 | public KlockInvocationException(String message) { 13 | super(message); 14 | } 15 | 16 | public KlockInvocationException(String message, Throwable cause) { 17 | super(message, cause); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/handler/KlockTimeoutException.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.handler; 2 | 3 | /** 4 | * @author wanglaomo 5 | * @since 2019/4/16 6 | **/ 7 | public class KlockTimeoutException extends RuntimeException { 8 | 9 | public KlockTimeoutException() { 10 | } 11 | 12 | public KlockTimeoutException(String message) { 13 | super(message); 14 | } 15 | 16 | public KlockTimeoutException(String message, Throwable cause) { 17 | super(message, cause); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/handler/lock/LockTimeoutHandler.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.handler.lock; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.springframework.boot.autoconfigure.klock.lock.Lock; 5 | import org.springframework.boot.autoconfigure.klock.model.LockInfo; 6 | 7 | /** 8 | * 获取锁超时的处理逻辑接口 9 | * 10 | * @author wanglaomo 11 | * @since 2019/4/15 12 | **/ 13 | public interface LockTimeoutHandler { 14 | 15 | void handle(LockInfo lockInfo, Lock lock, JoinPoint joinPoint); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/handler/release/ReleaseTimeoutHandler.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.handler.release; 2 | 3 | import org.springframework.boot.autoconfigure.klock.model.LockInfo; 4 | 5 | /** 6 | * 获取锁超时的处理逻辑接口 7 | * 8 | * @author wanglaomo 9 | * @since 2019/4/15 10 | **/ 11 | public interface ReleaseTimeoutHandler { 12 | 13 | void handle(LockInfo lockInfo); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/lock/FairLock.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.lock; 2 | 3 | import org.redisson.api.RLock; 4 | import org.redisson.api.RedissonClient; 5 | import org.springframework.boot.autoconfigure.klock.model.LockInfo; 6 | 7 | import java.util.concurrent.ExecutionException; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /** 11 | * Created by kl on 2017/12/29. 12 | */ 13 | public class FairLock implements Lock { 14 | 15 | private RLock rLock; 16 | 17 | private final LockInfo lockInfo; 18 | 19 | private RedissonClient redissonClient; 20 | 21 | public FairLock(RedissonClient redissonClient,LockInfo info) { 22 | this.redissonClient = redissonClient; 23 | this.lockInfo = info; 24 | } 25 | 26 | @Override 27 | public boolean acquire() { 28 | try { 29 | rLock=redissonClient.getFairLock(lockInfo.getName()); 30 | return rLock.tryLock(lockInfo.getWaitTime(), lockInfo.getLeaseTime(), TimeUnit.SECONDS); 31 | } catch (InterruptedException e) { 32 | return false; 33 | } 34 | } 35 | 36 | @Override 37 | public boolean release() { 38 | if(rLock.isHeldByCurrentThread()){ 39 | 40 | try { 41 | return rLock.forceUnlockAsync().get(); 42 | } catch (InterruptedException e) { 43 | return false; 44 | } catch (ExecutionException e) { 45 | return false; 46 | } 47 | } 48 | return false; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/lock/Lock.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.lock; 2 | 3 | /** 4 | * Created by kl on 2017/12/29. 5 | */ 6 | public interface Lock { 7 | 8 | boolean acquire(); 9 | 10 | boolean release(); 11 | } 12 | 13 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/lock/LockFactory.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.lock; 2 | 3 | import org.redisson.api.RedissonClient; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.autoconfigure.klock.model.LockInfo; 8 | 9 | /** 10 | * Created by kl on 2017/12/29. 11 | * Content : 12 | */ 13 | public class LockFactory { 14 | Logger logger= LoggerFactory.getLogger(getClass()); 15 | 16 | @Autowired 17 | private RedissonClient redissonClient; 18 | 19 | public Lock getLock(LockInfo lockInfo){ 20 | switch (lockInfo.getType()) { 21 | case Reentrant: 22 | return new ReentrantLock(redissonClient, lockInfo); 23 | case Fair: 24 | return new FairLock(redissonClient, lockInfo); 25 | case Read: 26 | return new ReadLock(redissonClient, lockInfo); 27 | case Write: 28 | return new WriteLock(redissonClient, lockInfo); 29 | default: 30 | return new ReentrantLock(redissonClient, lockInfo); 31 | } 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/lock/ReadLock.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.lock; 2 | 3 | import org.redisson.api.RReadWriteLock; 4 | import org.redisson.api.RedissonClient; 5 | import org.springframework.boot.autoconfigure.klock.model.LockInfo; 6 | 7 | import java.util.concurrent.ExecutionException; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /** 11 | * Created by kl on 2017/12/29. 12 | */ 13 | public class ReadLock implements Lock { 14 | 15 | private RReadWriteLock rLock; 16 | 17 | private final LockInfo lockInfo; 18 | 19 | private RedissonClient redissonClient; 20 | 21 | public ReadLock(RedissonClient redissonClient,LockInfo info) { 22 | this.redissonClient = redissonClient; 23 | this.lockInfo = info; 24 | } 25 | 26 | @Override 27 | public boolean acquire() { 28 | try { 29 | rLock=redissonClient.getReadWriteLock(lockInfo.getName()); 30 | return rLock.readLock().tryLock(lockInfo.getWaitTime(), lockInfo.getLeaseTime(), TimeUnit.SECONDS); 31 | } catch (InterruptedException e) { 32 | return false; 33 | } 34 | } 35 | 36 | @Override 37 | public boolean release() { 38 | if(rLock.readLock().isHeldByCurrentThread()){ 39 | try { 40 | return rLock.readLock().forceUnlockAsync().get(); 41 | } catch (InterruptedException e) { 42 | return false; 43 | } catch (ExecutionException e) { 44 | return false; 45 | } 46 | } 47 | 48 | return false; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/lock/ReentrantLock.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.lock; 2 | 3 | import org.redisson.api.RLock; 4 | import org.redisson.api.RedissonClient; 5 | import org.springframework.boot.autoconfigure.klock.model.LockInfo; 6 | 7 | import java.util.concurrent.ExecutionException; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /** 11 | * Created by kl on 2017/12/29. 12 | */ 13 | public class ReentrantLock implements Lock { 14 | 15 | private RLock rLock; 16 | 17 | private final LockInfo lockInfo; 18 | 19 | private RedissonClient redissonClient; 20 | 21 | public ReentrantLock(RedissonClient redissonClient,LockInfo lockInfo) { 22 | this.redissonClient = redissonClient; 23 | this.lockInfo = lockInfo; 24 | } 25 | @Override 26 | public boolean acquire() { 27 | try { 28 | rLock = redissonClient.getLock(lockInfo.getName()); 29 | return rLock.tryLock(lockInfo.getWaitTime(), lockInfo.getLeaseTime(), TimeUnit.SECONDS); 30 | } catch (InterruptedException e) { 31 | return false; 32 | } 33 | } 34 | 35 | @Override 36 | public boolean release() { 37 | if(rLock.isHeldByCurrentThread()){ 38 | try { 39 | return rLock.forceUnlockAsync().get(); 40 | } catch (InterruptedException e) { 41 | return false; 42 | } catch (ExecutionException e) { 43 | return false; 44 | } 45 | } 46 | return false; 47 | } 48 | public String getKey(){ 49 | return this.lockInfo.getName(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/lock/WriteLock.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.lock; 2 | 3 | import org.redisson.api.RReadWriteLock; 4 | import org.redisson.api.RedissonClient; 5 | import org.springframework.boot.autoconfigure.klock.model.LockInfo; 6 | 7 | import java.util.concurrent.ExecutionException; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /** 11 | * Created by kl on 2017/12/29. 12 | */ 13 | public class WriteLock implements Lock { 14 | 15 | private RReadWriteLock rLock; 16 | 17 | private final LockInfo lockInfo; 18 | 19 | private RedissonClient redissonClient; 20 | 21 | public WriteLock(RedissonClient redissonClient,LockInfo info) { 22 | this.redissonClient = redissonClient; 23 | this.lockInfo = info; 24 | } 25 | 26 | @Override 27 | public boolean acquire() { 28 | try { 29 | rLock=redissonClient.getReadWriteLock(lockInfo.getName()); 30 | return rLock.writeLock().tryLock(lockInfo.getWaitTime(), lockInfo.getLeaseTime(), TimeUnit.SECONDS); 31 | } catch (InterruptedException e) { 32 | return false; 33 | } 34 | } 35 | 36 | @Override 37 | public boolean release() { 38 | if(rLock.writeLock().isHeldByCurrentThread()){ 39 | try { 40 | return rLock.writeLock().forceUnlockAsync().get(); 41 | } catch (InterruptedException e) { 42 | return false; 43 | } catch (ExecutionException e) { 44 | return false; 45 | } 46 | } 47 | 48 | return false; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/model/LockInfo.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.model; 2 | 3 | /** 4 | * Created by kl on 2017/12/29. 5 | * Content :锁基本信息 6 | */ 7 | public class LockInfo { 8 | 9 | private LockType type; 10 | private String name; 11 | private long waitTime; 12 | private long leaseTime; 13 | 14 | public LockInfo() { 15 | } 16 | 17 | public LockInfo(LockType type, String name, long waitTime, long leaseTime) { 18 | this.type = type; 19 | this.name = name; 20 | this.waitTime = waitTime; 21 | this.leaseTime = leaseTime; 22 | } 23 | 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | public void setName(String name) { 29 | this.name = name; 30 | } 31 | 32 | public long getWaitTime() { 33 | return waitTime; 34 | } 35 | 36 | public void setWaitTime(long waitTime) { 37 | this.waitTime = waitTime; 38 | } 39 | 40 | public long getLeaseTime() { 41 | return leaseTime; 42 | } 43 | 44 | public void setLeaseTime(long leaseTime) { 45 | this.leaseTime = leaseTime; 46 | } 47 | 48 | public LockType getType() { 49 | return type; 50 | } 51 | 52 | public void setType(LockType type) { 53 | this.type = type; 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return "LockInfo{" + 59 | "type=" + type + 60 | ", name='" + name + '\'' + 61 | ", waitTime=" + waitTime + 62 | ", leaseTime=" + leaseTime + 63 | '}'; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/model/LockTimeoutStrategy.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.model; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.springframework.boot.autoconfigure.klock.handler.KlockTimeoutException; 5 | import org.springframework.boot.autoconfigure.klock.handler.lock.LockTimeoutHandler; 6 | import org.springframework.boot.autoconfigure.klock.lock.Lock; 7 | 8 | import java.util.concurrent.TimeUnit; 9 | 10 | 11 | /** 12 | * @author wanglaomo 13 | * @since 2019/4/15 14 | **/ 15 | public enum LockTimeoutStrategy implements LockTimeoutHandler { 16 | 17 | /** 18 | * 继续执行业务逻辑,不做任何处理 19 | */ 20 | NO_OPERATION() { 21 | @Override 22 | public void handle(LockInfo lockInfo, Lock lock, JoinPoint joinPoint) { 23 | // do nothing 24 | } 25 | }, 26 | 27 | /** 28 | * 快速失败 29 | */ 30 | FAIL_FAST() { 31 | @Override 32 | public void handle(LockInfo lockInfo, Lock lock, JoinPoint joinPoint) { 33 | 34 | String errorMsg = String.format("Failed to acquire Lock(%s) with timeout(%ds)", lockInfo.getName(), lockInfo.getWaitTime()); 35 | throw new KlockTimeoutException(errorMsg); 36 | } 37 | }, 38 | 39 | /** 40 | * 一直阻塞,直到获得锁,在太多的尝试后,仍会报错 41 | */ 42 | KEEP_ACQUIRE() { 43 | 44 | private static final long DEFAULT_INTERVAL = 100L; 45 | 46 | private static final long DEFAULT_MAX_INTERVAL = 3 * 60 * 1000L; 47 | 48 | @Override 49 | public void handle(LockInfo lockInfo, Lock lock, JoinPoint joinPoint) { 50 | 51 | long interval = DEFAULT_INTERVAL; 52 | 53 | while(!lock.acquire()) { 54 | 55 | if(interval > DEFAULT_MAX_INTERVAL) { 56 | String errorMsg = String.format("Failed to acquire Lock(%s) after too many times, this may because dead lock occurs.", 57 | lockInfo.getName()); 58 | throw new KlockTimeoutException(errorMsg); 59 | } 60 | 61 | try { 62 | TimeUnit.MILLISECONDS.sleep(interval); 63 | interval <<= 1; 64 | } catch (InterruptedException e) { 65 | throw new KlockTimeoutException("Failed to acquire Lock", e); 66 | } 67 | } 68 | } 69 | } 70 | } -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/model/LockType.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.model; 2 | 3 | /** 4 | * Created by kl on 2017/12/29. 5 | * Content :锁类型 6 | */ 7 | public enum LockType { 8 | /** 9 | * 可重入锁 10 | */ 11 | Reentrant, 12 | /** 13 | * 公平锁 14 | */ 15 | Fair, 16 | /** 17 | * 读锁 18 | */ 19 | Read, 20 | /** 21 | * 写锁 22 | */ 23 | Write; 24 | 25 | LockType() { 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/autoconfigure/klock/model/ReleaseTimeoutStrategy.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.model; 2 | 3 | import org.springframework.boot.autoconfigure.klock.handler.KlockTimeoutException; 4 | import org.springframework.boot.autoconfigure.klock.handler.release.ReleaseTimeoutHandler; 5 | 6 | /** 7 | * @author wanglaomo 8 | * @since 2019/4/15 9 | **/ 10 | public enum ReleaseTimeoutStrategy implements ReleaseTimeoutHandler { 11 | 12 | /** 13 | * 继续执行业务逻辑,不做任何处理 14 | */ 15 | NO_OPERATION() { 16 | @Override 17 | public void handle(LockInfo lockInfo) { 18 | // do nothing 19 | } 20 | }, 21 | /** 22 | * 快速失败 23 | */ 24 | FAIL_FAST() { 25 | @Override 26 | public void handle(LockInfo lockInfo) { 27 | 28 | String errorMsg = String.format("Found Lock(%s) already been released while lock lease time is %d s", lockInfo.getName(), lockInfo.getLeaseTime()); 29 | throw new KlockTimeoutException(errorMsg); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 2 | org.springframework.boot.autoconfigure.klock.KlockAutoConfiguration -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.klock.KlockAutoConfiguration 2 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/boot/autoconfigure/klock/test/KlockTestApplication.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.test; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.EnableAspectJAutoProxy; 6 | 7 | /** 8 | * Created by kl on 2017/12/31. 9 | */ 10 | @SpringBootApplication 11 | @EnableAspectJAutoProxy 12 | public class KlockTestApplication { 13 | 14 | public static void main(String[] args) { 15 | SpringApplication.run(KlockTestApplication.class, args); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/boot/autoconfigure/klock/test/KlockTests.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.test; 2 | 3 | import org.junit.*; 4 | import org.junit.rules.ExpectedException; 5 | import org.junit.runner.RunWith; 6 | import org.redisson.api.RedissonClient; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.autoconfigure.klock.handler.KlockTimeoutException; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import java.util.Date; 13 | import java.util.concurrent.CountDownLatch; 14 | import java.util.concurrent.ExecutorService; 15 | import java.util.concurrent.Executors; 16 | import java.util.concurrent.TimeUnit; 17 | import java.util.stream.IntStream; 18 | 19 | @RunWith(SpringRunner.class) 20 | @SpringBootTest(classes = KlockTestApplication.class) 21 | public class KlockTests { 22 | 23 | @Autowired 24 | TestService testService; 25 | 26 | @Autowired 27 | TimeoutService timeoutService; 28 | 29 | @Rule 30 | public final ExpectedException exception = ExpectedException.none(); 31 | 32 | /** 33 | * 同一进程内多线程获取锁测试 34 | * @throws Exception 35 | */ 36 | @Test 37 | public void multithreadingTest()throws Exception{ 38 | ExecutorService executorService = Executors.newFixedThreadPool(6); 39 | IntStream.range(0,10).forEach(i-> executorService.submit(() -> { 40 | try { 41 | String result = testService.getValue("sleep"); 42 | System.err.println("线程:[" + Thread.currentThread().getName() + "]拿到结果=》" + result + new Date().toString()); 43 | } catch (Exception e) { 44 | e.printStackTrace(); 45 | } 46 | })); 47 | executorService.awaitTermination(30, TimeUnit.SECONDS); 48 | } 49 | 50 | 51 | /** 52 | *线程休眠50秒 53 | * @throws Exception 54 | */ 55 | @Test 56 | public void jvm1()throws Exception{ 57 | String result=testService.getValue("sleep"); 58 | Assert.assertEquals(result,"success"); 59 | } 60 | 61 | /** 62 | *不休眠 63 | * @throws Exception 64 | */ 65 | @Test 66 | public void jvm2()throws Exception{ 67 | String result=testService.getValue("noSleep"); 68 | Assert.assertEquals(result,"success"); 69 | } 70 | /** 71 | *不休眠 72 | * @throws Exception 73 | */ 74 | @Test 75 | public void jvm3()throws Exception{ 76 | String result=testService.getValue("noSleep"); 77 | Assert.assertEquals(result,"success"); 78 | } 79 | //先后启动jvm1 和 jvm 2两个测试用例,会发现虽然 jvm2没休眠,因为getValue加锁了, 80 | // 所以只要jvm1拿到锁就基本同时完成 81 | 82 | /** 83 | * 测试业务key 84 | */ 85 | @Test 86 | public void businessKeyJvm1()throws Exception{ 87 | String result=testService.getValue("user1",null); 88 | Assert.assertEquals(result,"success"); 89 | } 90 | /** 91 | * 测试业务key 92 | */ 93 | @Test 94 | public void businessKeyJvm2()throws Exception{ 95 | String result=testService.getValue("user1",1); 96 | Assert.assertEquals(result,"success"); 97 | } 98 | /** 99 | * 测试业务key 100 | */ 101 | @Test 102 | public void businessKeyJvm3()throws Exception{ 103 | String result=testService.getValue("user1",2); 104 | Assert.assertEquals(result,"success"); 105 | } 106 | /** 107 | * 测试业务key 108 | */ 109 | @Test 110 | public void businessKeyJvm4()throws Exception{ 111 | String result=testService.getValue(new User(3,null)); 112 | Assert.assertEquals(result,"success"); 113 | } 114 | 115 | /** 116 | * 测试watchdog无限延长加锁时间 117 | */ 118 | @Test 119 | public void infiniteLeaseTime() { 120 | timeoutService.foo1(); 121 | } 122 | 123 | /** 124 | * 测试加锁超时快速失败 125 | */ 126 | @Test 127 | public void lockTimeoutFailFast() throws InterruptedException { 128 | 129 | ExecutorService executorService = Executors.newFixedThreadPool(10); 130 | 131 | executorService.submit(() -> timeoutService.foo1()); 132 | 133 | TimeUnit.MILLISECONDS.sleep(1000); 134 | 135 | exception.expect(KlockTimeoutException.class); 136 | timeoutService.foo2(); 137 | 138 | } 139 | 140 | /** 141 | * 测试加锁超时阻塞等待 142 | * 会打印10次acquire lock 143 | */ 144 | @Test 145 | public void lockTimeoutKeepAcquire() throws InterruptedException { 146 | 147 | ExecutorService executorService = Executors.newFixedThreadPool(10); 148 | CountDownLatch startLatch = new CountDownLatch(1); 149 | CountDownLatch endLatch = new CountDownLatch(10); 150 | 151 | for(int i=0; i<10; i++) { 152 | executorService.submit(() -> { 153 | try { 154 | startLatch.await(); 155 | timeoutService.foo3(); 156 | } catch (InterruptedException e) { 157 | e.printStackTrace(); 158 | } finally { 159 | endLatch.countDown(); 160 | } 161 | }); 162 | } 163 | 164 | long start = System.currentTimeMillis(); 165 | startLatch.countDown(); 166 | endLatch.await(); 167 | long end = System.currentTimeMillis(); 168 | Assert.assertTrue((end - start) >= 10*2*1000); 169 | } 170 | 171 | /** 172 | * 测试自定义加锁超时处理策略 173 | * 会执行1次自定义加锁超时处理策略 174 | */ 175 | @Test 176 | public void lockTimeoutCustom() throws InterruptedException { 177 | 178 | ExecutorService executorService = Executors.newFixedThreadPool(10); 179 | CountDownLatch latch = new CountDownLatch(2); 180 | 181 | executorService.submit(() -> { 182 | timeoutService.foo1(); 183 | latch.countDown(); 184 | }); 185 | 186 | executorService.submit(() -> { 187 | timeoutService.foo4("foo", "bar"); 188 | latch.countDown(); 189 | }); 190 | 191 | latch.await(); 192 | } 193 | 194 | /** 195 | * 测试加锁超时不做处理 196 | */ 197 | @Test 198 | public void lockTimeoutNoOperation() throws InterruptedException { 199 | 200 | ExecutorService executorService = Executors.newFixedThreadPool(10); 201 | CountDownLatch startLatch = new CountDownLatch(1); 202 | CountDownLatch endLatch = new CountDownLatch(10); 203 | 204 | for(int i=0; i<10; i++) { 205 | executorService.submit(() -> { 206 | try { 207 | startLatch.await(); 208 | timeoutService.foo5("foo", "bar"); 209 | } catch (Exception e) { 210 | e.printStackTrace(); 211 | } finally { 212 | endLatch.countDown(); 213 | } 214 | }); 215 | 216 | } 217 | 218 | long start = System.currentTimeMillis(); 219 | startLatch.countDown(); 220 | endLatch.await(); 221 | long end = System.currentTimeMillis(); 222 | Assert.assertTrue((end - start) < 10*2*1000); 223 | } 224 | 225 | /** 226 | * 测试释放锁时已超时,不做处理 227 | */ 228 | @Test 229 | public void releaseTimeoutNoOperation() { 230 | 231 | timeoutService.foo6("foo", "bar"); 232 | } 233 | 234 | /** 235 | * 测试释放锁时已超时,快速失败 236 | */ 237 | @Test 238 | public void releaseTimeoutFailFast() { 239 | 240 | exception.expect(KlockTimeoutException.class); 241 | timeoutService.foo7("foo", "bar"); 242 | } 243 | /** 244 | * 测试释放锁时已超时,自定义策略 245 | */ 246 | @Test 247 | public void releaseTimeoutCustom(){ 248 | exception.expect(IllegalStateException.class); 249 | timeoutService.foo8("foo", "bar"); 250 | } 251 | } 252 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/boot/autoconfigure/klock/test/TestService.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.test; 2 | 3 | import org.springframework.boot.autoconfigure.klock.annotation.Klock; 4 | import org.springframework.boot.autoconfigure.klock.annotation.KlockKey; 5 | import org.springframework.boot.autoconfigure.klock.model.LockTimeoutStrategy; 6 | import org.springframework.stereotype.Service; 7 | 8 | /** 9 | * Created by kl on 2017/12/29. 10 | */ 11 | @Service 12 | public class TestService { 13 | 14 | @Klock(waitTime = 10,leaseTime = 60,keys = {"#param"},lockTimeoutStrategy = LockTimeoutStrategy.FAIL_FAST) 15 | public String getValue(String param) throws Exception { 16 | // if ("sleep".equals(param)) {//线程休眠或者断点阻塞,达到一直占用锁的测试效果 17 | Thread.sleep(1000*3); 18 | //} 19 | return "success"; 20 | } 21 | 22 | @Klock(keys = {"#userId"}) 23 | public String getValue(String userId,@KlockKey Integer id)throws Exception{ 24 | Thread.sleep(60*1000); 25 | return "success"; 26 | } 27 | 28 | @Klock(keys = {"#user.name","#user.id"}) 29 | public String getValue(User user)throws Exception{ 30 | Thread.sleep(60*1000); 31 | return "success"; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/boot/autoconfigure/klock/test/TimeoutService.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.test; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.boot.autoconfigure.klock.annotation.Klock; 6 | import org.springframework.boot.autoconfigure.klock.model.LockTimeoutStrategy; 7 | import org.springframework.boot.autoconfigure.klock.model.ReleaseTimeoutStrategy; 8 | import org.springframework.stereotype.Service; 9 | 10 | import java.util.concurrent.TimeUnit; 11 | 12 | /** 13 | * @author wanglaomo 14 | * @since 2019/4/16 15 | **/ 16 | @Service 17 | public class TimeoutService { 18 | 19 | private static final Logger logger = LoggerFactory.getLogger(TimeoutService.class); 20 | 21 | @Klock(name="foo-service", leaseTime=-1, releaseTimeoutStrategy = ReleaseTimeoutStrategy.FAIL_FAST) 22 | public void foo1() { 23 | try { 24 | logger.info("foo1 acquire lock"); 25 | TimeUnit.SECONDS.sleep(3); 26 | } catch (InterruptedException e) { 27 | e.printStackTrace(); 28 | } 29 | } 30 | 31 | @Klock(name="foo-service", waitTime=2, lockTimeoutStrategy = LockTimeoutStrategy.FAIL_FAST) 32 | public void foo2() { 33 | try { 34 | logger.info("acquire lock"); 35 | TimeUnit.SECONDS.sleep(2); 36 | } catch (InterruptedException e) { 37 | e.printStackTrace(); 38 | } 39 | } 40 | 41 | @Klock(name="foo-service", waitTime=2, lockTimeoutStrategy = LockTimeoutStrategy.KEEP_ACQUIRE) 42 | public void foo3() { 43 | try { 44 | TimeUnit.SECONDS.sleep(2); 45 | logger.info("acquire lock"); 46 | } catch (InterruptedException e) { 47 | e.printStackTrace(); 48 | } 49 | } 50 | 51 | @Klock(name="foo-service", 52 | waitTime=2, 53 | customLockTimeoutStrategy = "customLockTimeout") 54 | public String foo4(String foo, String bar) { 55 | try { 56 | TimeUnit.SECONDS.sleep(2); 57 | logger.info("acquire lock"); 58 | } catch (InterruptedException e) { 59 | e.printStackTrace(); 60 | } 61 | 62 | return "foo4"; 63 | } 64 | 65 | private String customLockTimeout(String foo, String bar) { 66 | 67 | logger.info("customLockTimeout foo: " + foo + " bar: " + bar); 68 | return "custom foo: " + foo + " bar: " + bar; 69 | } 70 | 71 | 72 | @Klock(name="foo-service", waitTime=10) 73 | public void foo5(String foo, String bar) { 74 | try { 75 | TimeUnit.SECONDS.sleep(2); 76 | logger.info("acquire lock"); 77 | } catch (InterruptedException e) { 78 | e.printStackTrace(); 79 | } 80 | } 81 | 82 | @Klock(name="foo-service", leaseTime=10, waitTime = 10000) 83 | public void foo6(String foo, String bar) { 84 | try { 85 | TimeUnit.SECONDS.sleep(2); 86 | logger.info("acquire lock"); 87 | } catch (InterruptedException e) { 88 | e.printStackTrace(); 89 | } 90 | } 91 | 92 | @Klock(name="foo-service", leaseTime=1, waitTime = 10000, releaseTimeoutStrategy = ReleaseTimeoutStrategy.FAIL_FAST) 93 | public void foo7(String foo, String bar) { 94 | try { 95 | TimeUnit.SECONDS.sleep(2); 96 | logger.info("acquire lock"); 97 | } catch (InterruptedException e) { 98 | e.printStackTrace(); 99 | } 100 | } 101 | 102 | 103 | @Klock(name="foo-service", leaseTime=1, waitTime = 10000, customReleaseTimeoutStrategy = "customReleaseTimeout") 104 | public String foo8(String foo, String bar) { 105 | try { 106 | TimeUnit.SECONDS.sleep(2); 107 | } catch (InterruptedException e) { 108 | e.printStackTrace(); 109 | } 110 | return "foo8"; 111 | } 112 | 113 | private String customReleaseTimeout(String foo, String bar) { 114 | 115 | throw new IllegalStateException("customReleaseTimeout"); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/boot/autoconfigure/klock/test/User.java: -------------------------------------------------------------------------------- 1 | package org.springframework.boot.autoconfigure.klock.test; 2 | 3 | public class User{ 4 | private int id; 5 | private String name; 6 | 7 | public User() { 8 | } 9 | 10 | public User(int id, String name) { 11 | this.id = id; 12 | this.name = name; 13 | } 14 | 15 | public int getId() { 16 | return id; 17 | } 18 | 19 | public void setId(int id) { 20 | this.id = id; 21 | } 22 | 23 | public String getName() { 24 | return name; 25 | } 26 | 27 | public void setName(String name) { 28 | this.name = name; 29 | } 30 | } -------------------------------------------------------------------------------- /src/test/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.klock.address=redis://192.168.10.204:6379 2 | --------------------------------------------------------------------------------