├── .gitignore ├── LICENSE ├── aspectDemo ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── xiongyx │ │ │ ├── ApplicationMain.java │ │ │ ├── annotation │ │ │ ├── RedisLock.java │ │ │ └── RedisLockKey.java │ │ │ ├── aspect │ │ │ └── RedisLockAspect.java │ │ │ ├── controller │ │ │ └── TestController.java │ │ │ ├── enums │ │ │ └── RedisLockKeyType.java │ │ │ ├── service │ │ │ ├── api │ │ │ │ ├── TestService.java │ │ │ │ └── TestService2.java │ │ │ └── impl │ │ │ │ ├── TestService2Impl.java │ │ │ │ └── TestServiceImpl.java │ │ │ └── util │ │ │ └── RedisLockKeyUtil.java │ └── resources │ │ ├── application.properties │ │ └── log4j.properties │ └── test.html ├── pom.xml └── redisDistributeLock ├── pom.xml └── src └── main ├── java └── com │ └── xiongyx │ ├── ApplicationMain.java │ ├── TestServiceA.java │ ├── config │ ├── JedisConfig.java │ └── RedisConfig.java │ ├── constants │ └── RedisConstants.java │ ├── controller │ └── TestController.java │ ├── exception │ └── RedisLockFailException.java │ ├── lock │ ├── api │ │ └── DistributeLock.java │ ├── impl │ │ └── RedisDistributeLock.java │ └── script │ │ └── LuaScript.java │ ├── redis │ ├── RedisClient.java │ └── RedisClientImpl.java │ └── util │ ├── CastUtil.java │ └── PropsUtil.java └── resources ├── application.properties ├── lock.lua ├── redis.properties └── unlock.lua /.gitignore: -------------------------------------------------------------------------------- 1 | ## idea 2 | *.iml 3 | .idea 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 1399852153 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /aspectDemo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | DistributeLock 7 | DistributeLock 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | aspectDemo 13 | 14 | 15 | 16 | org.springframework.boot 17 | spring-boot-starter-web 18 | 19 | 20 | 21 | 22 | org.aspectj 23 | aspectjweaver 24 | 1.9.1 25 | 26 | 27 | 28 | redis.clients 29 | jedis 30 | 31 | 32 | 33 | DistributeLock 34 | redisDistributeLock 35 | 1.0-SNAPSHOT 36 | 37 | 38 | org.slf4j 39 | slf4j-log4j12 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /aspectDemo/src/main/java/com/xiongyx/ApplicationMain.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * @author xiongyx 8 | * on 2019/5/18. 9 | */ 10 | @SpringBootApplication 11 | public class ApplicationMain { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(ApplicationMain.class,args); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /aspectDemo/src/main/java/com/xiongyx/annotation/RedisLock.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.annotation; 2 | 3 | import com.xiongyx.exception.RedisLockFailException; 4 | import com.xiongyx.lock.impl.RedisDistributeLock; 5 | 6 | import java.lang.annotation.*; 7 | 8 | /** 9 | * @Author xiongyx 10 | * @Date 2019/4/12 11 | */ 12 | @Target(ElementType.METHOD) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | @Documented 15 | public @interface RedisLock { 16 | /** 17 | * redis锁,重试次数-1代表无限重试 18 | * */ 19 | int unLimitRetryCount = RedisDistributeLock.UN_LIMIT_RETRY_COUNT; 20 | 21 | /** 22 | * redis锁对应的key 会拼接此参数,用于进一步区分,避免redis的key被覆盖 23 | * */ 24 | String lockKey() default ""; 25 | 26 | /** 27 | * redis锁过期时间(单位:秒) 28 | * */ 29 | int expireTime() default 10; 30 | 31 | /** 32 | * redis锁,加锁失败重试次数 默认30次,大约3s 33 | * 超过指定次数后,抛出加锁失败异常,可以由调用方自己补偿 34 | * @see RedisLockFailException 35 | * */ 36 | int retryCount() default 30; 37 | } 38 | -------------------------------------------------------------------------------- /aspectDemo/src/main/java/com/xiongyx/annotation/RedisLockKey.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.annotation; 2 | 3 | import com.xiongyx.enums.RedisLockKeyType; 4 | 5 | import java.lang.annotation.*; 6 | 7 | /** 8 | * @author xiongyx 9 | * @date 2019/5/20 10 | */ 11 | 12 | @Target(ElementType.PARAMETER) 13 | @Retention(RetentionPolicy.RUNTIME) 14 | @Documented 15 | public @interface RedisLockKey { 16 | 17 | String expressionKeySeparator = ","; 18 | 19 | RedisLockKeyType type(); 20 | 21 | String expression() default ""; 22 | } 23 | -------------------------------------------------------------------------------- /aspectDemo/src/main/java/com/xiongyx/aspect/RedisLockAspect.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.aspect; 2 | 3 | import com.xiongyx.annotation.RedisLock; 4 | import com.xiongyx.constants.RedisConstants; 5 | import com.xiongyx.exception.RedisLockFailException; 6 | import com.xiongyx.lock.api.DistributeLock; 7 | import com.xiongyx.util.RedisLockKeyUtil; 8 | import org.aspectj.lang.ProceedingJoinPoint; 9 | import org.aspectj.lang.annotation.Around; 10 | import org.aspectj.lang.annotation.Aspect; 11 | import org.aspectj.lang.annotation.Pointcut; 12 | import org.aspectj.lang.reflect.MethodSignature; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.core.env.Environment; 17 | import org.springframework.stereotype.Component; 18 | 19 | import java.lang.reflect.Method; 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | /** 24 | * @Author xiongyx 25 | * @Date 2019/4/12 26 | * 27 | * redis锁 切面定义 28 | */ 29 | 30 | @Component 31 | @Aspect 32 | public class RedisLockAspect { 33 | 34 | private static final Logger LOGGER = LoggerFactory.getLogger(RedisLockAspect.class); 35 | 36 | private static final String LOCK_KEY_SIGN = "redisLock:"; 37 | private final RequestIDMap REQUEST_ID_MAP = new RequestIDMap(); 38 | 39 | /** 40 | * 将ThreadLocal包装成一个对象方便使用 41 | * */ 42 | private class RequestIDMap{ 43 | private ThreadLocal> innerThreadLocal = new ThreadLocal<>(); 44 | 45 | private void setRequestID(String redisLockKey,String requestID){ 46 | Map requestIDMap = innerThreadLocal.get(); 47 | if(requestIDMap == null){ 48 | Map newMap = new HashMap<>(); 49 | newMap.put(redisLockKey,requestID); 50 | innerThreadLocal.set(newMap); 51 | }else{ 52 | requestIDMap.put(redisLockKey,requestID); 53 | } 54 | } 55 | 56 | private String getRequestID(String redisLockKey){ 57 | Map requestIDMap = innerThreadLocal.get(); 58 | if(requestIDMap == null){ 59 | return null; 60 | }else{ 61 | return requestIDMap.get(redisLockKey); 62 | } 63 | } 64 | 65 | private void removeRequestID(String redisLockKey){ 66 | Map requestIDMap = innerThreadLocal.get(); 67 | if(requestIDMap != null){ 68 | requestIDMap.remove(redisLockKey); 69 | // 如果requestIDMap为空,说明当前重入锁 最外层已经解锁 70 | if(requestIDMap.isEmpty()){ 71 | // 清空threadLocal避免内存泄露 72 | innerThreadLocal.remove(); 73 | } 74 | } 75 | } 76 | } 77 | 78 | @Autowired 79 | private Environment environment; 80 | @Autowired 81 | private DistributeLock distributeLock; 82 | 83 | @Pointcut("@annotation(com.xiongyx.annotation.RedisLock)") 84 | public void annotationPointcut() { 85 | } 86 | 87 | @Around("annotationPointcut()") 88 | public Object around(ProceedingJoinPoint joinPoint) throws Throwable { 89 | MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature(); 90 | Method method = methodSignature.getMethod(); 91 | RedisLock annotation = method.getAnnotation(RedisLock.class); 92 | 93 | // 方法执行前,先尝试加锁 94 | boolean lockSuccess = lock(annotation,joinPoint); 95 | // 如果加锁成功 96 | if(lockSuccess){ 97 | // 执行方法 98 | try { 99 | Object result = joinPoint.proceed(); 100 | // 方法执行后,进行解锁 101 | unlock(annotation,joinPoint); 102 | return result; 103 | } catch (Throwable throwable) { 104 | // catch异常,进行解锁 105 | 106 | LOGGER.info("发生异常,解锁"); 107 | unlock(annotation,joinPoint); 108 | throw throwable; 109 | } 110 | 111 | }else{ 112 | throw new RedisLockFailException("redis分布式锁加锁失败,method= " + method.getName()); 113 | } 114 | } 115 | 116 | /** 117 | * 加锁 118 | * */ 119 | private boolean lock(RedisLock annotation,ProceedingJoinPoint joinPoint) { 120 | int retryCount = annotation.retryCount(); 121 | 122 | // 拼接redisLock的key 123 | String redisLockKey = getFinallyKeyLock(annotation,joinPoint); 124 | String requestID = REQUEST_ID_MAP.getRequestID(redisLockKey); 125 | if(requestID != null){ 126 | // 当前线程 已经存在requestID 127 | distributeLock.lockAndRetry(redisLockKey,requestID,annotation.expireTime(),retryCount); 128 | LOGGER.info("重入加锁成功 redisLockKey=" + redisLockKey); 129 | 130 | return true; 131 | }else{ 132 | // 当前线程 不存在requestID 133 | String newRequestID = distributeLock.lockAndRetry(redisLockKey,annotation.expireTime(),retryCount); 134 | 135 | if(newRequestID != null){ 136 | // 加锁成功,设置新的requestID 137 | REQUEST_ID_MAP.setRequestID(redisLockKey,newRequestID); 138 | LOGGER.info("加锁成功 redisLockKey=" + redisLockKey); 139 | 140 | return true; 141 | }else{ 142 | LOGGER.info("加锁失败,超过重试次数,直接返回 retryCount= {}",retryCount); 143 | 144 | return false; 145 | } 146 | } 147 | } 148 | 149 | /** 150 | * 解锁 151 | * */ 152 | private void unlock(RedisLock annotation,ProceedingJoinPoint joinPoint) { 153 | // 拼接redisLock的key 154 | String redisLockKey = getFinallyKeyLock(annotation,joinPoint); 155 | String requestID = REQUEST_ID_MAP.getRequestID(redisLockKey); 156 | if(requestID != null){ 157 | // 解锁成功 158 | boolean unLockSuccess = distributeLock.unLock(redisLockKey,requestID); 159 | if(unLockSuccess){ 160 | // 移除 ThreadLocal中的数据,防止内存泄漏 161 | REQUEST_ID_MAP.removeRequestID(redisLockKey); 162 | LOGGER.info("解锁成功 redisLockKey= " + redisLockKey); 163 | } 164 | }else{ 165 | LOGGER.info("解锁失败 redisLockKey= " + redisLockKey); 166 | } 167 | } 168 | 169 | /** 170 | * 拼接redisLock的key 171 | * */ 172 | private String getFinallyKeyLock(RedisLock annotation,ProceedingJoinPoint joinPoint){ 173 | String applicationName = environment.getProperty("spring.application.name"); 174 | if(applicationName == null){ 175 | applicationName = ""; 176 | } 177 | 178 | // applicationName在前 179 | String finallyKey = RedisLockKeyUtil.getFinallyLockKey(applicationName,annotation, 180 | joinPoint); 181 | 182 | if (finallyKey.length() > RedisConstants.FINALLY_KEY_LIMIT) { 183 | throw new RuntimeException("finallyLockKey is too long finallyKey=" + finallyKey); 184 | }else{ 185 | return LOCK_KEY_SIGN + finallyKey; 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /aspectDemo/src/main/java/com/xiongyx/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.controller; 2 | 3 | import com.xiongyx.aspect.RedisLockAspect; 4 | import com.xiongyx.service.api.TestService; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import javax.servlet.http.HttpServletRequest; 12 | 13 | /** 14 | * @Author xiongyx 15 | * on 2019/4/12. 16 | */ 17 | @Controller 18 | public class TestController { 19 | 20 | private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class); 21 | 22 | 23 | @Autowired 24 | private TestService testService; 25 | 26 | @RequestMapping("/test/{abc}/bcd") 27 | @ResponseBody 28 | public String test1(@PathVariable("abc") String abc) throws InterruptedException { 29 | LOGGER.info("接收到请求 " + abc); 30 | 31 | testService.method1(abc); 32 | 33 | return "ok"; 34 | } 35 | 36 | @RequestMapping("/test/{abc}/efg") 37 | @ResponseBody 38 | public String test2(@PathVariable("abc") String abc) throws InterruptedException { 39 | LOGGER.info("接收到请求 " + abc); 40 | 41 | return "ok"; 42 | } 43 | 44 | @RequestMapping("/test/efg") 45 | @ResponseBody 46 | public String test3(@RequestParam String abc) throws InterruptedException { 47 | LOGGER.info("接收到请求 " + abc); 48 | 49 | return "ok"; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /aspectDemo/src/main/java/com/xiongyx/enums/RedisLockKeyType.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.enums; 2 | 3 | /** 4 | * @author xiongyx 5 | * @date 2019/5/20 6 | */ 7 | public enum RedisLockKeyType { 8 | /** 9 | * 当前对象的toString做key 10 | * */ 11 | ALL, 12 | 13 | /** 14 | * 当前对象的内部属性的toString做key 15 | * */ 16 | FIELD, 17 | ; 18 | } 19 | -------------------------------------------------------------------------------- /aspectDemo/src/main/java/com/xiongyx/service/api/TestService.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.service.api; 2 | 3 | /** 4 | * @Author xiongyx 5 | * on 2019/4/12. 6 | */ 7 | public interface TestService { 8 | 9 | String method1(String num) throws InterruptedException; 10 | 11 | } 12 | -------------------------------------------------------------------------------- /aspectDemo/src/main/java/com/xiongyx/service/api/TestService2.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.service.api; 2 | 3 | /** 4 | * @author xiongyx 5 | * on 2019/10/15. 6 | */ 7 | public interface TestService2 { 8 | 9 | String method2(String num) throws InterruptedException; 10 | } 11 | -------------------------------------------------------------------------------- /aspectDemo/src/main/java/com/xiongyx/service/impl/TestService2Impl.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.service.impl; 2 | 3 | import com.xiongyx.annotation.RedisLock; 4 | import com.xiongyx.annotation.RedisLockKey; 5 | import com.xiongyx.enums.RedisLockKeyType; 6 | import com.xiongyx.service.api.TestService2; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.stereotype.Service; 10 | 11 | /** 12 | * @author xiongyx 13 | * on 2019/10/15. 14 | */ 15 | @Service 16 | public class TestService2Impl implements TestService2 { 17 | 18 | private static final Logger LOGGER = LoggerFactory.getLogger(TestService2Impl.class); 19 | 20 | @Override 21 | @RedisLock(lockKey = "lockKey", expireTime = 100, retryCount = 3) 22 | public String method2(@RedisLockKey(type = RedisLockKeyType.ALL) String num) throws InterruptedException { 23 | int sleepMS = 1000; 24 | Thread.sleep(sleepMS); 25 | LOGGER.info("method2 ... 休眠{}ms num={}",sleepMS,num); 26 | return "method2"; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /aspectDemo/src/main/java/com/xiongyx/service/impl/TestServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.service.impl; 2 | 3 | import com.xiongyx.annotation.RedisLock; 4 | import com.xiongyx.annotation.RedisLockKey; 5 | import com.xiongyx.aspect.RedisLockAspect; 6 | import com.xiongyx.enums.RedisLockKeyType; 7 | import com.xiongyx.service.api.TestService; 8 | import com.xiongyx.service.api.TestService2; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.stereotype.Service; 13 | 14 | /** 15 | * @Author xiongyx 16 | * on 2019/4/12. 17 | */ 18 | @Service 19 | public class TestServiceImpl implements TestService { 20 | private static final Logger LOGGER = LoggerFactory.getLogger(TestServiceImpl.class); 21 | 22 | private int number = 0; 23 | 24 | @Autowired 25 | private TestService2 testService2; 26 | 27 | @Override 28 | @RedisLock(lockKey = "lockKey", retryCount = 50, expireTime = 100) 29 | public String method1(@RedisLockKey(type = RedisLockKeyType.ALL) String num) throws InterruptedException { 30 | int sleepMS = 3000; 31 | Thread.sleep(sleepMS); 32 | number = number + 10; 33 | LOGGER.info("method1 ... 休眠{}ms num={}",sleepMS,num); 34 | testService2.method2(num); 35 | return "method1 " + number; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /aspectDemo/src/main/java/com/xiongyx/util/RedisLockKeyUtil.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.util; 2 | 3 | import com.xiongyx.annotation.RedisLock; 4 | import com.xiongyx.annotation.RedisLockKey; 5 | import com.xiongyx.constants.RedisConstants; 6 | import io.netty.util.internal.StringUtil; 7 | import org.aspectj.lang.ProceedingJoinPoint; 8 | import org.aspectj.lang.reflect.MethodSignature; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.util.StringUtils; 12 | 13 | import java.lang.annotation.Annotation; 14 | import java.lang.reflect.Method; 15 | import java.util.Map; 16 | 17 | /** 18 | * @author xiongyx 19 | * @date 2019/5/21 20 | */ 21 | public class RedisLockKeyUtil { 22 | 23 | private static final Logger LOGGER = LoggerFactory.getLogger(RedisLockKeyUtil.class); 24 | 25 | /** 26 | * 拼接redis最终的key 27 | * */ 28 | public static String getFinallyLockKey(String applicationName, RedisLock annotation, ProceedingJoinPoint proceedingJoinPoint){ 29 | StringBuilder keyStringBuilder = new StringBuilder(); 30 | 31 | // 拼接所在应用名字 32 | keyStringBuilder.append(applicationName) 33 | .append(RedisConstants.KEY_SEPARATOR); 34 | 35 | // 拼接当前方法所在类名 36 | String className = proceedingJoinPoint.getTarget().getClass().getSimpleName(); 37 | keyStringBuilder.append(className) 38 | .append(RedisConstants.KEY_SEPARATOR); 39 | 40 | // 拼接当前方法所在方法名 41 | String methodName = proceedingJoinPoint.getSignature().getName(); 42 | keyStringBuilder.append(methodName) 43 | .append(RedisConstants.KEY_SEPARATOR); 44 | 45 | // 拼接注解中的key 46 | if(!StringUtils.isEmpty(annotation.lockKey())){ 47 | keyStringBuilder.append(annotation.lockKey()) 48 | .append(RedisConstants.KEY_SEPARATOR); 49 | } 50 | 51 | // 拼接注解参数中的值 52 | String paramKey = getRedisLockKeyFormParam(proceedingJoinPoint); 53 | if(!StringUtils.isEmpty(paramKey)){ 54 | keyStringBuilder.append(paramKey) 55 | .append(RedisConstants.KEY_SEPARATOR); 56 | } 57 | 58 | return keyStringBuilder.toString(); 59 | } 60 | 61 | /** 62 | * 从参数中获取拼接key的元素 63 | * */ 64 | private static String getRedisLockKeyFormParam(ProceedingJoinPoint proceedingJoinPoint) { 65 | MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature(); 66 | Annotation[][] parameterAnnotations = signature.getMethod().getParameterAnnotations(); 67 | 68 | // 方法参数 69 | Object[] args = proceedingJoinPoint.getArgs(); 70 | 71 | for(int i=0; i 2 | 3 | 4 | 5 | 并发测试 6 | 7 | 8 | 9 | 29 | 30 | 并发测试 31 | 32 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 4.0.0 6 | 7 | DistributeLock 8 | DistributeLock 9 | pom 10 | 1.0-SNAPSHOT 11 | 12 | aspectDemo 13 | redisDistributeLock 14 | 15 | 16 | DistributeLock 17 | 18 | 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-dependencies 24 | 2.0.1.RELEASE 25 | pom 26 | import 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | org.apache.maven.plugins 35 | maven-compiler-plugin 36 | 37 | 1.8 38 | 1.8 39 | 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-maven-plugin 45 | 2.0.1.RELEASE 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /redisDistributeLock/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | DistributeLock 7 | DistributeLock 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | redisDistributeLock 13 | 14 | 15 | 16 | org.springframework.boot 17 | spring-boot-starter-data-redis 18 | 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-web 24 | 25 | 26 | redis.clients 27 | jedis 28 | 29 | 30 | 31 | 32 | 33 | 34 | org.apache.maven.plugins 35 | maven-compiler-plugin 36 | 37 | 1.8 38 | 1.8 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/ApplicationMain.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * @author xiongyx 8 | * on 2019/5/18. 9 | */ 10 | @SpringBootApplication 11 | public class ApplicationMain { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(ApplicationMain.class,args); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/TestServiceA.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx; 2 | 3 | import com.xiongyx.lock.impl.RedisDistributeLock; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.transaction.annotation.Transactional; 7 | 8 | import javax.annotation.PostConstruct; 9 | import javax.annotation.Resource; 10 | import java.util.concurrent.Executors; 11 | import java.util.concurrent.TimeUnit; 12 | import java.util.concurrent.atomic.AtomicInteger; 13 | 14 | /** 15 | *

