├── src ├── main │ ├── resources │ │ ├── image │ │ │ ├── nouse.png │ │ │ ├── use1.png │ │ │ └── use2.png │ │ ├── META-INF │ │ │ └── services │ │ │ │ └── com.it4alla.idempotent.locker.core.LockerProvider │ │ └── application.yml │ └── java │ │ └── com │ │ └── it4alla │ │ └── idempotent │ │ ├── locker │ │ ├── redis │ │ │ ├── JedisUtil.java │ │ │ ├── RedisLocker.java │ │ │ ├── RedissonLockerProvider.java │ │ │ ├── RedissonConfig.java │ │ │ └── RedissonDistributedLocker.java │ │ ├── core │ │ │ ├── LockerProvider.java │ │ │ └── LockerService.java │ │ └── zookeeper │ │ │ ├── ZookeeperProperties.java │ │ │ ├── ZookeeperClient.java │ │ │ └── ZookeeperDistributedLocker.java │ │ ├── controller │ │ ├── UserService.java │ │ ├── UserServiceImpl.java │ │ └── UserController.java │ │ ├── loader │ │ └── EnhancedServiceLoader.java │ │ ├── IdempotentApplication.java │ │ ├── exception │ │ └── IdempotentException.java │ │ ├── annotation │ │ └── Idempotent.java │ │ ├── entity │ │ └── User.java │ │ └── aspect │ │ └── IdempotentAspect.java └── test │ └── java │ └── com │ └── it4alla │ └── idempotent │ └── IdempotentApplicationTests.java ├── .mvn └── wrapper │ ├── maven-wrapper.properties │ └── MavenWrapperDownloader.java ├── .gitignore ├── pom.xml ├── mvnw.cmd ├── mvnw ├── LICENSE └── README.md /src/main/resources/image/nouse.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/it4alla/idempotent/HEAD/src/main/resources/image/nouse.png -------------------------------------------------------------------------------- /src/main/resources/image/use1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/it4alla/idempotent/HEAD/src/main/resources/image/use1.png -------------------------------------------------------------------------------- /src/main/resources/image/use2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/it4alla/idempotent/HEAD/src/main/resources/image/use2.png -------------------------------------------------------------------------------- /src/main/resources/META-INF/services/com.it4alla.idempotent.locker.core.LockerProvider: -------------------------------------------------------------------------------- 1 | com.it4alla.idempotent.locker.redis.RedissonLockerProvider 2 | com.it4alla.idempotent.locker.redis.RedisLocker 3 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/locker/redis/JedisUtil.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.locker.redis; 2 | 3 | /** 4 | * @description: Jedis utils 5 | * 6 | * @author 7 | * @since 1.0.0 8 | */ 9 | public class JedisUtil { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/controller/UserService.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.controller; 2 | 3 | 4 | import com.it4alla.idempotent.entity.User; 5 | 6 | /** 7 | * @author ITyunqing 8 | */ 9 | @Deprecated 10 | public interface UserService { 11 | 12 | void add(User user); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/locker/core/LockerProvider.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.locker.core; 2 | 3 | /** 4 | * @description: LockerProvider 5 | * 6 | * @author ITyunqing 7 | * @since 1.0.0 8 | */ 9 | public interface LockerProvider { 10 | 11 | LockerService provider(); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/it4alla/idempotent/IdempotentApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class IdempotentApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/loader/EnhancedServiceLoader.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.loader; 2 | 3 | /** 4 | * @description: Service Loader 5 | * 6 | * @author ITyunqing 7 | * @since 1.0.0 8 | */ 9 | public class EnhancedServiceLoader { 10 | private static final String SERVICES_DIRECTORY = "META-INF/services/"; 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/locker/redis/RedisLocker.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.locker.redis; 2 | 3 | import com.it4alla.idempotent.locker.core.LockerProvider; 4 | import com.it4alla.idempotent.locker.core.LockerService; 5 | 6 | /** 7 | * @description: RedisLocker 8 | * 9 | * @author 10 | * @since 1.0.0 11 | */ 12 | public class RedisLocker implements LockerProvider { 13 | 14 | @Override 15 | public LockerService provider() { 16 | //TODO 17 | return null; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/IdempotentApplication.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * @description: 启动类 8 | * 9 | * @author ITyunqing 10 | * @since 1.0.0 11 | */ 12 | @SpringBootApplication 13 | public class IdempotentApplication { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(IdempotentApplication.class, args); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/locker/redis/RedissonLockerProvider.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.locker.redis; 2 | 3 | import com.it4alla.idempotent.locker.core.LockerProvider; 4 | import com.it4alla.idempotent.locker.core.LockerService; 5 | 6 | /** 7 | * @description: RedissonLockerProvider 8 | * 9 | * @author ITyunqing 10 | * @since 1.0.0 11 | */ 12 | public class RedissonLockerProvider implements LockerProvider { 13 | 14 | @Override 15 | public LockerService provider() { 16 | return RedissonDistributedLocker.getInstance(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### maven ignor 8 | target/ 9 | *.jar 10 | *.war 11 | *.zip 12 | *.tar 13 | *.tar.gz 14 | *.class 15 | 16 | ### STS ### 17 | .apt_generated 18 | .classpath 19 | .factorypath 20 | .project 21 | .settings 22 | .springBeans 23 | .sts4-cache 24 | 25 | ### eclipse ignore ### 26 | .settings/ 27 | .project 28 | .classpath 29 | 30 | ### IntelliJ IDEA ### 31 | .idea 32 | *.iws 33 | *.iml 34 | *.ipr 35 | 36 | ### NetBeans ### 37 | /nbproject/private/ 38 | /nbbuild/ 39 | /dist/ 40 | /nbdist/ 41 | /.nb-gradle/ 42 | build/ 43 | 44 | ### VS Code ### 45 | .vscode/ 46 | 47 | ### temp ignore ### 48 | *.log 49 | *.cache 50 | *.diff 51 | *.patch 52 | *.tmp 53 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/controller/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.controller; 2 | 3 | import com.it4alla.idempotent.entity.User; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.stereotype.Service; 7 | 8 | /** 9 | * @author ITyunqing 10 | */ 11 | @Deprecated 12 | @Service("userServiceImpl") 13 | public class UserServiceImpl implements UserService{ 14 | private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class); 15 | 16 | @Override 17 | public void add(User user) { 18 | try { 19 | Thread.sleep(1*1000); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | LOGGER.info("添加用户成功"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/locker/core/LockerService.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.locker.core; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | import org.apache.zookeeper.KeeperException; 5 | 6 | /** 7 | * @description: Jedis utils 8 | * 9 | * @author 10 | * @since 1.0.0 11 | */ 12 | public interface LockerService { 13 | 14 | Object lock(String lockKey) throws KeeperException, InterruptedException; 15 | 16 | Object lock(String lockKey,Integer expireTime, TimeUnit timeUnit); 17 | 18 | Object fairLock(String lockKey,Integer expireTime, TimeUnit timeUnit); 19 | 20 | Object tryLock(String lockKey,Integer expireTime, TimeUnit timeUnit,Integer waitTime); 21 | 22 | Object multiLock(Integer expireTime, TimeUnit timeUnit,String ...lockKey); 23 | 24 | void unLock(String lockKey); 25 | 26 | void unLock(Object lock); 27 | 28 | void unLockMultiLock(Object lock); 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/locker/zookeeper/ZookeeperProperties.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.locker.zookeeper; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.stereotype.Component; 5 | 6 | /** 7 | * @description: Zookeeper Properties 8 | * 9 | * @author ITyunqing 10 | * @since 1.0.0 11 | */ 12 | @Component 13 | public class ZookeeperProperties { 14 | 15 | @Value("${zk.host}") 16 | private String zkHost; 17 | @Value("${zk.session.timeout}") 18 | private Integer zkSessionTimeout; 19 | 20 | public String getZkHost() { 21 | return zkHost; 22 | } 23 | 24 | public void setZkHost(String zkHost) { 25 | this.zkHost = zkHost; 26 | } 27 | 28 | public Integer getZkSessionTimeout() { 29 | return zkSessionTimeout; 30 | } 31 | 32 | public void setZkSessionTimeout(Integer zkSessionTimeout) { 33 | this.zkSessionTimeout = zkSessionTimeout; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/exception/IdempotentException.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.exception; 2 | 3 | /** 4 | * @description: Idempotent Exception 5 | * If there is a custom global exception, you need to inherit the custom global exception. 6 | * 7 | * @author ITyunqing 8 | * @since 1.0.0 9 | */ 10 | public class IdempotentException extends Exception{ 11 | 12 | public IdempotentException() { 13 | super(); 14 | } 15 | 16 | public IdempotentException(String message) { 17 | super(message); 18 | } 19 | 20 | public IdempotentException(String message, Throwable cause) { 21 | super(message, cause); 22 | } 23 | 24 | public IdempotentException(Throwable cause) { 25 | super(cause); 26 | } 27 | 28 | protected IdempotentException(String message, Throwable cause, boolean enableSuppression, 29 | boolean writableStackTrace) { 30 | super(message, cause, enableSuppression, writableStackTrace); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.controller; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | import com.it4alla.idempotent.annotation.Idempotent; 6 | import com.it4alla.idempotent.entity.User; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | /** 13 | * @author ITyunqing 14 | */ 15 | @Deprecated 16 | @RestController 17 | @RequestMapping("user") 18 | public class UserController { 19 | 20 | @Autowired 21 | private UserService userServiceImpl; 22 | 23 | @Idempotent(isIdempotent = true,expireTime = 3,timeUnit = TimeUnit.SECONDS,info = "请勿重复添加用户",delKey = false) 24 | @GetMapping(value = "add") 25 | public String add(User user, String love, Integer count){ 26 | userServiceImpl.add(user); 27 | return "添加成功"; 28 | } 29 | 30 | @RequestMapping(value ="test") 31 | public String test(String name){ 32 | return name; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 7777 3 | 4 | #Redisson单机配置 5 | singleServerConfig: 6 | address: "redis://192.168.13.155:6379" 7 | password: RLredis13 8 | #ping节点超时 9 | pingTimeout: 1000 10 | #连接等待超时 11 | connectTimeout: 30000 12 | #命令等待超时 13 | timeout: 3000 14 | #如果当前连接池里的连接数量超过了最小空闲连接数,而同时有连接空闲时间超过了该数值,那么这些连接将会自动被关闭,并从连接池里去掉。时间单位是毫秒。 15 | idleConnectionTimeout: 10000 16 | #如果尝试达到 retryAttempts(命令失败重试次数) 仍然不能将命令发送至某个指定的节点时,将抛出错误。如果尝试在此限制之内发送成功,则开始启用 timeout(命令等待超时) 计时。 17 | retryAttempts: 3 18 | #在一条命令发送失败以后,等待重试发送的时间间隔。时间单位是毫秒。 19 | retryInterval: 3000 20 | #当与某个节点的连接断开时,等待与其重新建立连接的时间间隔。时间单位是毫秒。 21 | reconnectionTimeout: 3000 22 | #在某个节点执行相同或不同命令时,连续 失败 failedAttempts(执行失败最大次数) 时,该节点将被从可用节点列表里清除,直到 reconnectionTimeout(重新连接时间间隔) 超时以后再次尝试。 23 | failedAttempts: 3 24 | #每个连接的最大订阅数量 25 | subscriptionsPerConnection: 5 26 | #用于发布和订阅连接的最小保持连接数(长连接)。Redisson内部经常通过发布和订阅来实现许多功能。长期保持一定数量的发布订阅连接是必须的。 27 | subscriptionConnectionMinimumIdleSize: 1 28 | #用于发布和订阅连接的连接池最大容量。连接池的连接数量自动弹性伸缩。 29 | subscriptionConnectionPoolSize: 500 30 | #最小保持连接数(长连接)。长期保持一定数量的连接有利于提高瞬时写入反应速度。 31 | connectionMinimumIdleSize: 32 32 | #连接池最大容量。连接池的连接数量自动弹性伸缩。 33 | connectionPoolSize: 64 34 | 35 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/annotation/Idempotent.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Inherited; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /** 11 | * @description: Idempotent annotation 12 | * 13 | * @author ITyunqing 14 | * @since 1.0.0 15 | * 16 | * you can use it on your interface in controller like this : 17 | * @Idempotent(idempotent = true,expireTime = 6,timeUnit = TimeUnit.SECONDS,info = "请勿重复添加用户") 18 | * @PutMapping(value = "add") 19 | * public String add(User user){ 20 | * userServiceImpl.add(user); 21 | * return "success"; 22 | * } 23 | */ 24 | @Inherited 25 | @Target(ElementType.METHOD) 26 | @Retention(value = RetentionPolicy.RUNTIME) 27 | public @interface Idempotent { 28 | 29 | 30 | /** 31 | * 是否做幂等处理 32 | * false:非幂等 33 | * true:幂等 34 | * @return 35 | */ 36 | boolean isIdempotent() default false; 37 | 38 | /** 39 | * 有效期 40 | * 默认:1 41 | * 有效期要大于程序执行时间,否则请求还是可能会进来 42 | * @return 43 | */ 44 | int expireTime() default 1; 45 | 46 | /** 47 | * 时间单位 48 | * 默认:s 49 | * @return 50 | */ 51 | TimeUnit timeUnit() default TimeUnit.SECONDS; 52 | 53 | /** 54 | * 提示信息,可自定义 55 | * @return 56 | */ 57 | String info() default "重复请求,请稍后重试"; 58 | 59 | /** 60 | * 是否在业务完成后删除key 61 | * true:删除 62 | * false:不删除 63 | * @return 64 | */ 65 | boolean delKey() default false; 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/locker/zookeeper/ZookeeperClient.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.locker.zookeeper; 2 | 3 | import java.io.IOException; 4 | import java.util.concurrent.CountDownLatch; 5 | import org.apache.zookeeper.WatchedEvent; 6 | import org.apache.zookeeper.Watcher; 7 | import org.apache.zookeeper.Watcher.Event.KeeperState; 8 | import org.apache.zookeeper.ZooKeeper; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | 13 | /** 14 | * @description: Zookeeper Client 15 | * 16 | * @author ITyunqing 17 | * @since 1.0.0 18 | */ 19 | public class ZookeeperClient { 20 | 21 | private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperClient.class); 22 | private static CountDownLatch countDownLatch = new CountDownLatch(1); 23 | 24 | @Autowired 25 | private ZookeeperProperties properties; 26 | 27 | public ZookeeperClient() { 28 | } 29 | 30 | public ZooKeeper getClient(){ 31 | try { 32 | ZooKeeper zookeeper = new ZooKeeper(properties.getZkHost(), 33 | properties.getZkSessionTimeout(), new ZKWatcher()); 34 | countDownLatch.await(); 35 | return zookeeper; 36 | } catch (IOException e) { 37 | e.printStackTrace(); 38 | //FIXME 39 | return null; 40 | } catch (InterruptedException e) { 41 | e.printStackTrace(); 42 | //FIXME 43 | return null; 44 | } 45 | } 46 | 47 | 48 | private class ZKWatcher implements Watcher { 49 | @Override 50 | public void process(WatchedEvent watchedEvent) { 51 | if (KeeperState.SyncConnected == watchedEvent.getState()) { 52 | countDownLatch.countDown(); 53 | LOGGER.info("zookeeper client host:{} connect successed",properties.getZkHost()); 54 | } else { 55 | LOGGER.info("zookeeper client host:{} connecting ......",properties.getZkHost()); 56 | } 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.springframework.boot 8 | spring-boot-starter-parent 9 | 2.2.6.RELEASE 10 | 11 | 12 | com.it4alla 13 | idempotent 14 | 0.0.1-SNAPSHOT 15 | idempotent 16 | An idempotent solution 17 | 18 | 19 | 1.8 20 | 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-web 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-test 31 | test 32 | 33 | 34 | org.junit.vintage 35 | junit-vintage-engine 36 | 37 | 38 | 39 | 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-starter-aop 44 | 45 | 46 | 47 | org.redisson 48 | redisson 49 | 3.5.4 50 | 51 | 52 | 53 | org.apache.zookeeper 54 | zookeeper 55 | 3.4.9 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | org.springframework.boot 64 | spring-boot-maven-plugin 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.entity; 2 | 3 | import java.math.BigDecimal; 4 | 5 | /** 6 | * @description: the user 7 | * 8 | * @author ITyunqing 9 | * @since 1.0.0 10 | */ 11 | @Deprecated 12 | public class User { 13 | 14 | private String id; 15 | 16 | private String name; 17 | 18 | private Integer age; 19 | 20 | private String province; 21 | 22 | private String city; 23 | 24 | private String address; 25 | 26 | private String hobby; 27 | 28 | private BigDecimal money; 29 | 30 | private String school; 31 | 32 | @Override 33 | public String toString() { 34 | return "User{" + 35 | "id='" + id + '\'' + 36 | ", name='" + name + '\'' + 37 | ", age=" + age + 38 | ", province='" + province + '\'' + 39 | ", city='" + city + '\'' + 40 | ", address='" + address + '\'' + 41 | ", hobby='" + hobby + '\'' + 42 | ", money=" + money + 43 | ", school='" + school + '\'' + 44 | '}'; 45 | } 46 | 47 | public String getId() { 48 | return id; 49 | } 50 | 51 | public void setId(String id) { 52 | this.id = id; 53 | } 54 | 55 | public String getName() { 56 | return name; 57 | } 58 | 59 | public void setName(String name) { 60 | this.name = name; 61 | } 62 | 63 | public Integer getAge() { 64 | return age; 65 | } 66 | 67 | public void setAge(Integer age) { 68 | this.age = age; 69 | } 70 | 71 | public String getProvince() { 72 | return province; 73 | } 74 | 75 | public void setProvince(String province) { 76 | this.province = province; 77 | } 78 | 79 | public String getCity() { 80 | return city; 81 | } 82 | 83 | public void setCity(String city) { 84 | this.city = city; 85 | } 86 | 87 | public String getAddress() { 88 | return address; 89 | } 90 | 91 | public void setAddress(String address) { 92 | this.address = address; 93 | } 94 | 95 | public String getHobby() { 96 | return hobby; 97 | } 98 | 99 | public void setHobby(String hobby) { 100 | this.hobby = hobby; 101 | } 102 | 103 | public BigDecimal getMoney() { 104 | return money; 105 | } 106 | 107 | public void setMoney(BigDecimal money) { 108 | this.money = money; 109 | } 110 | 111 | public String getSchool() { 112 | return school; 113 | } 114 | 115 | public void setSchool(String school) { 116 | this.school = school; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/locker/redis/RedissonConfig.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.locker.redis; 2 | 3 | import org.redisson.Redisson; 4 | import org.redisson.config.Config; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | /** 10 | * @description: Redisson配置类 11 | * 12 | * @author ITyunqing 13 | * @since 1.0.0 14 | */ 15 | @Configuration 16 | public class RedissonConfig { 17 | 18 | @Value("${singleServerConfig.address}") 19 | private String address; 20 | 21 | @Value("${singleServerConfig.password}") 22 | private String password; 23 | 24 | @Value("${singleServerConfig.pingTimeout}") 25 | private int pingTimeout; 26 | 27 | @Value("${singleServerConfig.connectTimeout}") 28 | private int connectTimeout; 29 | 30 | @Value("${singleServerConfig.timeout}") 31 | private int timeout; 32 | 33 | @Value("${singleServerConfig.idleConnectionTimeout}") 34 | private int idleConnectionTimeout; 35 | 36 | @Value("${singleServerConfig.retryAttempts}") 37 | private int retryAttempts; 38 | 39 | @Value("${singleServerConfig.retryInterval}") 40 | private int retryInterval; 41 | 42 | @Value("${singleServerConfig.reconnectionTimeout}") 43 | private int reconnectionTimeout; 44 | 45 | @Value("${singleServerConfig.failedAttempts}") 46 | private int failedAttempts; 47 | 48 | @Value("${singleServerConfig.subscriptionsPerConnection}") 49 | private int subscriptionsPerConnection; 50 | 51 | @Value("${singleServerConfig.subscriptionConnectionMinimumIdleSize}") 52 | private int subscriptionConnectionMinimumIdleSize; 53 | 54 | @Value("${singleServerConfig.subscriptionConnectionPoolSize}") 55 | private int subscriptionConnectionPoolSize; 56 | 57 | @Value("${singleServerConfig.connectionMinimumIdleSize}") 58 | private int connectionMinimumIdleSize; 59 | 60 | @Value("${singleServerConfig.connectionPoolSize}") 61 | private int connectionPoolSize; 62 | 63 | 64 | @Bean(destroyMethod = "shutdown") 65 | public Redisson redisson() { 66 | Config config = new Config(); 67 | config.useSingleServer().setAddress(address) 68 | .setPassword(password) 69 | .setIdleConnectionTimeout(idleConnectionTimeout) 70 | .setConnectTimeout(connectTimeout) 71 | .setTimeout(timeout) 72 | .setRetryAttempts(retryAttempts) 73 | .setRetryInterval(retryInterval) 74 | .setReconnectionTimeout(reconnectionTimeout) 75 | .setPingTimeout(pingTimeout) 76 | .setFailedAttempts(failedAttempts) 77 | .setSubscriptionsPerConnection(subscriptionsPerConnection) 78 | .setSubscriptionConnectionMinimumIdleSize(subscriptionConnectionMinimumIdleSize) 79 | .setSubscriptionConnectionPoolSize(subscriptionConnectionPoolSize) 80 | .setConnectionMinimumIdleSize(connectionMinimumIdleSize) 81 | .setConnectionPoolSize(connectionPoolSize); 82 | return (Redisson) Redisson.create(config); 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/locker/zookeeper/ZookeeperDistributedLocker.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.locker.zookeeper; 2 | 3 | import com.it4alla.idempotent.locker.core.LockerService; 4 | import java.util.Collections; 5 | import java.util.List; 6 | import java.util.concurrent.CountDownLatch; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.stream.Collectors; 9 | import org.apache.zookeeper.CreateMode; 10 | import org.apache.zookeeper.KeeperException; 11 | import org.apache.zookeeper.WatchedEvent; 12 | import org.apache.zookeeper.Watcher; 13 | import org.apache.zookeeper.Watcher.Event.EventType; 14 | import org.apache.zookeeper.ZooDefs.Ids; 15 | import org.apache.zookeeper.ZooKeeper; 16 | import org.apache.zookeeper.data.Stat; 17 | import org.slf4j.Logger; 18 | import org.slf4j.LoggerFactory; 19 | import org.springframework.util.CollectionUtils; 20 | 21 | /** 22 | * @description: Zookeeper Distributed Locker 23 | * 24 | * @author ITyunqing 25 | * @since 1.0.0 26 | */ 27 | public class ZookeeperDistributedLocker implements LockerService { 28 | private static final Logger logger = LoggerFactory.getLogger(ZookeeperDistributedLocker.class); 29 | private static final ThreadLocal threadLocal = new ThreadLocal<>(); 30 | private static final String ROOT_NODE_LOCK = "/ROOT_LOCK"; 31 | private static String currentLockId; 32 | private static final String DATA = "node"; 33 | private static final CountDownLatch countDownLatch = new CountDownLatch(1); 34 | 35 | @Override 36 | public Object lock(String lockKey) throws KeeperException, InterruptedException { 37 | ZooKeeper client = new ZookeeperClient().getClient(); 38 | this.checkRootNode(client); 39 | currentLockId = 40 | client.create(ROOT_NODE_LOCK+"/",DATA.getBytes(), 41 | Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL); 42 | List children = client.getChildren(ROOT_NODE_LOCK, false); 43 | if(!CollectionUtils.isEmpty(children)){ 44 | Collections.sort(children); 45 | String firstNode= children.get(0); 46 | String currentNode = currentLockId.substring(currentLockId.lastIndexOf("/") + 1); 47 | threadLocal.set(currentLockId); 48 | if(currentNode.equals(firstNode)){ 49 | return true; 50 | } 51 | 52 | int index = children.indexOf(currentNode); 53 | if(index > 0){ 54 | String preNode = children.get(index - 1); 55 | client.exists(ROOT_NODE_LOCK + "/" + preNode, new Watcher() { 56 | @Override 57 | public void process(WatchedEvent watchedEvent) { 58 | if(watchedEvent.getType().equals(EventType.NodeDeleted)){ 59 | countDownLatch.countDown(); 60 | } 61 | } 62 | }); 63 | countDownLatch.await(); 64 | return true; 65 | } 66 | 67 | } 68 | return true; 69 | } 70 | 71 | /** 72 | * check root node 73 | */ 74 | private void checkRootNode(ZooKeeper client){ 75 | try { 76 | Stat stat = client.exists(ROOT_NODE_LOCK, false); 77 | if (null == stat) { 78 | client.create(ROOT_NODE_LOCK, DATA.getBytes(), Ids.OPEN_ACL_UNSAFE, 79 | CreateMode.PERSISTENT); 80 | } 81 | }catch (Exception ex){ 82 | logger.info("【Zookeeper】Failed to create root node",ex); 83 | } 84 | 85 | 86 | } 87 | 88 | @Override 89 | public Object lock(String lockKey, Integer expireTime, TimeUnit timeUnit) { 90 | //FIXME add not support ex 91 | return null; 92 | } 93 | 94 | @Override 95 | public Object fairLock(String lockKey, Integer expireTime, TimeUnit timeUnit) { 96 | return null; 97 | } 98 | 99 | @Override 100 | public Object tryLock(String lockKey, Integer expireTime, TimeUnit timeUnit, Integer waitTime) { 101 | return null; 102 | } 103 | 104 | @Override 105 | public Object multiLock(Integer expireTime, TimeUnit timeUnit, String... lockKey) { 106 | return null; 107 | } 108 | 109 | @Override 110 | public void unLock(String lockKey) { 111 | 112 | } 113 | 114 | @Override 115 | public void unLock(Object lock) { 116 | 117 | } 118 | 119 | @Override 120 | public void unLockMultiLock(Object lock) { 121 | 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/aspect/IdempotentAspect.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.aspect; 2 | 3 | import com.it4alla.idempotent.annotation.Idempotent; 4 | import com.it4alla.idempotent.exception.IdempotentException; 5 | import java.lang.reflect.Method; 6 | import java.time.LocalDateTime; 7 | import java.util.Arrays; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import java.util.concurrent.TimeUnit; 11 | import javax.servlet.http.HttpServletRequest; 12 | import org.aspectj.lang.JoinPoint; 13 | import org.aspectj.lang.annotation.After; 14 | import org.aspectj.lang.annotation.Aspect; 15 | import org.aspectj.lang.annotation.Before; 16 | import org.aspectj.lang.annotation.Pointcut; 17 | import org.aspectj.lang.reflect.MethodSignature; 18 | import org.redisson.Redisson; 19 | import org.redisson.api.RMapCache; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | import org.springframework.beans.factory.annotation.Autowired; 23 | import org.springframework.stereotype.Component; 24 | import org.springframework.util.CollectionUtils; 25 | import org.springframework.web.context.request.RequestContextHolder; 26 | import org.springframework.web.context.request.ServletRequestAttributes; 27 | 28 | /** 29 | * @description: The Idempotent Aspect 30 | * 31 | * @author ITyunqing 32 | * @since 1.0.0 33 | */ 34 | @Aspect 35 | @Component 36 | public class IdempotentAspect { 37 | 38 | private static final Logger LOGGER = LoggerFactory.getLogger(IdempotentAspect.class); 39 | private ThreadLocal> threadLocal = new ThreadLocal(); 40 | private static final String RMAPCACHE_KEY = "idempotent"; 41 | private static final String KEY = "key"; 42 | private static final String DELKEY = "delKey"; 43 | 44 | @Autowired 45 | private Redisson redisson; 46 | 47 | 48 | @Pointcut("@annotation(com.it4alla.idempotent.annotation.Idempotent)") 49 | public void pointCut(){} 50 | 51 | @Before("pointCut()") 52 | public void beforePointCut(JoinPoint joinPoint)throws Exception{ 53 | ServletRequestAttributes requestAttributes = 54 | (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 55 | HttpServletRequest request = requestAttributes.getRequest(); 56 | 57 | MethodSignature signature = (MethodSignature)joinPoint.getSignature(); 58 | Method method = signature.getMethod(); 59 | if(!method.isAnnotationPresent(Idempotent.class)){ 60 | return; 61 | } 62 | Idempotent idempotent = method.getAnnotation(Idempotent.class); 63 | boolean isIdempotent = idempotent.isIdempotent(); 64 | if(!isIdempotent){ 65 | return; 66 | } 67 | 68 | String url = request.getRequestURL().toString(); 69 | String argString = Arrays.asList(joinPoint.getArgs()).toString(); 70 | String key = url + argString; 71 | 72 | long expireTime = idempotent.expireTime(); 73 | String info = idempotent.info(); 74 | TimeUnit timeUnit = idempotent.timeUnit(); 75 | boolean delKey = idempotent.delKey(); 76 | 77 | //do not need check null 78 | RMapCache rMapCache = redisson.getMapCache(RMAPCACHE_KEY); 79 | String value = LocalDateTime.now().toString().replace("T", " "); 80 | Object v1; 81 | if (null != rMapCache.get(key)){ 82 | //had stored 83 | throw new IdempotentException("[idempotent]:"+info); 84 | } 85 | synchronized (this){ 86 | v1 = rMapCache.putIfAbsent(key, value, expireTime, TimeUnit.SECONDS); 87 | if(null != v1){ 88 | throw new IdempotentException("[idempotent]:"+info); 89 | }else { 90 | LOGGER.info("[idempotent]:has stored key={},value={},expireTime={}{},now={}",key,value,expireTime,timeUnit,LocalDateTime.now().toString()); 91 | } 92 | } 93 | 94 | Map map = 95 | CollectionUtils.isEmpty(threadLocal.get()) ? new HashMap<>(4):threadLocal.get(); 96 | map.put(KEY,key); 97 | map.put(DELKEY,delKey); 98 | threadLocal.set(map); 99 | 100 | } 101 | 102 | @After("pointCut()") 103 | public void afterPointCut(JoinPoint joinPoint){ 104 | Map map = threadLocal.get(); 105 | if(CollectionUtils.isEmpty(map)){ 106 | return; 107 | } 108 | 109 | RMapCache mapCache = redisson.getMapCache(RMAPCACHE_KEY); 110 | if(mapCache.size() == 0){ 111 | return; 112 | } 113 | 114 | String key = map.get(KEY).toString(); 115 | boolean delKey = (boolean)map.get(DELKEY); 116 | 117 | if(delKey){ 118 | mapCache.fastRemove(key); 119 | LOGGER.info("[idempotent]:has removed key={}",key); 120 | } 121 | threadLocal.remove(); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/main/java/com/it4alla/idempotent/locker/redis/RedissonDistributedLocker.java: -------------------------------------------------------------------------------- 1 | package com.it4alla.idempotent.locker.redis; 2 | 3 | import com.it4alla.idempotent.locker.core.LockerService; 4 | import java.util.concurrent.TimeUnit; 5 | import org.redisson.Redisson; 6 | import org.redisson.RedissonMultiLock; 7 | import org.redisson.api.RLock; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.stereotype.Component; 12 | 13 | /** 14 | * @description: Redisson分布式锁 15 | * 16 | * @author ITyunqing 17 | * @since 1.0.0 18 | */ 19 | @Component 20 | public class RedissonDistributedLocker implements LockerService { 21 | private static final Logger logger = LoggerFactory.getLogger(RedissonDistributedLocker.class); 22 | 23 | private static volatile RedissonDistributedLocker instance; 24 | 25 | static RedissonDistributedLocker getInstance(){ 26 | if (null == instance) { 27 | synchronized (RedissonDistributedLocker.class) { 28 | if (null == instance) { 29 | instance = new RedissonDistributedLocker(); 30 | } 31 | } 32 | } 33 | return instance; 34 | } 35 | 36 | @Autowired 37 | private Redisson redisson; 38 | 39 | /** 40 | * 获取锁,需要主动释放 41 | * @param lockKey 42 | * @return 43 | */ 44 | @Override 45 | public RLock lock(String lockKey){ 46 | RLock lock = redisson.getLock(lockKey); 47 | lock.lock(); 48 | logger.info("【Redisson lock】success to acquire lock for [ "+lockKey+" ]"); 49 | return lock; 50 | } 51 | 52 | /** 53 | * 获取锁,如果没有主动调用unlock解锁,expireTime后会自动释放 54 | * @param lockKey 55 | * @param expireTime 如果没有调用unlock解锁,expireTime 后自动释放 56 | * @param timeUnit 时间单位 57 | * @return 58 | */ 59 | @Override 60 | public RLock lock(String lockKey,Integer expireTime,TimeUnit timeUnit){ 61 | RLock lock = redisson.getLock(lockKey); 62 | lock.lock(expireTime, timeUnit); 63 | logger.info("【Redisson lock】success to acquire lock for [ "+lockKey+" ],expire time:"+expireTime+timeUnit); 64 | return lock; 65 | } 66 | 67 | /** 68 | * 获取公平锁,如果没有主动调用unlock解锁,expireTime后会自动释放 69 | * @param lockKey 70 | * @param expireTime 如果没有调用unlock解锁,expireTime 后自动释放 71 | * @param timeUnit 时间单位 72 | * @return 73 | */ 74 | @Override 75 | public RLock fairLock(String lockKey,Integer expireTime,TimeUnit timeUnit){ 76 | RLock fairLock = redisson.getFairLock(lockKey); 77 | fairLock.lock(expireTime, timeUnit); 78 | logger.info("【Redisson lock】success to acquire fair lock for [ "+lockKey+" ],expire time:"+expireTime+timeUnit); 79 | return fairLock; 80 | } 81 | 82 | /** 83 | * 获取锁 尝试加锁,最多等待waitTime 的时间,加锁expireTime 后自动释放 84 | * @param lockKey 85 | * @param expireTime 过期时间 86 | * @param timeUnit 时间单位 87 | * @param waitTime 加锁等待 88 | * @return 89 | */ 90 | @Override 91 | public Boolean tryLock(String lockKey, Integer expireTime,TimeUnit timeUnit,Integer waitTime) { 92 | RLock lock = redisson.getLock(lockKey); 93 | try { 94 | logger.info("【Redisson lock】success to acquire lock for [ "+lockKey+" ],expire time:"+expireTime+timeUnit); 95 | return lock.tryLock(waitTime, expireTime, timeUnit); 96 | } catch (InterruptedException e) { 97 | return false; 98 | } 99 | } 100 | 101 | /** 102 | * 联锁 获取一组锁,一组资源的锁,当作一个锁 103 | * @param expireTime 104 | * @param timeUnit 如果没有调用unlock解锁,expireTime 后自动释放 105 | * @param lockKey 时间单位 106 | * @return 107 | */ 108 | @Override 109 | public RedissonMultiLock multiLock(Integer expireTime,TimeUnit timeUnit,String ...lockKey){ 110 | RLock [] rLocks = new RLock[lockKey.length]; 111 | for(int i = 0,length = lockKey.length; i < length ;i ++){ 112 | RLock lock = redisson.getLock(lockKey[i]); 113 | rLocks[i] = lock; 114 | } 115 | RedissonMultiLock multiLock = new RedissonMultiLock(rLocks); 116 | multiLock.lock(expireTime,timeUnit); 117 | logger.info("【Redisson lock】success to acquire multiLock for [ "+lockKey+" ],expire time:"+expireTime+timeUnit); 118 | return multiLock; 119 | } 120 | 121 | /** 122 | * 释放锁 123 | * @param lockKey 124 | */ 125 | @Override 126 | public void unLock(String lockKey){ 127 | RLock lock = redisson.getLock(lockKey); 128 | lock.unlock(); 129 | logger.info("【Redisson lock】success to release lock for [ "+lockKey+" ]"); 130 | } 131 | 132 | /** 133 | * 释放锁 134 | * @param lock 135 | */ 136 | @Override 137 | public void unLock(Object lock) { 138 | RLock rLock = (RLock) lock; 139 | rLock.unlock(); 140 | logger.info("【Redisson lock】success to release lock for [ "+rLock.getName()+" ]"); 141 | } 142 | 143 | /** 144 | * 释放联锁 145 | * @param lock 146 | */ 147 | @Override 148 | public void unLockMultiLock(Object lock) { 149 | RedissonMultiLock multiLock = (RedissonMultiLock) lock; 150 | multiLock.unlock(); 151 | logger.info("【Redisson lock】success to release lock"); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * locker under the License is locker on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import java.net.*; 18 | import java.io.*; 19 | import java.nio.channels.*; 20 | import java.util.Properties; 21 | 22 | public class MavenWrapperDownloader { 23 | 24 | private static final String WRAPPER_VERSION = "0.5.6"; 25 | /** 26 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 27 | */ 28 | private static final String DEFAULT_DOWNLOAD_URL = 29 | "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 30 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 31 | 32 | /** 33 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to use 34 | * instead of the default one. 35 | */ 36 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 37 | ".mvn/wrapper/maven-wrapper.properties"; 38 | 39 | /** 40 | * Path where the maven-wrapper.jar will be saved to. 41 | */ 42 | private static final String MAVEN_WRAPPER_JAR_PATH = 43 | ".mvn/wrapper/maven-wrapper.jar"; 44 | 45 | /** 46 | * Name of the property which should be used to override the default download url for the 47 | * wrapper. 48 | */ 49 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 50 | 51 | public static void main(String args[]) { 52 | System.out.println("- Downloader started"); 53 | File baseDirectory = new File(args[0]); 54 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 55 | 56 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 57 | // wrapperUrl parameter. 58 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 59 | String url = DEFAULT_DOWNLOAD_URL; 60 | if (mavenWrapperPropertyFile.exists()) { 61 | FileInputStream mavenWrapperPropertyFileInputStream = null; 62 | try { 63 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 64 | Properties mavenWrapperProperties = new Properties(); 65 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 66 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 67 | } catch (IOException e) { 68 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 69 | } finally { 70 | try { 71 | if (mavenWrapperPropertyFileInputStream != null) { 72 | mavenWrapperPropertyFileInputStream.close(); 73 | } 74 | } catch (IOException e) { 75 | // Ignore ... 76 | } 77 | } 78 | } 79 | System.out.println("- Downloading from: " + url); 80 | 81 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 82 | if (!outputFile.getParentFile().exists()) { 83 | if (!outputFile.getParentFile().mkdirs()) { 84 | System.out.println( 85 | "- ERROR creating output directory '" + outputFile.getParentFile() 86 | .getAbsolutePath() + "'"); 87 | } 88 | } 89 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 90 | try { 91 | downloadFileFromURL(url, outputFile); 92 | System.out.println("Done"); 93 | System.exit(0); 94 | } catch (Throwable e) { 95 | System.out.println("- Error downloading"); 96 | e.printStackTrace(); 97 | System.exit(1); 98 | } 99 | } 100 | 101 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 102 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 103 | String username = System.getenv("MVNW_USERNAME"); 104 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 105 | Authenticator.setDefault(new Authenticator() { 106 | @Override 107 | protected PasswordAuthentication getPasswordAuthentication() { 108 | return new PasswordAuthentication(username, password); 109 | } 110 | }); 111 | } 112 | URL website = new URL(urlString); 113 | ReadableByteChannel rbc; 114 | rbc = Channels.newChannel(website.openStream()); 115 | FileOutputStream fos = new FileOutputStream(destination); 116 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 117 | fos.close(); 118 | rbc.close(); 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /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 | ### 接口幂等处理 2 | 3 | # idempotent 幂等处理方案 4 | An idempotent solution. 5 | ### 1.原理 6 | 1.请求开始前,根据key查询 7 | 查到结果:报错 8 | 未查到结果:存入key-value-expireTime 9 | key=ip+url+args 10 | 11 | 2.请求结束后,直接删除key 12 | 不管key是否存在,直接删除 13 | 是否删除,可配置 14 | 15 | 3.expireTime过期时间,防止一个请求卡死,会一直阻塞,超过过期时间,自动删除 16 | 过期时间要大于业务执行时间,需要大概评估下; 17 | 18 | 4.此方案直接切的是接口请求层面。 19 | 20 | 5.过期时间需要大于业务执行时间,否则业务请求1进来还在执行中,前端未做遮罩,或者用户跳转页面后再回来做重复请求2,在业务层面上看,结果依旧是不符合预期的。 21 | 22 | 6.建议delKey = false。即使业务执行完,也不删除key,强制锁expireTime的时间。预防5的情况发生。 23 | 24 | 7.实现思路:同一个请求ip和接口,相同参数的请求,在expireTime内多次请求,只允许成功一次。 25 | 26 | 8.页面做遮罩,数据库层面的唯一索引,先查询再添加,等处理方式应该都处理下。 27 | 28 | 9.此注解只用于幂等,不用于锁,100个并发这种压测,会出现问题,在这种场景下也没有意义,实际中用户也不会出现1s或者3s内手动发送了50个或者100个重复请求,或者弱网下有100个重复请求; 29 | 30 | 31 | ### 2.使用 32 | 引入注解,切面,配置类,异常类,修改配置,直接在需要使用的接口上添加注解即可; 33 | (后期会优化为jar) 34 | 使用如下: 35 | ```java 36 | @Idempotent(idempotent = true,expireTime = 3,timeUnit = TimeUnit.SECONDS,info = "请勿重复添加用户",delKey = false) 37 | @GetMapping(value = "add") 38 | public String add(User user){ 39 | userServiceImpl.add(user); 40 | return "添加成功"; 41 | } 42 | ``` 43 | 44 | ### 3.测试 45 | jmeter并发压测,或者charles弱网测试结果: 46 | 47 | ```java 48 | 2019-08-28 13:45:11.847 INFO 5468 --- [nio-7777-exec-4] com.java4all.aspect.IdempotentAspect : [idempotent]:has stored key=http://localhost:7777/user/add[User{id='11', name='wang', age=26, province='陕西', city='商洛市', address='商南县', hobby='magic', money=100000.99, school='清华大学'}],value=2019-08-28 13:45:11.824,expireTime=6SECONDS 49 | 2019-08-28 13:45:12.160 ERROR 5468 --- [nio-7777-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.reflect.UndeclaredThrowableException] with root cause 50 | 51 | com.java4all.exception.IdempotentException: [idempotent]:请勿重复添加用户 52 | at com.java4all.aspect.IdempotentAspect.beforePointCut(IdempotentAspect.java:69) ~[classes/:na] 53 | at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65] 54 | at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65] 55 | at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65] 56 | at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65] 57 | at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 58 | at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:626) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 59 | at org.springframework.aop.aspectj.AspectJMethodBeforeAdvice.before(AspectJMethodBeforeAdvice.java:44) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 60 | at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:55) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 61 | at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 62 | at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:47) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 63 | at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 64 | at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 65 | at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 66 | at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 67 | at com.java4all.controller.UserController$$EnhancerBySpringCGLIB$$7c3364f2.add() ~[classes/:na] 68 | at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65] 69 | at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65] 70 | at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65] 71 | at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65] 72 | at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 73 | at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 74 | at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 75 | at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 76 | at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 77 | at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 78 | at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 79 | at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 80 | at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 81 | at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 82 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 83 | at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 84 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 85 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 86 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 87 | at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.22.jar:9.0.22] 88 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 89 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 90 | at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 91 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 92 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 93 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 94 | at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 95 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 96 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 97 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 98 | at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 99 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 100 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 101 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 102 | at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 103 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 104 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 105 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 106 | at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 107 | at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.22.jar:9.0.22] 108 | at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.22.jar:9.0.22] 109 | at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.22.jar:9.0.22] 110 | at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.22.jar:9.0.22] 111 | at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.22.jar:9.0.22] 112 | at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.22.jar:9.0.22] 113 | at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.22.jar:9.0.22] 114 | at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.22.jar:9.0.22] 115 | at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853) [tomcat-embed-core-9.0.22.jar:9.0.22] 116 | at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587) [tomcat-embed-core-9.0.22.jar:9.0.22] 117 | at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.22.jar:9.0.22] 118 | at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_65] 119 | at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_65] 120 | at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.22.jar:9.0.22] 121 | at java.lang.Thread.run(Thread.java:745) [na:1.8.0_65] 122 | 123 | 2019-08-28 13:45:12.502 ERROR 5468 --- [nio-7777-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.reflect.UndeclaredThrowableException] with root cause 124 | 125 | com.java4all.exception.IdempotentException: [idempotent]:请勿重复添加用户 126 | at com.java4all.aspect.IdempotentAspect.beforePointCut(IdempotentAspect.java:69) ~[classes/:na] 127 | at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65] 128 | at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65] 129 | at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65] 130 | at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65] 131 | at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 132 | at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:626) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 133 | at org.springframework.aop.aspectj.AspectJMethodBeforeAdvice.before(AspectJMethodBeforeAdvice.java:44) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 134 | at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:55) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 135 | at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 136 | at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:47) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 137 | at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 138 | at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 139 | at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 140 | at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE] 141 | at com.java4all.controller.UserController$$EnhancerBySpringCGLIB$$7c3364f2.add() ~[classes/:na] 142 | at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65] 143 | at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65] 144 | at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65] 145 | at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65] 146 | at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 147 | at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 148 | at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 149 | at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 150 | at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 151 | at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 152 | at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 153 | at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 154 | at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 155 | at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 156 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 157 | at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] 158 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 159 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 160 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 161 | at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.22.jar:9.0.22] 162 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 163 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 164 | at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 165 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 166 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 167 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 168 | at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 169 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 170 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 171 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 172 | at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 173 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 174 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 175 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 176 | at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 177 | at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] 178 | at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 179 | at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 180 | at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 181 | at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.22.jar:9.0.22] 182 | at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.22.jar:9.0.22] 183 | at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.22.jar:9.0.22] 184 | at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.22.jar:9.0.22] 185 | at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.22.jar:9.0.22] 186 | at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.22.jar:9.0.22] 187 | at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.22.jar:9.0.22] 188 | at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.22.jar:9.0.22] 189 | at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853) [tomcat-embed-core-9.0.22.jar:9.0.22] 190 | at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587) [tomcat-embed-core-9.0.22.jar:9.0.22] 191 | at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.22.jar:9.0.22] 192 | at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_65] 193 | at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_65] 194 | at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.22.jar:9.0.22] 195 | at java.lang.Thread.run(Thread.java:745) [na:1.8.0_65] 196 | 197 | 2019-08-28 13:45:12.847 INFO 5468 --- [nio-7777-exec-4] com.java4all.controller.UserServiceImpl : 添加用户成功 198 | 2019-08-28 13:45:12.864 INFO 5468 --- [nio-7777-exec-4] com.java4all.aspect.IdempotentAspect : [idempotent]:has removed key=http://localhost:7777/user/add[User{id='11', name='wang', age=26, province='陕西', city='商洛市', address='商南县', hobby='magic', money=100000.99, school='清华大学'}] 199 | 200 | ``` 201 | 业务执行1s,设置过期时间3s,2s内10个重复请求: 202 | 203 | 不添加注解时: 204 | 205 | ![不添加注解](/./src/main/resources/image/nouse.png) 206 | 207 | 添加注解时: 208 | 209 | @Idempotent(idempotent = true,expireTime = 3,timeUnit = TimeUnit.SECONDS,info = "请勿重复添加用户",delKey = false) 210 | 211 | ![添加注解1](/./src/main/resources/image/use1.png) 212 | 213 | ![添加注解1](/./src/main/resources/image/use2.png) 214 | --------------------------------------------------------------------------------