├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── src ├── main │ ├── resources │ │ ├── scripts │ │ │ ├── unlock.lua │ │ │ ├── lock.lua │ │ │ └── limit.lua │ │ ├── application.properties │ │ ├── sql │ │ │ └── init.sql │ │ └── ratelimit │ │ │ └── ratelimit.lua │ └── java │ │ └── com │ │ └── hqs │ │ └── flashsales │ │ ├── service │ │ ├── OrderService.java │ │ └── impl │ │ │ └── OrderServiceImpl.java │ │ ├── Model │ │ ├── Catalog.java │ │ └── SalesOrder.java │ │ ├── annotation │ │ └── DistriLimitAnno.java │ │ ├── FlashsalesApplication.java │ │ ├── Mapper │ │ ├── CatalogMapper.java │ │ └── SalesOrderMapper.java │ │ ├── util │ │ └── UnifiedErrorHandler.java │ │ ├── lock │ │ └── DistributedLock.java │ │ ├── config │ │ ├── SwaggerConfig.java │ │ └── ScriptConfig.java │ │ ├── aspect │ │ └── LimitAspect.java │ │ ├── limit │ │ └── DistributedLimit.java │ │ └── controller │ │ └── FlashSaleController.java └── test │ └── java │ └── com │ └── hqs │ └── flashsales │ └── FlashSalesApplicationTests.java ├── README.md ├── .gitignore ├── pom.xml ├── mvnw.cmd └── mvnw /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stonehqs/flashsales/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip 2 | -------------------------------------------------------------------------------- /src/main/resources/scripts/unlock.lua: -------------------------------------------------------------------------------- 1 | redis.call('del', 'result') 2 | if redis.call('get', KEYS[1]) == ARGV[1] then 3 | return redis.call('del', KEYS[1]) 4 | else 5 | return 0 6 | end -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # flashsales 2 | flash sales using distributed limit & lock, limit is implemented by counter or token bucket(leaky bucket) 3 | 4 | 5 | blog site: https://www.cnblogs.com/huangqingshi/p/10325574.html 6 | -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/service/OrderService.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.service; 2 | 3 | /** 4 | * @author huangqingshi 5 | * @Date 2019-01-23 6 | */ 7 | public interface OrderService { 8 | 9 | void initCatalog(); 10 | 11 | Long placeOrder(Long catalogId); 12 | 13 | Long placeOrderWithQueue(Long catalogId); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/resources/scripts/lock.lua: -------------------------------------------------------------------------------- 1 | local expire = tonumber(ARGV[2]) 2 | local ret = redis.call('set', KEYS[1], ARGV[1], 'NX', 'PX', expire) 3 | local strret = tostring(ret) 4 | --用于查看结果,我本机获取锁成功后程序返回随机结果"table: 0x7fb4b3700fe0",否则返回"false" 5 | redis.call('set', 'result', strret) 6 | if strret == 'false' then 7 | return false 8 | else 9 | return true 10 | end -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/Model/Catalog.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.Model; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @author huangqingshi 7 | * @Date 2019-01-23 8 | */ 9 | @Data 10 | public class Catalog { 11 | private Long id; 12 | private String name; 13 | private Long total; 14 | private Long sold; 15 | private Long version; 16 | } 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/Model/SalesOrder.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.Model; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.Date; 6 | 7 | /** 8 | * @author huangqingshi 9 | * @Date 2019-01-23 10 | */ 11 | @Data 12 | public class SalesOrder { 13 | private Long id; 14 | private Long cid; 15 | private String name; 16 | private Date createTime; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/annotation/DistriLimitAnno.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.annotation; 2 | 3 | import java.lang.annotation.*; 4 | 5 | /** 6 | * 自定义limit注解 7 | * @author huangqingshi 8 | * @Date 2019-01-17 9 | */ 10 | @Target(ElementType.METHOD) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | public @interface DistriLimitAnno { 13 | String limitKey() default "limit"; 14 | int limit() default 1; 15 | String seconds() default "1"; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/resources/scripts/limit.lua: -------------------------------------------------------------------------------- 1 | 2 | --lua 下标从 1 开始 3 | -- 限流 key 4 | local key = KEYS[1] 5 | -- 限流大小 6 | local limit = tonumber(ARGV[1]) 7 | 8 | -- 获取当前流量大小 9 | local curentLimit = tonumber(redis.call('get', key) or "0") 10 | 11 | if curentLimit + 1 > limit then 12 | -- 达到限流大小 返回 13 | return 0; 14 | else 15 | -- 没有达到阈值 value + 1 16 | redis.call("INCRBY", key, 1) 17 | -- EXPIRE后边的单位是秒 18 | redis.call("EXPIRE", key, ARGV[2]) 19 | return curentLimit + 1 20 | end 21 | 22 | -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/FlashsalesApplication.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.ComponentScan; 6 | 7 | @SpringBootApplication 8 | public class FlashsalesApplication { 9 | 10 | public static void main(String[] args) { 11 | SpringApplication.run(FlashsalesApplication.class, args); 12 | } 13 | 14 | } 15 | 16 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8080 2 | server.address=127.0.0.1 3 | 4 | spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai 5 | spring.datasource.username=root 6 | spring.datasource.password=root 7 | spring.datasource.testWhileIdle=true 8 | spring.datasource.validationQuery=SELECT 1 9 | 10 | swagger.switch=true 11 | 12 | # redis 13 | redis.host=127.0.0.1 14 | redis.port=6379 15 | redis.password= 16 | redis.maxIdle=100 17 | redis.maxTotal=300 18 | redis.maxWait=10000 19 | redis.testOnBorrow=true 20 | redis.timeout=100000 21 | -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/Mapper/CatalogMapper.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.Mapper; 2 | 3 | import com.hqs.flashsales.Model.Catalog; 4 | import org.apache.ibatis.annotations.*; 5 | 6 | /** 7 | * @author huangqingshi 8 | * @Date 2019-01-23 9 | */ 10 | @Mapper 11 | public interface CatalogMapper { 12 | 13 | @Insert("insert into catalog (name, total, sold) values (#{name}, #{total}, #{sold}) ") 14 | @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id") 15 | Long insertCatalog(Catalog catalog); 16 | 17 | @Update("update catalog set name=#{name}, total=#{total}, sold=#{sold} where id=#{id}") 18 | Long updateCatalog(Catalog catalog); 19 | 20 | @Select("select * from catalog where id=#{id}") 21 | Catalog selectCatalog(@Param("id") Long id); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/resources/sql/init.sql: -------------------------------------------------------------------------------- 1 | --drop table catalog; 2 | --drop table sales_order; 3 | 4 | CREATE TABLE `catalog` ( 5 | `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 6 | `name` varchar(50) NOT NULL DEFAULT '' COMMENT '名称', 7 | `total` int(11) NOT NULL COMMENT '库存', 8 | `sold` int(11) NOT NULL COMMENT '已售', 9 | `version` int(11) NULL COMMENT '乐观锁,版本号', 10 | PRIMARY KEY (`id`) 11 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 12 | 13 | CREATE TABLE `sales_order` ( 14 | `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 15 | `cid` int(11) NOT NULL COMMENT '库存ID', 16 | `name` varchar(30) NOT NULL DEFAULT '' COMMENT '商品名称', 17 | `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间', 18 | PRIMARY KEY (`id`) 19 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 20 | 21 | --select * from catalog; 22 | --select * from sales_order; 23 | -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/util/UnifiedErrorHandler.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.util; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.web.bind.annotation.ControllerAdvice; 6 | import org.springframework.web.bind.annotation.ExceptionHandler; 7 | import org.springframework.web.bind.annotation.ResponseBody; 8 | import org.springframework.web.bind.annotation.ResponseStatus; 9 | 10 | import javax.servlet.http.HttpServletRequest; 11 | 12 | /** 13 | * @author huangqingshi 14 | * @Date 2019-01-17 15 | * 统一的controller错误处理 16 | */ 17 | @Slf4j 18 | @ControllerAdvice 19 | public class UnifiedErrorHandler { 20 | 21 | @ExceptionHandler(value = Exception.class) 22 | @ResponseStatus(HttpStatus.OK) 23 | @ResponseBody 24 | public Long processException(HttpServletRequest req, Exception e) { 25 | log.info("error:{}", e.getMessage()); 26 | return 0L; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/Mapper/SalesOrderMapper.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.Mapper; 2 | 3 | import com.hqs.flashsales.Model.SalesOrder; 4 | import org.apache.ibatis.annotations.*; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * @author huangqingshi 10 | * @Date 2019-01-23 11 | */ 12 | @Mapper 13 | public interface SalesOrderMapper { 14 | 15 | @Insert("insert sales_order (cid, name) values (#{cid}, #{name})") 16 | @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id") 17 | void insertSalesOrder(SalesOrder salesOrder); 18 | 19 | @Update("update sales_order set cid=#{cid}, name=#{name} where id=#{id}") 20 | Long updateSalesOrder(SalesOrder salesOrder); 21 | 22 | @Select("select * from sales_order where id=#{id}") 23 | SalesOrder selectSalesOrder(@Param("id") Long id); 24 | 25 | @Delete("Delete from sales_order where id=#{id}") 26 | Long deleteSalesOrder(@Param("id") Long id); 27 | 28 | @Select("select * from sales_order") 29 | List selectAllSalesOrder(); 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/lock/DistributedLock.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.lock; 2 | 3 | 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.data.redis.core.RedisTemplate; 7 | import org.springframework.data.redis.core.script.RedisScript; 8 | import org.springframework.stereotype.Component; 9 | 10 | import java.util.Collections; 11 | 12 | @Slf4j 13 | @Component 14 | public class DistributedLock { 15 | 16 | //注意RedisTemplate用的String,String,后续所有用到的key和value都是String的 17 | @Autowired 18 | private RedisTemplate redisTemplate; 19 | 20 | @Autowired 21 | RedisScript lockScript; 22 | 23 | @Autowired 24 | RedisScript unlockScript; 25 | 26 | public Boolean distributedLock(String key, String uuid, String secondsToLock) { 27 | Boolean locked = false; 28 | try { 29 | String millSeconds = String.valueOf(Integer.parseInt(secondsToLock) * 1000); 30 | locked =redisTemplate.execute(lockScript, Collections.singletonList(key), uuid, millSeconds); 31 | log.info("distributedLock.key{}: - uuid:{}: - timeToLock:{} - locked:{} - millSeconds:{}", 32 | key, uuid, secondsToLock, locked, millSeconds); 33 | } catch (Exception e) { 34 | log.error("error", e); 35 | } 36 | return locked; 37 | } 38 | 39 | public void distributedUnlock(String key, String uuid) { 40 | Long unlocked = redisTemplate.execute(unlockScript, Collections.singletonList(key), 41 | uuid); 42 | log.info("distributedLock.key{}: - uuid:{}: - unlocked:{}", key, uuid, unlocked); 43 | 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/com/hqs/flashsales/FlashSalesApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.test.web.client.TestRestTemplate; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | import org.springframework.util.LinkedMultiValueMap; 11 | import org.springframework.util.MultiValueMap; 12 | 13 | import java.util.concurrent.TimeUnit; 14 | 15 | @Slf4j 16 | @RunWith(SpringRunner.class) 17 | @SpringBootTest(classes = FlashsalesApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 18 | public class FlashSalesApplicationTests { 19 | 20 | @Autowired 21 | private TestRestTemplate testRestTemplate; 22 | 23 | @Test 24 | public void flashsaleTest() { 25 | String url = "http://localhost:8080/placeOrder"; 26 | for(int i = 0; i < 3000; i++) { 27 | try { 28 | TimeUnit.MILLISECONDS.sleep(20); 29 | new Thread(() -> { 30 | MultiValueMap params = new LinkedMultiValueMap<>(); 31 | params.add("orderId", "1"); 32 | Long result = testRestTemplate.postForObject(url, params, Long.class); 33 | if(result != 0) { 34 | System.out.println("-------------" + result); 35 | } 36 | } 37 | ).start(); 38 | } catch (Exception e) { 39 | log.info("error:{}", e.getMessage()); 40 | } 41 | 42 | } 43 | } 44 | 45 | @Test 46 | public void contextLoads() { 47 | } 48 | 49 | } 50 | 51 | -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/config/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import springfox.documentation.builders.ApiInfoBuilder; 7 | import springfox.documentation.builders.PathSelectors; 8 | import springfox.documentation.builders.RequestHandlerSelectors; 9 | import springfox.documentation.service.ApiInfo; 10 | import springfox.documentation.service.Contact; 11 | import springfox.documentation.spi.DocumentationType; 12 | import springfox.documentation.spring.web.plugins.Docket; 13 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 14 | 15 | /** 16 | * Created by huangqingshi on 2019/1/8. 17 | */ 18 | @Configuration 19 | @EnableSwagger2 20 | public class SwaggerConfig { 21 | 22 | @Value("${swagger.switch}") 23 | private boolean swaggerSwitch; 24 | 25 | @Bean 26 | public Docket api() { 27 | Docket docket = new Docket(DocumentationType.SWAGGER_2); 28 | docket.enable(swaggerSwitch); 29 | docket 30 | .apiInfo(apiInfo()) 31 | .select() 32 | .apis(RequestHandlerSelectors.basePackage("com.hqs.flashsales.controller")) 33 | .paths(PathSelectors.any()).build(); 34 | return docket; 35 | } 36 | 37 | private ApiInfo apiInfo() { 38 | return new ApiInfoBuilder() 39 | .title("Spring boot flash sale") 40 | .description("秒杀") 41 | .contact(new Contact("黄青石","http://www.cnblogs.com/huangqingshi","68344150@qq.com")) 42 | .termsOfServiceUrl("http://www.cnblogs.com/huangqingshi") 43 | .version("1.0") 44 | .build(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/aspect/LimitAspect.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.aspect; 2 | 3 | 4 | import com.hqs.flashsales.annotation.DistriLimitAnno; 5 | import com.hqs.flashsales.limit.DistributedLimit; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.aspectj.lang.JoinPoint; 8 | import org.aspectj.lang.annotation.Aspect; 9 | import org.aspectj.lang.annotation.Before; 10 | import org.aspectj.lang.annotation.Pointcut; 11 | import org.aspectj.lang.reflect.MethodSignature; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.context.annotation.Configuration; 14 | import org.springframework.context.annotation.EnableAspectJAutoProxy; 15 | import org.springframework.stereotype.Component; 16 | 17 | import java.lang.reflect.Method; 18 | 19 | /** 20 | * @author huangqingshi 21 | * @Date 2019-01-17 22 | */ 23 | @Slf4j 24 | @Aspect 25 | @Component 26 | @EnableAspectJAutoProxy(proxyTargetClass = true) 27 | public class LimitAspect { 28 | 29 | @Autowired 30 | DistributedLimit distributedLimit; 31 | 32 | @Pointcut("@annotation(com.hqs.flashsales.annotation.DistriLimitAnno)") 33 | public void limit() {}; 34 | 35 | @Before("limit()") 36 | public void beforeLimit(JoinPoint joinPoint) throws Exception { 37 | MethodSignature signature = (MethodSignature) joinPoint.getSignature(); 38 | Method method = signature.getMethod(); 39 | DistriLimitAnno distriLimitAnno = method.getAnnotation(DistriLimitAnno.class); 40 | String key = distriLimitAnno.limitKey(); 41 | int limit = distriLimitAnno.limit(); 42 | String seconds = distriLimitAnno.seconds(); 43 | Boolean exceededLimit = distributedLimit.distributedRateLimit(key, String.valueOf(limit), seconds); 44 | if(!exceededLimit) { 45 | throw new RuntimeException("exceeded limit"); 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/limit/DistributedLimit.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.limit; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.context.annotation.DependsOn; 6 | import org.springframework.data.redis.core.RedisTemplate; 7 | import org.springframework.data.redis.core.script.RedisScript; 8 | import org.springframework.stereotype.Component; 9 | 10 | import javax.annotation.Resource; 11 | import java.util.Collections; 12 | 13 | /** 14 | * @author huangqingshi 15 | * @Date 2019-01-17 16 | */ 17 | @Slf4j 18 | @Component 19 | public class DistributedLimit { 20 | 21 | //注意RedisTemplate用的String,String,后续所有用到的key和value都是String的 22 | @Autowired 23 | RedisTemplate redisTemplate; 24 | 25 | @Resource 26 | RedisScript rateLimitScript; 27 | 28 | @Resource 29 | RedisScript limitScript; 30 | 31 | public Boolean distributedLimit(String key, String limit, String seconds) { 32 | Long id = 0L; 33 | 34 | try { 35 | id = redisTemplate.execute(limitScript, Collections.singletonList(key), 36 | limit, seconds); 37 | // log.info("id:{}", id); 38 | } catch (Exception e) { 39 | log.error("error", e); 40 | } 41 | 42 | if(id == 0L) { 43 | return false; 44 | } else { 45 | return true; 46 | } 47 | } 48 | 49 | public Boolean distributedRateLimit(String key, String limit, String seconds) { 50 | Long id = 0L; 51 | long intervalInMills = Long.valueOf(seconds) * 1000; 52 | long limitInLong = Long.valueOf(limit); 53 | long intervalPerPermit = intervalInMills / limitInLong; 54 | // Long refillTime = System.currentTimeMillis(); 55 | // log.info("调用redis执行lua脚本, {} {} {} {} {}", "ratelimit", intervalPerPermit, refillTime, 56 | // limit, intervalInMills); 57 | try { 58 | id = redisTemplate.execute(rateLimitScript, Collections.singletonList(key), 59 | String.valueOf(intervalPerPermit), String.valueOf(System.currentTimeMillis()), 60 | String.valueOf(limitInLong), String.valueOf(intervalInMills)); 61 | } catch (Exception e) { 62 | log.error("error", e); 63 | } 64 | 65 | if(id == 0L) { 66 | return false; 67 | } else { 68 | return true; 69 | } 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/resources/ratelimit/ratelimit.lua: -------------------------------------------------------------------------------- 1 | -- bucket name 2 | local key = KEYS[1] 3 | -- token generate interval 4 | local intervalPerPermit = tonumber(ARGV[1]) 5 | -- grant timestamp 6 | local refillTime = tonumber(ARGV[2]) 7 | -- limit token count 8 | local limit = tonumber(ARGV[3]) 9 | -- ratelimit time period 10 | local interval = tonumber(ARGV[4]) 11 | 12 | local counter = redis.call('hgetall', key) 13 | 14 | if table.getn(counter) == 0 then 15 | -- first check if bucket not exists, if yes, create a new one with full capacity, then grant access 16 | redis.call('hmset', key, 'lastRefillTime', refillTime, 'tokensRemaining', limit - 1) 17 | -- expire will save memory 18 | redis.call('expire', key, interval) 19 | return 1 20 | elseif table.getn(counter) == 4 then 21 | -- if bucket exists, first we try to refill the token bucket 22 | local lastRefillTime, tokensRemaining = tonumber(counter[2]), tonumber(counter[4]) 23 | local currentTokens 24 | if refillTime > lastRefillTime then 25 | -- check if refillTime larger than lastRefillTime. 26 | -- if not, it means some other operation later than this call made the call first. 27 | -- there is no need to refill the tokens. 28 | local intervalSinceLast = refillTime - lastRefillTime 29 | if intervalSinceLast > interval then 30 | currentTokens = limit 31 | redis.call('hset', key, 'lastRefillTime', refillTime) 32 | else 33 | local grantedTokens = math.floor(intervalSinceLast / intervalPerPermit) 34 | if grantedTokens > 0 then 35 | -- ajust lastRefillTime, we want shift left the refill time. 36 | local padMillis = math.fmod(intervalSinceLast, intervalPerPermit) 37 | redis.call('hset', key, 'lastRefillTime', refillTime - padMillis) 38 | end 39 | currentTokens = math.min(grantedTokens + tokensRemaining, limit) 40 | end 41 | else 42 | -- if not, it means some other operation later than this call made the call first. 43 | -- there is no need to refill the tokens. 44 | currentTokens = tokensRemaining 45 | end 46 | 47 | assert(currentTokens >= 0) 48 | 49 | if currentTokens == 0 then 50 | -- we didn't consume any keys 51 | redis.call('hset', key, 'tokensRemaining', currentTokens) 52 | return 0 53 | else 54 | -- we take 1 token from the bucket 55 | redis.call('hset', key, 'tokensRemaining', currentTokens - 1) 56 | return 1 57 | end 58 | else 59 | error("Size of counter is " .. table.getn(counter) .. ", Should Be 0 or 4.") 60 | end -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/controller/FlashSaleController.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.controller; 2 | 3 | import com.hqs.flashsales.annotation.DistriLimitAnno; 4 | import com.hqs.flashsales.aspect.LimitAspect; 5 | import com.hqs.flashsales.lock.DistributedLock; 6 | import com.hqs.flashsales.limit.DistributedLimit; 7 | import com.hqs.flashsales.service.OrderService; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.data.redis.core.RedisTemplate; 11 | import org.springframework.data.redis.core.script.RedisScript; 12 | import org.springframework.stereotype.Controller; 13 | import org.springframework.web.bind.annotation.GetMapping; 14 | import org.springframework.web.bind.annotation.PostMapping; 15 | import org.springframework.web.bind.annotation.ResponseBody; 16 | 17 | import javax.annotation.Resource; 18 | import java.util.Collections; 19 | 20 | 21 | /** 22 | * @author huangqingshi 23 | * @Date 2019-01-23 24 | */ 25 | @Slf4j 26 | @Controller 27 | public class FlashSaleController { 28 | 29 | @Autowired 30 | OrderService orderService; 31 | @Autowired 32 | DistributedLock distributedLock; 33 | @Autowired 34 | LimitAspect limitAspect; 35 | //注意RedisTemplate用的String,String,后续所有用到的key和value都是String的 36 | @Autowired 37 | RedisTemplate redisTemplate; 38 | 39 | private static final String LOCK_PRE = "LOCK_ORDER"; 40 | 41 | @PostMapping("/initCatalog") 42 | @ResponseBody 43 | public String initCatalog() { 44 | try { 45 | orderService.initCatalog(); 46 | } catch (Exception e) { 47 | log.error("error", e); 48 | } 49 | 50 | return "init is ok"; 51 | } 52 | 53 | @PostMapping("/placeOrder") 54 | @ResponseBody 55 | @DistriLimitAnno(limitKey = "limit", limit = 100, seconds = "1") 56 | public Long placeOrder(Long orderId) { 57 | Long saleOrderId = 0L; 58 | boolean locked = false; 59 | String key = LOCK_PRE + orderId; 60 | String uuid = String.valueOf(orderId); 61 | try { 62 | locked = distributedLock.distributedLock(key, uuid, 63 | "10" ); 64 | if(locked) { 65 | //直接操作数据库 66 | // saleOrderId = orderService.placeOrder(orderId); 67 | //操作缓存 异步操作数据库 68 | saleOrderId = orderService.placeOrderWithQueue(orderId); 69 | } 70 | log.info("saleOrderId:{}", saleOrderId); 71 | } catch (Exception e) { 72 | log.error(e.getMessage()); 73 | } finally { 74 | if(locked) { 75 | distributedLock.distributedUnlock(key, uuid); 76 | } 77 | } 78 | return saleOrderId; 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/config/ScriptConfig.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.config; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.beans.factory.annotation.Configurable; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.core.io.ClassPathResource; 8 | import org.springframework.data.redis.core.script.RedisScript; 9 | import org.springframework.scripting.ScriptSource; 10 | import org.springframework.scripting.support.ResourceScriptSource; 11 | 12 | /** 13 | * @author huangqingshi 14 | * @Date 2019-01-23 15 | */ 16 | @Slf4j 17 | @Configuration 18 | public class ScriptConfig { 19 | 20 | /** 21 | * The script resultType should be one of 22 | * Long, Boolean, List, or a deserialized value type. It can also be null if the script returns 23 | * a throw-away status (specifically, OK). 24 | * @return 25 | */ 26 | @Bean 27 | public RedisScript limitScript() { 28 | RedisScript redisScript = null; 29 | try { 30 | ScriptSource scriptSource = new ResourceScriptSource(new ClassPathResource("/scripts/limit.lua")); 31 | // log.info("script:{}", scriptSource.getScriptAsString()); 32 | redisScript = RedisScript.of(scriptSource.getScriptAsString(), Long.class); 33 | } catch (Exception e) { 34 | log.error("error", e); 35 | } 36 | return redisScript; 37 | 38 | } 39 | 40 | @Bean 41 | public RedisScript lockScript() { 42 | RedisScript redisScript = null; 43 | try { 44 | ScriptSource scriptSource = new ResourceScriptSource(new ClassPathResource("/scripts/lock.lua")); 45 | redisScript = RedisScript.of(scriptSource.getScriptAsString(), Boolean.class); 46 | } catch (Exception e) { 47 | log.error("error" , e); 48 | } 49 | return redisScript; 50 | } 51 | 52 | @Bean 53 | public RedisScript unlockScript() { 54 | RedisScript redisScript = null; 55 | try { 56 | ScriptSource scriptSource = new ResourceScriptSource(new ClassPathResource("/scripts/unlock.lua")); 57 | redisScript = RedisScript.of(scriptSource.getScriptAsString(), Long.class); 58 | } catch (Exception e) { 59 | log.error("error" , e); 60 | } 61 | return redisScript; 62 | } 63 | 64 | @Bean 65 | public RedisScript rateLimitScript() { 66 | RedisScript redisScript = null; 67 | try { 68 | ScriptSource scriptSource = new ResourceScriptSource(new ClassPathResource("/ratelimit/ratelimit.lua")); 69 | redisScript = RedisScript.of(scriptSource.getScriptAsString(), Long.class); 70 | } catch (Exception e) { 71 | log.error("error" , e); 72 | } 73 | return redisScript; 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.2.RELEASE 9 | 10 | 11 | com.hqs 12 | flashsales 13 | 0.0.1-SNAPSHOT 14 | flashsales 15 | Flash sale project 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-aop 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-data-redis 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-web 33 | 34 | 35 | org.mybatis.spring.boot 36 | mybatis-spring-boot-starter 37 | 2.0.0 38 | 39 | 40 | mysql 41 | mysql-connector-java 42 | 43 | 44 | org.projectlombok 45 | lombok 46 | true 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-test 51 | test 52 | 53 | 54 | io.springfox 55 | springfox-swagger-ui 56 | 2.9.2 57 | 58 | 59 | io.springfox 60 | springfox-swagger2 61 | 2.9.2 62 | compile 63 | 64 | 65 | redis.clients 66 | jedis 67 | 2.9.0 68 | 69 | 70 | org.springframework.boot 71 | spring-boot-devtools 72 | runtime 73 | 74 | 75 | 76 | 77 | 78 | 79 | org.springframework.boot 80 | spring-boot-maven-plugin 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /src/main/java/com/hqs/flashsales/service/impl/OrderServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.hqs.flashsales.service.impl; 2 | 3 | 4 | import com.hqs.flashsales.Mapper.CatalogMapper; 5 | import com.hqs.flashsales.Mapper.SalesOrderMapper; 6 | import com.hqs.flashsales.Model.Catalog; 7 | import com.hqs.flashsales.Model.SalesOrder; 8 | import com.hqs.flashsales.service.OrderService; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.data.redis.core.RedisTemplate; 12 | import org.springframework.stereotype.Service; 13 | import org.springframework.transaction.annotation.Transactional; 14 | 15 | import java.util.concurrent.ArrayBlockingQueue; 16 | import java.util.concurrent.BlockingQueue; 17 | 18 | /** 19 | * @author huangqingshi 20 | * @Date 2019-01-23 21 | */ 22 | @Transactional(rollbackFor = Exception.class) 23 | @Service 24 | @Slf4j 25 | public class OrderServiceImpl implements OrderService { 26 | 27 | @Autowired 28 | private CatalogMapper catalogMapper; 29 | @Autowired 30 | private SalesOrderMapper salesOrderMapper; 31 | @Autowired 32 | RedisTemplate redisTemplate; 33 | 34 | private static final String CATALOG_TOTAL = "CATALOG_TOTAL"; 35 | private static final String CATALOG_SOLD = "CATALOG_SOLD"; 36 | private BlockingQueue catalogs = new ArrayBlockingQueue<>(1000); 37 | 38 | 39 | @Override 40 | public void initCatalog() { 41 | Catalog catalog = new Catalog(); 42 | catalog.setName("mac"); 43 | catalog.setTotal(1000L); 44 | catalog.setSold(0L); 45 | catalogMapper.insertCatalog(catalog); 46 | log.info("catalog:{}", catalog); 47 | redisTemplate.opsForValue().set(CATALOG_TOTAL + catalog.getId(), catalog.getTotal().toString()); 48 | redisTemplate.opsForValue().set(CATALOG_SOLD + catalog.getId(), catalog.getSold().toString()); 49 | log.info("redis value:{}", redisTemplate.opsForValue().get(CATALOG_TOTAL + catalog.getId())); 50 | handleCatalog(); 51 | } 52 | 53 | private void handleCatalog() { 54 | new Thread(() -> { 55 | try { 56 | for(;;) { 57 | Long catalogId = catalogs.take(); 58 | if(catalogId != 0) { 59 | Catalog catalog = catalogMapper.selectCatalog(catalogId); 60 | catalog.setSold(catalog.getSold() + 1); 61 | SalesOrder salesOrder = new SalesOrder(); 62 | salesOrder.setCid(catalogId); 63 | salesOrder.setName(catalog.getName()); 64 | catalogMapper.updateCatalog(catalog); 65 | salesOrderMapper.insertSalesOrder(salesOrder); 66 | log.info("returned salesOrder.id:{}", salesOrder.getId()); 67 | } 68 | } 69 | 70 | } catch (Exception e) { 71 | log.error("error", e); 72 | } 73 | }).start(); 74 | } 75 | 76 | @Override 77 | public Long placeOrder(Long catalogId) { 78 | 79 | Integer total = Integer.parseInt(redisTemplate.opsForValue().get(CATALOG_TOTAL + catalogId)); 80 | Integer sold = Integer.parseInt(redisTemplate.opsForValue().get(CATALOG_SOLD + catalogId)); 81 | if (total.equals(sold)){ 82 | throw new RuntimeException("ALL SOLD OUT: " + catalogId); 83 | } 84 | 85 | Catalog catalog = catalogMapper.selectCatalog(catalogId); 86 | catalog.setSold(catalog.getSold() + 1); 87 | SalesOrder salesOrder = new SalesOrder(); 88 | salesOrder.setCid(catalogId); 89 | salesOrder.setName(catalog.getName()); 90 | catalogMapper.updateCatalog(catalog); 91 | salesOrderMapper.insertSalesOrder(salesOrder); 92 | log.info("returned salesOrder.id:{}", salesOrder.getId()); 93 | //自增 94 | redisTemplate.opsForValue().increment(CATALOG_SOLD + catalogId,1) ; 95 | return salesOrder.getId(); 96 | } 97 | 98 | @Override 99 | public Long placeOrderWithQueue(Long catalogId) { 100 | String totalCache = redisTemplate.opsForValue().get(CATALOG_TOTAL + catalogId); 101 | String soldCache = redisTemplate.opsForValue().get(CATALOG_SOLD + catalogId); 102 | if(totalCache == null || soldCache == null) { 103 | throw new RuntimeException("Not Initialized: " + catalogId); 104 | } 105 | 106 | Integer total = Integer.parseInt(totalCache); 107 | Integer sold = Integer.valueOf(soldCache); 108 | 109 | if (total.equals(sold)){ 110 | throw new RuntimeException("ALL SOLD OUT: " + catalogId); 111 | } 112 | try { 113 | catalogs.put(catalogId); 114 | } catch (Exception e) { 115 | log.error("error", e); 116 | } 117 | 118 | //自增 119 | Long soldId = redisTemplate.opsForValue().increment(CATALOG_SOLD + catalogId,1) ; 120 | return soldId; 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing my 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.4.2/maven-wrapper-0.4.2.jar" 124 | FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( 125 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 126 | ) 127 | 128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 130 | if exist %WRAPPER_JAR% ( 131 | echo Found %WRAPPER_JAR% 132 | ) else ( 133 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 134 | echo Downloading from: %DOWNLOAD_URL% 135 | powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" 136 | echo Finished downloading %WRAPPER_JAR% 137 | ) 138 | @REM End of extension 139 | 140 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 141 | if ERRORLEVEL 1 goto error 142 | goto end 143 | 144 | :error 145 | set ERROR_CODE=1 146 | 147 | :end 148 | @endlocal & set ERROR_CODE=%ERROR_CODE% 149 | 150 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 151 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 152 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 153 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 154 | :skipRcPost 155 | 156 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 157 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 158 | 159 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 160 | 161 | exit /B %ERROR_CODE% 162 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # 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 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | ########################################################################################## 204 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 205 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 206 | ########################################################################################## 207 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 208 | if [ "$MVNW_VERBOSE" = true ]; then 209 | echo "Found .mvn/wrapper/maven-wrapper.jar" 210 | fi 211 | else 212 | if [ "$MVNW_VERBOSE" = true ]; then 213 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 214 | fi 215 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" 216 | while IFS="=" read key value; do 217 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 218 | esac 219 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 220 | if [ "$MVNW_VERBOSE" = true ]; then 221 | echo "Downloading from: $jarUrl" 222 | fi 223 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 224 | 225 | if command -v wget > /dev/null; then 226 | if [ "$MVNW_VERBOSE" = true ]; then 227 | echo "Found wget ... using wget" 228 | fi 229 | wget "$jarUrl" -O "$wrapperJarPath" 230 | elif command -v curl > /dev/null; then 231 | if [ "$MVNW_VERBOSE" = true ]; then 232 | echo "Found curl ... using curl" 233 | fi 234 | curl -o "$wrapperJarPath" "$jarUrl" 235 | else 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Falling back to using Java to download" 238 | fi 239 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 240 | if [ -e "$javaClass" ]; then 241 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 242 | if [ "$MVNW_VERBOSE" = true ]; then 243 | echo " - Compiling MavenWrapperDownloader.java ..." 244 | fi 245 | # Compiling the Java class 246 | ("$JAVA_HOME/bin/javac" "$javaClass") 247 | fi 248 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 249 | # Running the downloader 250 | if [ "$MVNW_VERBOSE" = true ]; then 251 | echo " - Running MavenWrapperDownloader.java ..." 252 | fi 253 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 254 | fi 255 | fi 256 | fi 257 | fi 258 | ########################################################################################## 259 | # End of extension 260 | ########################################################################################## 261 | 262 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 263 | if [ "$MVNW_VERBOSE" = true ]; then 264 | echo $MAVEN_PROJECTBASEDIR 265 | fi 266 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 267 | 268 | # For Cygwin, switch paths to Windows format before running java 269 | if $cygwin; then 270 | [ -n "$M2_HOME" ] && 271 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 272 | [ -n "$JAVA_HOME" ] && 273 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 274 | [ -n "$CLASSPATH" ] && 275 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 276 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 277 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 278 | fi 279 | 280 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 281 | 282 | exec "$JAVACMD" \ 283 | $MAVEN_OPTS \ 284 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 285 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 286 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 287 | --------------------------------------------------------------------------------