16 | * Description: 17 | *

18 | * 19 | * @author zhangjw 20 | * @version 1.0 21 | */ 22 | @Service 23 | public class TestServiceA { 24 | private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(TestServiceA.class); 25 | 26 | @Resource 27 | private RedisDistributeLock redisDistributeLock; 28 | 29 | 30 | private AtomicInteger count = new AtomicInteger(); 31 | 32 | 33 | @Transactional 34 | public void exeTask(Integer i) { 35 | try { 36 | String s = redisDistributeLock.lockAndRetry(i.toString(), 2000, 1); 37 | TimeUnit.SECONDS.sleep(8); 38 | count.incrementAndGet(); 39 | redisDistributeLock.unLock(i.toString(),s); 40 | } catch (InterruptedException e) { 41 | e.printStackTrace(); 42 | } 43 | } 44 | 45 | @PostConstruct 46 | public void monitor() { 47 | // Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate((Runnable) () -> { 48 | // 49 | // int qps = count.getAndSet(0); 50 | // LOGGER.info("qps = {}", qps); 51 | // 52 | // }, 0, 1, TimeUnit.SECONDS); 53 | 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/config/JedisConfig.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | import org.springframework.stereotype.Component; 6 | 7 | /** 8 | * @author xiongyx 9 | * on 2019/5/18. 10 | */ 11 | @Component 12 | @ConfigurationProperties 13 | public class JedisConfig { 14 | @Value("${spring.redis.host}") 15 | public String host; 16 | @Value("${spring.redis.port}") 17 | public int port; 18 | @Value("${spring.redis.database}") 19 | public int database; 20 | @Value("${spring.redis.jedis.pool.max-idle}") 21 | public int maxIdle; 22 | @Value("${spring.redis.jedis.pool.min-idle}") 23 | public int minIdle; 24 | @Value("${spring.redis.jedis.pool.max-active}") 25 | public int maxActive; 26 | @Value("${spring.redis.jedis.pool.max-wait}") 27 | public String maxWait; 28 | @Value("${spring.redis.timeout}") 29 | public String timeout; 30 | 31 | public String getHost() { 32 | return host; 33 | } 34 | 35 | public void setHost(String host) { 36 | this.host = host; 37 | } 38 | 39 | public int getPort() { 40 | return port; 41 | } 42 | 43 | public void setPort(int port) { 44 | this.port = port; 45 | } 46 | 47 | public int getDatabase() { 48 | return database; 49 | } 50 | 51 | public void setDatabase(int database) { 52 | this.database = database; 53 | } 54 | 55 | public int getMaxIdle() { 56 | return maxIdle; 57 | } 58 | 59 | public void setMaxIdle(int maxIdle) { 60 | this.maxIdle = maxIdle; 61 | } 62 | 63 | public int getMinIdle() { 64 | return minIdle; 65 | } 66 | 67 | public void setMinIdle(int minIdle) { 68 | this.minIdle = minIdle; 69 | } 70 | 71 | public int getMaxActive() { 72 | return maxActive; 73 | } 74 | 75 | public void setMaxActive(int maxActive) { 76 | this.maxActive = maxActive; 77 | } 78 | 79 | public String getMaxWait() { 80 | return maxWait; 81 | } 82 | 83 | public void setMaxWait(String maxWait) { 84 | this.maxWait = maxWait; 85 | } 86 | 87 | public String getTimeout() { 88 | return timeout; 89 | } 90 | 91 | public void setTimeout(String timeout) { 92 | this.timeout = timeout; 93 | } 94 | } -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/config/RedisConfig.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.config; 2 | 3 | import com.fasterxml.jackson.annotation.JsonAutoDetect; 4 | import com.fasterxml.jackson.annotation.PropertyAccessor; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.cache.annotation.CachingConfigurerSupport; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.data.redis.connection.RedisStandaloneConfiguration; 11 | import org.springframework.data.redis.connection.jedis.JedisClientConfiguration; 12 | import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; 13 | import org.springframework.data.redis.core.RedisTemplate; 14 | import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 15 | import org.springframework.data.redis.serializer.StringRedisSerializer; 16 | import redis.clients.jedis.JedisPoolConfig; 17 | 18 | import java.time.Duration; 19 | 20 | /** 21 | * @author xiongyx 22 | * redis 相关配置 23 | */ 24 | @Configuration 25 | public class RedisConfig extends CachingConfigurerSupport { 26 | 27 | @Autowired 28 | private JedisConfig jedisConfig; 29 | 30 | @Bean 31 | public JedisConnectionFactory jedisConnectionFactory (){ 32 | JedisPoolConfig poolConfig = new JedisPoolConfig(); 33 | poolConfig.setMaxTotal(jedisConfig.getMaxActive()); 34 | poolConfig.setMaxIdle(jedisConfig.getMaxIdle()); 35 | int maxWait = Integer.parseInt(jedisConfig.getMaxWait().substring(0,jedisConfig.maxWait.length()-2)); 36 | poolConfig.setMaxWaitMillis(maxWait); 37 | poolConfig.setMinIdle(jedisConfig.getMaxIdle()); 38 | poolConfig.setTestOnBorrow(true); 39 | poolConfig.setTestOnReturn(false); 40 | poolConfig.setTestWhileIdle(true); 41 | 42 | int readTimeout = Integer.parseInt(jedisConfig.getTimeout().substring(0,jedisConfig.maxWait.length()-2)); 43 | // 使用jedis连接池 44 | JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder() 45 | .usePooling().poolConfig(poolConfig) 46 | .and().readTimeout(Duration.ofMillis(readTimeout)).build(); 47 | 48 | RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); 49 | redisStandaloneConfiguration.setDatabase(jedisConfig.getDatabase()); 50 | redisStandaloneConfiguration.setPort(jedisConfig.getPort()); 51 | redisStandaloneConfiguration.setHostName(jedisConfig.getHost()); 52 | 53 | return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration); 54 | } 55 | 56 | /** 57 | * retemplate相关配置 58 | */ 59 | @Bean 60 | public RedisTemplate redisTemplate(JedisConnectionFactory factory) { 61 | RedisTemplate template = new RedisTemplate<>(); 62 | 63 | // 配置连接工厂 64 | template.setConnectionFactory(factory); 65 | 66 | //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式) 67 | Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer<>(Object.class); 68 | 69 | ObjectMapper om = new ObjectMapper(); 70 | // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public 71 | om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 72 | // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常 73 | om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 74 | jacksonSeial.setObjectMapper(om); 75 | 76 | // 值采用json序列化 77 | template.setValueSerializer(jacksonSeial); 78 | //使用StringRedisSerializer来序列化和反序列化redis的key值 79 | template.setKeySerializer(new StringRedisSerializer()); 80 | 81 | // 设置hash key 和value序列化模式 82 | template.setHashKeySerializer(new StringRedisSerializer()); 83 | template.setHashValueSerializer(jacksonSeial); 84 | template.afterPropertiesSet(); 85 | 86 | return template; 87 | } 88 | } -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/constants/RedisConstants.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.constants; 2 | 3 | /** 4 | * @Desciption: 5 | * @author: Chai jin qiu 6 | * @date: 2019/5/22 7 | */ 8 | public class RedisConstants { 9 | 10 | /** 11 | * key的分隔符 12 | */ 13 | public static final String KEY_SEPARATOR = ":"; 14 | /** 15 | * key的最大字节数 16 | */ 17 | public static final int FINALLY_KEY_LIMIT = 256; 18 | } 19 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.controller; 2 | 3 | import com.xiongyx.TestServiceA; 4 | import com.xiongyx.lock.impl.RedisDistributeLock; 5 | import com.xiongyx.redis.RedisClient; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RequestParam; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import javax.annotation.Resource; 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | import java.util.concurrent.ExecutionException; 15 | import java.util.concurrent.ExecutorService; 16 | import java.util.concurrent.Executors; 17 | import java.util.concurrent.Future; 18 | 19 | /** 20 | * @author xiongyx 21 | * on 2019/5/18. 22 | */ 23 | 24 | @RestController 25 | public class TestController { 26 | 27 | private static final String TEST_REDIS_LOCK_KEY = "lock_key"; 28 | 29 | private static final int EXPIRE_TIME = 100; 30 | 31 | @Resource 32 | private TestServiceA testServiceA; 33 | @Autowired 34 | private RedisDistributeLock redisDistributeLock; 35 | 36 | @Autowired 37 | private RedisClient redisClient; 38 | 39 | 40 | @RequestMapping("/testRedis") 41 | public String testRedis(@RequestParam("id") String id) { 42 | String oldValue = (String)redisClient.get("user_id"); 43 | 44 | redisClient.set("user_id",id); 45 | 46 | String newValue = (String)redisClient.get("user_id"); 47 | return newValue; 48 | } 49 | 50 | @RequestMapping("/test") 51 | public String test() throws ExecutionException, InterruptedException { 52 | int threadNum = 5; 53 | 54 | ExecutorService executorService = Executors.newFixedThreadPool(threadNum); 55 | 56 | List futureList = new ArrayList<>(); 57 | for(int i=0; i{ 60 | System.out.println("线程尝试获得锁 i=" + currentThreadNum); 61 | String requestID = redisDistributeLock.lockAndRetry(TEST_REDIS_LOCK_KEY,EXPIRE_TIME); 62 | System.out.println("获得锁,开始执行任务 requestID=" + requestID + "i=" + currentThreadNum); 63 | 64 | // if(currentThreadNum == 1){ 65 | // System.out.println("模拟 宕机事件 不释放锁,直接返回 currentThreadNum=" + currentThreadNum); 66 | // return; 67 | // } 68 | 69 | try { 70 | // 休眠完毕 71 | Thread.sleep(3000); 72 | } catch (InterruptedException e) { 73 | e.printStackTrace(); 74 | } 75 | System.out.println("任务执行完毕" + "i=" + currentThreadNum); 76 | redisDistributeLock.unLock(TEST_REDIS_LOCK_KEY,requestID); 77 | System.out.println("释放锁完毕"); 78 | 79 | redisDistributeLock.lockAndRetry(TEST_REDIS_LOCK_KEY,requestID,EXPIRE_TIME); 80 | System.out.println("重入获得锁,开始执行任务 requestID=" + requestID + "i=" + currentThreadNum); 81 | redisDistributeLock.unLock(TEST_REDIS_LOCK_KEY,requestID); 82 | System.out.println("释放重入锁完毕"); 83 | }); 84 | 85 | futureList.add(future); 86 | } 87 | 88 | for(Future future : futureList){ 89 | future.get(); 90 | } 91 | 92 | return "ok"; 93 | } 94 | 95 | 96 | @RequestMapping("/testLock") 97 | public String testLock(Integer threadNum) throws ExecutionException, InterruptedException { 98 | ExecutorService executorService = Executors.newFixedThreadPool(threadNum); 99 | 100 | List futureList = new ArrayList<>(); 101 | for (int i = 0; i < threadNum; i++) { 102 | int currentThreadNum = i; 103 | executorService.execute(() -> { 104 | testServiceA.exeTask(currentThreadNum); 105 | }); 106 | } 107 | return "ok"; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/exception/RedisLockFailException.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.exception; 2 | 3 | /** 4 | * @author xiongyx 5 | * @date 2019/5/27 6 | * 7 | * redis分布式锁 加锁失败异常 8 | */ 9 | public class RedisLockFailException extends RuntimeException { 10 | 11 | public RedisLockFailException(String message) { 12 | super(message); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/lock/api/DistributeLock.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.lock.api; 2 | 3 | /** 4 | * 分布式锁 api接口 5 | */ 6 | public interface DistributeLock { 7 | 8 | /** 9 | * 尝试加锁 10 | * @param lockKey 锁的key 11 | * @return 加锁成功 返回uuid 12 | * 加锁失败 返回null 13 | * */ 14 | String lock(String lockKey); 15 | 16 | /** 17 | * 尝试加锁 (requestID相等 可重入) 18 | * @param lockKey 锁的key 19 | * @param expireTime 过期时间 单位:秒 20 | * @return 加锁成功 返回uuid 21 | * 加锁失败 返回null 22 | * */ 23 | String lock(String lockKey, int expireTime); 24 | 25 | /** 26 | * 尝试加锁 (requestID相等 可重入) 27 | * @param lockKey 锁的key 28 | * @param requestID 用户ID 29 | * @return 加锁成功 返回uuid 30 | * 加锁失败 返回null 31 | * */ 32 | String lock(String lockKey, String requestID); 33 | 34 | /** 35 | * 尝试加锁 (requestID相等 可重入) 36 | * @param lockKey 锁的key 37 | * @param requestID 用户ID 38 | * @param expireTime 过期时间 单位:秒 39 | * @return 加锁成功 返回uuid 40 | * 加锁失败 返回null 41 | * */ 42 | String lock(String lockKey, String requestID, int expireTime); 43 | 44 | /** 45 | * 尝试加锁,失败自动重试 会阻塞当前线程 46 | * @param lockKey 锁的key 47 | * @return 加锁成功 返回uuid 48 | * 加锁失败 返回null 49 | * */ 50 | String lockAndRetry(String lockKey); 51 | 52 | /** 53 | * 尝试加锁,失败自动重试 会阻塞当前线程 (requestID相等 可重入) 54 | * @param lockKey 锁的key 55 | * @param requestID 用户ID 56 | * @return 加锁成功 返回uuid 57 | * 加锁失败 返回null 58 | * */ 59 | String lockAndRetry(String lockKey, String requestID); 60 | 61 | /** 62 | * 尝试加锁 (requestID相等 可重入) 63 | * @param lockKey 锁的key 64 | * @param expireTime 过期时间 单位:秒 65 | * @return 加锁成功 返回uuid 66 | * 加锁失败 返回null 67 | * */ 68 | String lockAndRetry(String lockKey, int expireTime); 69 | 70 | /** 71 | * 尝试加锁 (requestID相等 可重入) 72 | * @param lockKey 锁的key 73 | * @param expireTime 过期时间 单位:秒 74 | * @param retryCount 重试次数 75 | * @return 加锁成功 返回uuid 76 | * 加锁失败 返回null 77 | * */ 78 | String lockAndRetry(String lockKey, int expireTime, int retryCount); 79 | 80 | /** 81 | * 尝试加锁 (requestID相等 可重入) 82 | * @param lockKey 锁的key 83 | * @param requestID 用户ID 84 | * @param expireTime 过期时间 单位:秒 85 | * @return 加锁成功 返回uuid 86 | * 加锁失败 返回null 87 | * */ 88 | String lockAndRetry(String lockKey, String requestID, int expireTime); 89 | 90 | /** 91 | * 尝试加锁 (requestID相等 可重入) 92 | * @param lockKey 锁的key 93 | * @param expireTime 过期时间 单位:秒 94 | * @param requestID 用户ID 95 | * @param retryCount 重试次数 96 | * @return 加锁成功 返回uuid 97 | * 加锁失败 返回null 98 | * */ 99 | String lockAndRetry(String lockKey, String requestID, int expireTime, int retryCount); 100 | 101 | /** 102 | * 释放锁 103 | * @param lockKey 锁的key 104 | * @param requestID 用户ID 105 | * @return true 释放自己所持有的锁 成功 106 | * false 释放自己所持有的锁 失败 107 | * */ 108 | boolean unLock(String lockKey, String requestID); 109 | } 110 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/lock/impl/RedisDistributeLock.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.lock.impl; 2 | 3 | import com.xiongyx.lock.api.DistributeLock; 4 | import com.xiongyx.lock.script.LuaScript; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.stereotype.Component; 8 | import com.xiongyx.redis.RedisClient; 9 | 10 | import javax.annotation.Resource; 11 | import java.io.IOException; 12 | import java.util.*; 13 | 14 | /** 15 | * redis 分布式锁的简单实现 16 | * @author xiongyx 17 | */ 18 | @Component("distributeLock") 19 | public final class RedisDistributeLock implements DistributeLock { 20 | 21 | /** 22 | * 无限重试 23 | * */ 24 | public static final int UN_LIMIT_RETRY_COUNT = -1; 25 | 26 | private RedisDistributeLock() { 27 | try { 28 | LuaScript.initLockScript(); 29 | LuaScript.initUnLockScript(); 30 | } catch (IOException e) { 31 | throw new RuntimeException("LuaScript init error!",e); 32 | } 33 | } 34 | 35 | /** 36 | * 持有锁 成功标识 37 | * */ 38 | private static final Long ADD_LOCK_SUCCESS = 1L; 39 | /** 40 | * 释放锁 失败标识 41 | * */ 42 | private static final Long RELEASE_LOCK_SUCCESS = 1L; 43 | 44 | /** 45 | * 默认过期时间 单位:秒 46 | * */ 47 | private static final int DEFAULT_EXPIRE_TIME_SECOND = 300; 48 | /** 49 | * 默认加锁重试时间 单位:毫秒 50 | * */ 51 | private static final int DEFAULT_RETRY_FIXED_TIME = 100; 52 | /** 53 | * 默认的加锁浮动时间区间 单位:毫秒 54 | * */ 55 | private static final int DEFAULT_RETRY_TIME_RANGE = 10; 56 | /** 57 | * 默认的加锁重试次数 58 | * */ 59 | private static final int DEFAULT_RETRY_COUNT = 30; 60 | 61 | @Resource 62 | private RedisClient redisClient; 63 | 64 | //===========================================api======================================= 65 | 66 | @Override 67 | public String lock(String lockKey) { 68 | String uuid = UUID.randomUUID().toString(); 69 | 70 | return lock(lockKey,uuid); 71 | } 72 | 73 | @Override 74 | public String lock(String lockKey, int expireTime) { 75 | String uuid = UUID.randomUUID().toString(); 76 | 77 | return lock(lockKey,uuid,expireTime); 78 | } 79 | 80 | @Override 81 | public String lock(String lockKey, String requestID) { 82 | return lock(lockKey,requestID,DEFAULT_EXPIRE_TIME_SECOND); 83 | } 84 | 85 | @Override 86 | public String lock(String lockKey, String requestID, int expireTime) { 87 | List keyList = Collections.singletonList(lockKey); 88 | 89 | List argsList = Arrays.asList( 90 | requestID, 91 | expireTime + "" 92 | ); 93 | Long result = (Long)redisClient.eval(LuaScript.LOCK_SCRIPT, keyList, argsList); 94 | 95 | if(result.equals(ADD_LOCK_SUCCESS)){ 96 | return requestID; 97 | }else{ 98 | return null; 99 | } 100 | } 101 | 102 | @Override 103 | public String lockAndRetry(String lockKey) { 104 | String uuid = UUID.randomUUID().toString(); 105 | 106 | return lockAndRetry(lockKey,uuid); 107 | } 108 | 109 | @Override 110 | public String lockAndRetry(String lockKey, String requestID) { 111 | return lockAndRetry(lockKey,requestID,DEFAULT_EXPIRE_TIME_SECOND); 112 | } 113 | 114 | @Override 115 | public String lockAndRetry(String lockKey, int expireTime) { 116 | String uuid = UUID.randomUUID().toString(); 117 | 118 | return lockAndRetry(lockKey,uuid,expireTime); 119 | } 120 | 121 | @Override 122 | public String lockAndRetry(String lockKey, int expireTime, int retryCount) { 123 | String uuid = UUID.randomUUID().toString(); 124 | 125 | return lockAndRetry(lockKey,uuid,expireTime,retryCount); 126 | } 127 | 128 | @Override 129 | public String lockAndRetry(String lockKey, String requestID, int expireTime) { 130 | return lockAndRetry(lockKey,requestID,expireTime,DEFAULT_RETRY_COUNT); 131 | } 132 | 133 | @Override 134 | public String lockAndRetry(String lockKey, String requestID, int expireTime, int retryCount) { 135 | if(retryCount <= 0){ 136 | // retryCount小于等于0 无限循环,一直尝试加锁 137 | while(true){ 138 | String result = lock(lockKey,requestID,expireTime); 139 | if(result != null){ 140 | return result; 141 | } 142 | 143 | // 休眠一会 144 | sleepSomeTime(); 145 | } 146 | }else{ 147 | // retryCount大于0 尝试指定次数后,退出 148 | for(int i=0; i keyList = Collections.singletonList(lockKey); 165 | 166 | List argsList = Collections.singletonList(requestID); 167 | 168 | Object result = redisClient.eval(LuaScript.UN_LOCK_SCRIPT, keyList, argsList); 169 | 170 | // 释放锁成功 171 | return RELEASE_LOCK_SUCCESS.equals(result); 172 | } 173 | 174 | //==============================================私有方法======================================== 175 | 176 | /** 177 | * 获得最终的获得锁的重试时间 178 | * */ 179 | private int getFinallyGetLockRetryTime(){ 180 | Random ra = new Random(); 181 | 182 | // 最终重试时间 = 固定时间 + 浮动时间 183 | return DEFAULT_RETRY_FIXED_TIME + ra.nextInt(DEFAULT_RETRY_TIME_RANGE); 184 | } 185 | 186 | /** 187 | * 当前线程 休眠一段时间 188 | * */ 189 | private void sleepSomeTime(){ 190 | // 重试时间 单位:毫秒 191 | int retryTime = getFinallyGetLockRetryTime(); 192 | try { 193 | Thread.sleep(retryTime); 194 | } catch (InterruptedException e) { 195 | throw new RuntimeException("redis锁重试时,出现异常",e); 196 | } 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/lock/script/LuaScript.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.lock.script; 2 | 3 | import org.springframework.util.StringUtils; 4 | 5 | import java.io.*; 6 | import java.util.Objects; 7 | 8 | /** 9 | * @Author xiongyx 10 | * on 2019/4/9. 11 | */ 12 | public class LuaScript { 13 | 14 | /** 15 | * 加锁脚本 lock.lua 16 | * 1. 判断key是否存在 17 | * 2. 如果存在,判断requestID是否相等 18 | * 相等,则删除掉key重新创建新的key值,重置过期时间 19 | * 不相等,说明已经被抢占,加锁失败,返回null 20 | * 3. 如果不存在,说明恰好已经过期,重新生成key 21 | */ 22 | public static String LOCK_SCRIPT; 23 | 24 | /** 25 | * 解锁脚本 unlock.lua 26 | */ 27 | public static String UN_LOCK_SCRIPT; 28 | 29 | public static void initLockScript() throws IOException { 30 | if (StringUtils.isEmpty(LOCK_SCRIPT)) { 31 | InputStream inputStream = Objects.requireNonNull( 32 | LuaScript.class.getClassLoader().getResourceAsStream("lock.lua")); 33 | LOCK_SCRIPT = readFile(inputStream); 34 | } 35 | } 36 | 37 | public static void initUnLockScript() throws IOException { 38 | if (StringUtils.isEmpty(UN_LOCK_SCRIPT)) { 39 | InputStream inputStream = Objects.requireNonNull( 40 | LuaScript.class.getClassLoader().getResourceAsStream("unlock.lua")); 41 | UN_LOCK_SCRIPT = readFile(inputStream); 42 | } 43 | } 44 | 45 | private static String readFile(InputStream inputStream) throws IOException { 46 | try ( 47 | BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)) 48 | ) { 49 | String line; 50 | StringBuilder stringBuilder = new StringBuilder(); 51 | while ((line = br.readLine()) != null) { 52 | stringBuilder.append(line) 53 | .append(System.lineSeparator()); 54 | } 55 | 56 | return stringBuilder.toString(); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/redis/RedisClient.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.redis; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | /** 8 | * @author xiongyx 9 | * @date 2019/5/21 10 | */ 11 | public interface RedisClient { 12 | 13 | /** 14 | * 执行脚本 15 | * */ 16 | Object eval(String script, List keys, List args); 17 | 18 | /** 19 | * get 20 | * */ 21 | Object get(String key); 22 | 23 | /** 24 | * set 25 | * */ 26 | void set(String key, Object value); 27 | 28 | /** 29 | * set 30 | * */ 31 | void set(String key, Object value, long expireTime, TimeUnit timeUnit); 32 | 33 | /** 34 | * setNX 35 | * */ 36 | Boolean setNX(String key, Object value); 37 | 38 | /** 39 | * 设置过期时间 40 | * */ 41 | Boolean expire(String key, long time, TimeUnit type); 42 | 43 | /** 44 | * 移除过期时间 45 | * */ 46 | Boolean persist(String key); 47 | 48 | /** 49 | * 增加 50 | * */ 51 | Long increment(String key, long number); 52 | 53 | /** 54 | * 增加 55 | * */ 56 | Double increment(String key, double number); 57 | 58 | /** 59 | * 删除 60 | * */ 61 | Boolean delete(String key); 62 | 63 | // ==========================hash======================== 64 | 65 | void hset(String key, String hashKey, Object value); 66 | 67 | void hsetAll(String key, Map map); 68 | 69 | Boolean hsetNX(String key, String hashKey, Object value); 70 | 71 | Object hget(String key, String hashKey); 72 | 73 | Map hgetAll(String key); 74 | } 75 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/redis/RedisClientImpl.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.redis; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.data.redis.core.RedisCallback; 5 | import org.springframework.data.redis.core.RedisTemplate; 6 | import org.springframework.data.redis.core.script.DefaultRedisScript; 7 | import org.springframework.stereotype.Component; 8 | import redis.clients.jedis.Jedis; 9 | import redis.clients.jedis.JedisCluster; 10 | 11 | import java.util.List; 12 | import java.util.Map; 13 | import java.util.concurrent.TimeUnit; 14 | 15 | /** 16 | * @author xiongyx 17 | * @date 2019/4/3 18 | */ 19 | @Component("redisClient") 20 | public class RedisClientImpl implements RedisClient{ 21 | 22 | @Autowired 23 | private RedisTemplate redisTemplate; 24 | 25 | @Override 26 | public Object eval(String script, List keys, List args) { 27 | DefaultRedisScript redisScript = new DefaultRedisScript<>(); 28 | redisScript.setScriptText(script); 29 | redisScript.setResultType(Integer.class); 30 | 31 | Object result = redisTemplate.execute((RedisCallback) redisConnection ->{ 32 | Object nativeConnection = redisConnection.getNativeConnection(); 33 | // 集群模式和单机模式虽然执行脚本的方法一样,但是没有共同的接口,所以只能分开执行 34 | // 集群模式 35 | if (nativeConnection instanceof JedisCluster) { 36 | return (Long) ((JedisCluster) nativeConnection).eval(script, keys, args); 37 | } 38 | 39 | // 单机模式 40 | else if (nativeConnection instanceof Jedis) { 41 | return (Long) ((Jedis) nativeConnection).eval(script, keys, args); 42 | } 43 | return -1L; 44 | }); 45 | return result; 46 | } 47 | 48 | @Override 49 | public Object get(String key){ 50 | return redisTemplate.opsForValue().get(key); 51 | } 52 | 53 | @Override 54 | public void set(String key,Object value){ 55 | redisTemplate.opsForValue().set(key,value); 56 | } 57 | 58 | @Override 59 | public void set(String key, Object value, long expireTime, TimeUnit timeUnit) { 60 | redisTemplate.opsForValue().set(key,value,expireTime,timeUnit); 61 | } 62 | 63 | @Override 64 | public Boolean setNX(String key, Object value) { 65 | return redisTemplate.opsForValue().setIfAbsent(key,value); 66 | } 67 | 68 | @Override 69 | public Boolean expire(String key, long time, TimeUnit timeUnit) { 70 | return redisTemplate.boundValueOps(key).expire(time, timeUnit); 71 | } 72 | 73 | @Override 74 | public Boolean persist(String key){ 75 | return redisTemplate.boundValueOps(key).persist(); 76 | } 77 | 78 | @Override 79 | public Long increment(String key, long number) { 80 | return redisTemplate.opsForValue().increment(key, number); 81 | } 82 | 83 | @Override 84 | public Double increment(String key, double number) { 85 | return redisTemplate.opsForValue().increment(key, number); 86 | } 87 | 88 | @Override 89 | public Boolean delete(String key) { 90 | return redisTemplate.delete(key); 91 | } 92 | 93 | @Override 94 | public void hset(String key, String hashKey, Object value) { 95 | redisTemplate.opsForHash().put(key, hashKey, value); 96 | } 97 | 98 | @Override 99 | public void hsetAll(String key, Map map) { 100 | redisTemplate.opsForHash().putAll(key, map); 101 | } 102 | 103 | @Override 104 | public Boolean hsetNX(String key, String hashKey, Object value) { 105 | return redisTemplate.opsForHash().putIfAbsent(key, hashKey, value); 106 | } 107 | 108 | @Override 109 | public Object hget(String key, String hashKey) { 110 | return redisTemplate.opsForHash().get(key,hashKey); 111 | } 112 | 113 | @Override 114 | public Map hgetAll(String key) { 115 | return redisTemplate.opsForHash().entries(key); 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/util/CastUtil.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.util; 2 | 3 | /** 4 | * @Author xiongyx 5 | * @Create 2018/4/13. 6 | * 7 | * 类型转换工具类 8 | */ 9 | public final class CastUtil { 10 | 11 | /** 12 | * 转为 string 13 | * */ 14 | public static String castToString(Object obj){ 15 | return castToString(obj,""); 16 | } 17 | 18 | /** 19 | * 转为 string 提供默认值 20 | * */ 21 | public static String castToString(Object obj,String defaultValue){ 22 | if(obj == null){ 23 | return defaultValue; 24 | }else{ 25 | return obj.toString(); 26 | } 27 | } 28 | 29 | /** 30 | * 转为 int 31 | * */ 32 | public static int castToInt(Object obj){ 33 | return castToInt(obj,0); 34 | } 35 | 36 | /** 37 | * 转为 int 提供默认值 38 | * */ 39 | public static int castToInt(Object obj,int defaultValue){ 40 | if(obj == null){ 41 | return defaultValue; 42 | }else{ 43 | return Integer.parseInt(obj.toString()); 44 | } 45 | } 46 | 47 | /** 48 | * 转为 double 49 | * */ 50 | public static double castToDouble(Object obj){ 51 | return castToDouble(obj,0); 52 | } 53 | 54 | /** 55 | * 转为 double 提供默认值 56 | * */ 57 | public static double castToDouble(Object obj,double defaultValue){ 58 | if(obj == null){ 59 | return defaultValue; 60 | }else{ 61 | return Double.parseDouble(obj.toString()); 62 | } 63 | } 64 | 65 | /** 66 | * 转为 long 67 | * */ 68 | public static long castToLong(Object obj){ 69 | return castToLong(obj,0); 70 | } 71 | 72 | /** 73 | * 转为 long 提供默认值 74 | * */ 75 | public static long castToLong(Object obj,long defaultValue){ 76 | if(obj == null){ 77 | return defaultValue; 78 | }else{ 79 | return Long.parseLong(obj.toString()); 80 | } 81 | } 82 | 83 | /** 84 | * 转为 boolean 85 | * */ 86 | public static boolean castToBoolean(Object obj){ 87 | return castToBoolean(obj,false); 88 | } 89 | 90 | /** 91 | * 转为 boolean 提供默认值 92 | * */ 93 | public static boolean castToBoolean(Object obj,boolean defaultValue){ 94 | if(obj == null){ 95 | return defaultValue; 96 | }else{ 97 | return Boolean.parseBoolean(obj.toString()); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/java/com/xiongyx/util/PropsUtil.java: -------------------------------------------------------------------------------- 1 | package com.xiongyx.util; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import java.io.FileNotFoundException; 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | import java.util.Properties; 10 | 11 | /** 12 | * @Author xiongyx 13 | * @Create 2018/4/11. 14 | */ 15 | public final class PropsUtil { 16 | 17 | private static final Logger LOGGER = LoggerFactory.getLogger(PropsUtil.class); 18 | 19 | /** 20 | * 读取配置文件 21 | * */ 22 | public static Properties loadProps(String fileName){ 23 | Properties props = null; 24 | InputStream is = null; 25 | try{ 26 | // 绝对路径获得输入流 27 | is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); 28 | if(is == null){ 29 | // 没找到文件,抛出异常 30 | throw new FileNotFoundException(fileName + " is not found"); 31 | } 32 | props = new Properties(); 33 | props.load(is); 34 | }catch(IOException e){ 35 | LOGGER.error("load propertis file fail",e); 36 | }finally { 37 | if(is != null){ 38 | try{ 39 | // 关闭io流 40 | is.close(); 41 | } catch (IOException e) { 42 | LOGGER.error("close input Stream fail",e); 43 | } 44 | } 45 | } 46 | 47 | return props; 48 | } 49 | 50 | /** 51 | * 获取字符串属性(默认为空字符串) 52 | * */ 53 | public static String getString(Properties properties,String key){ 54 | // 调用重载函数 默认值为:空字符串 55 | return getString(properties,key,""); 56 | } 57 | 58 | /** 59 | * 获取字符串属性 60 | * */ 61 | public static String getString(Properties properties,String key,String defaultValue){ 62 | // key对应的value数据是否存在 63 | if(properties.containsKey(key)){ 64 | return properties.getProperty(key); 65 | }else{ 66 | return defaultValue; 67 | } 68 | } 69 | 70 | /** 71 | * 获取int属性 默认值为0 72 | * */ 73 | public static int getInt(Properties properties,String key){ 74 | // 调用重载函数,默认为:0 75 | return getInt(properties,key,0); 76 | } 77 | 78 | /** 79 | * 获取int属性 80 | * */ 81 | public static int getInt(Properties properties,String key,int defaultValue){ 82 | // key对应的value数据是否存在 83 | if(properties.containsKey(key)){ 84 | return CastUtil.castToInt(properties.getProperty(key)); 85 | }else{ 86 | return defaultValue; 87 | } 88 | } 89 | 90 | /** 91 | * 获取boolean属性,默认值为false 92 | */ 93 | public static boolean getBoolean(Properties properties,String key){ 94 | return getBoolean(properties,key,false); 95 | } 96 | 97 | /** 98 | * 获取boolean属性 99 | */ 100 | public static boolean getBoolean(Properties properties,String key,boolean defaultValue){ 101 | // key对应的value数据是否存在 102 | if(properties.containsKey(key)){ 103 | return CastUtil.castToBoolean(properties.getProperty(key)); 104 | }else{ 105 | return defaultValue; 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8081 2 | 3 | spring.redis.database=5 4 | spring.redis.host=127.0.0.1 5 | spring.redis.port=6379 6 | spring.redis.timeout=3000ms 7 | spring.redis.jedis.pool.max-idle=500 8 | spring.redis.jedis.pool.min-idle=50 9 | spring.redis.jedis.pool.max-active=2000 10 | spring.redis.jedis.pool.max-wait=1000ms -------------------------------------------------------------------------------- /redisDistributeLock/src/main/resources/lock.lua: -------------------------------------------------------------------------------- 1 | -- 获取参数 2 | local requestIDKey = KEYS[1] 3 | 4 | local currentRequestID = ARGV[1] 5 | local expireTimeTTL = ARGV[2] 6 | 7 | -- setnx 尝试加锁 8 | local lockSet = redis.call('hsetnx',KEYS[1],'lockKey',currentRequestID) 9 | 10 | if lockSet == 1 11 | then 12 | -- 加锁成功 设置过期时间和重入次数=1 13 | redis.call('expire',KEYS[1],expireTimeTTL) 14 | redis.call('hset',KEYS[1],'lockCount',1) 15 | return 1 16 | else 17 | -- 判断是否是重入加锁 18 | local oldRequestID = redis.call('hget',KEYS[1],'lockKey') 19 | if currentRequestID == oldRequestID 20 | then 21 | -- 是重入加锁 22 | redis.call('hincrby',KEYS[1],'lockCount',1) 23 | -- 重置过期时间 24 | redis.call('expire',KEYS[1],expireTimeTTL) 25 | return 1 26 | else 27 | -- requestID不一致,加锁失败 28 | return 0 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /redisDistributeLock/src/main/resources/redis.properties: -------------------------------------------------------------------------------- 1 | spring.redis.database=0 2 | spring.redis.host=127.0.0.1 3 | spring.redis.port=6379 4 | spring.redis.timeout=3000ms 5 | spring.redis.jedis.pool.max-idle=500 6 | spring.redis.jedis.pool.min-idle=50 7 | spring.redis.jedis.pool.max-active=2000 8 | spring.redis.jedis.pool.max-wait=1000ms -------------------------------------------------------------------------------- /redisDistributeLock/src/main/resources/unlock.lua: -------------------------------------------------------------------------------- 1 | -- 获取参数 2 | local requestIDKey = KEYS[1] 3 | 4 | local currentRequestID = ARGV[1] 5 | 6 | -- 判断requestID一致性 7 | if redis.call('hget',KEYS[1],'lockKey') == currentRequestID 8 | then 9 | -- requestID相同,重入次数自减 10 | local currentCount = redis.call('hincrby',KEYS[1],'lockCount',-1) 11 | if currentCount == 0 12 | then 13 | -- 重入次数为0,删除锁 14 | redis.call('del',KEYS[1]) 15 | return 1 16 | else 17 | return 0 end 18 | else 19 | return 0 end --------------------------------------------------------------------------------