上一篇在springboot中基于自动配置集成了rabbitmq。那么回到最初的话题中就是想在秒杀下单环节增加排队机制,从而达到限流的目的。

 

      之前是在控制器里拿到客户端请求后直接入库、减库存。如果碰到羊毛党其实这套机制是不行的。并发量高的时候,库存数量也会不准确。那么引入rabbitmq则在下单时让用户信息产生一条消息入队。然后消费者处理下单(是否重复下单、下单失败、库存不够)。客户端接受到请求已入队列(response引入state处理交互)后发起ajax轮询请求,处理成功则跳转下单成功页或者结束本次交互。

 

  1. @RequestMapping(value="/{seckillId}/{md5}/execute",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
  2. @ResponseBody
  3. public SeckillResult<SeckillExecution> execute(@PathVariable("seckillId")Long seckillId,
  4. @PathVariable("md5")String md5,
  5. @CookieValue(value="phone",required=false)Long phone){
  6.  
  7. if(phone==null){
  8. return new SeckillResult<SeckillExecution>(false,"手机号未注册");
  9. }
  10.  
  11. SeckillResult<SeckillExecution> result=null;
  12.  
  13. try{
  14.  
  15. SeckillExecution execution=seckillService.executeSeckill(seckillId,phone,md5);
  16. result=new SeckillResult<SeckillExecution>(true,execution);
  17.  
  18. }catch(RepeatKillException e){
  19.  
  20. SeckillExecution execution=new SeckillExecution(seckillId,-1,"重复秒杀");
  21. result=new SeckillResult<SeckillExecution>(true,execution);
  22.  
  23.  
  24. }catch(SeckillCloseException e){
  25.  
  26. SeckillExecution execution=new SeckillExecution(seckillId,0,"秒杀结束");
  27. result=new SeckillResult<SeckillExecution>(true,execution);
  28.  
  29. }catch (Exception e){
  30.  
  31. SeckillExecution execution=new SeckillExecution(seckillId,-2,"系统异常");
  32. result=new SeckillResult<SeckillExecution>(true,execution);
  33.  
  34. }
  35.  
  36. return result;
  37.  
  38. }
  1. @Override
  2. public SeckillExecution executeSeckill(long seckillId, long phone, String md5)
  3. throws SeckillException,RepeatKillException,SeckillCloseException {
  4.  
  5. if (md5 == null || !md5.equals(getMd5(seckillId))) {
  6. throw new SeckillException("非法请求");
  7. }
  8.  
  9. Date now = new Date();
  10.  
  11. try {
  12. int insertCount = successKillDao.insertSuccessKilled(seckillId, phone);
  13. if (insertCount <= 0) {
  14. throw new RepeatKillException("重复秒杀");
  15.  
  16. } else {
  17.  
  18. //请求入队
  19. MiaoshaUser miaoshaUser=new MiaoshaUser();
  20. miaoshaUser.setPhone(phone);
  21.  
  22. MiaoshaMessage miaoshaMessage=new MiaoshaMessage();
  23. miaoshaMessage.setSeckillId(seckillId);
  24. miaoshaMessage.setMiaoshaUser(miaoshaUser);
  25.  
  26. String miaosha=JSON.toJSONString(miaoshaMessage);
  27. amqpTemplate.convertAndSend(miaosha);
  28.  
  29. return new SeckillExecution(seckillId,0,"请求入队");
  30.  
  31. /***
  32. * 直接入库操作
  33. int updateCount = seckillDao.reduceNumber(seckillId, now);
  34. if (updateCount <= 0) {
  35. throw new SeckillCloseException("秒杀已关闭");
  36. } else {
  37. //秒杀成功,可以把秒杀详情和商品详情实体返回
  38. SuccessKilled successKilled = successKillDao.queryByIdWithSeckill(seckillId, phone);
  39. return new SeckillExecution(seckillId, 1, "秒杀成功", successKilled);
  40. }
  41. ***/
  42. }
  43.  
  44. } catch (SeckillCloseException e) {
  45. throw e;
  46. } catch (RepeatKillException e1) {
  47. throw e1;
  48. } catch (SeckillException e2) {
  49. logger.error(e2.getMessage(), e2);
  50. throw new SeckillException("Unkonwn error:" + e2.getMessage());
  51. }
  52.  
  53. }
  1. @RequestMapping(value="/{seckillId}/{md5}/result",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"})
  2. @ResponseBody
  3. public SeckillResult<SeckillExecution> result(@PathVariable("seckillId")Long seckillId,
  4. @PathVariable("md5")String md5,
  5. @CookieValue(value="phone",required=false)Long phone){
  6.  
  7. SuccessKilled successKilled = seckillService.queryByIdWithSeckill(seckillId, phone);
  8. SeckillExecution execution=null;
  9. if(successKilled.getSeckillId()>0){
  10. execution=new SeckillExecution(seckillId, 1, "下单成功", successKilled);
  11. }else{
  12. execution=new SeckillExecution(seckillId, -2, "下单失败", successKilled);
  13. }
  14.  
  15. return new SeckillResult<SeckillExecution>(true,execution);
  16. }
  1. /**
  2. * 秒杀请求消费
  3. **/
  4. public class AmqpConsumer implements MessageListener {
  5.  
  6. @Autowired
  7. SeckillDao seckillDao;
  8.  
  9. @Autowired
  10. SuccessKillDao successKillDao;
  11.  
  12.  
  13. @Override
  14. public void onMessage(Message message) {
  15. Date now = new Date();
  16.  
  17. MiaoshaMessage miaosha = JSON.parseObject(message.getBody(), MiaoshaMessage.class);
  18.  
  19. Long seckillId = miaosha.getSeckillId();
  20. int updateCount = seckillDao.reduceNumber(seckillId, now);
  21. if (updateCount <= 0) {
  22. System.out.println("秒杀下单失败");
  23. } else {
  24. System.out.println("秒杀下单成功");
  25.  
  26. }
  27.  
  28.  
  29. }
  30. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:rabbit="http://www.springframework.org/schema/rabbit"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
  8.  
  9. <!--spring集成rabbitmq-->
  10. <rabbit:connection-factory id="connectionFactory"
  11. host="192.168.80.128"
  12. port="5672"
  13. username="admin"
  14. password="admin"
  15. channel-cache-size="5"
  16. virtual-host="/" />
  17.  
  18. <rabbit:admin connection-factory="connectionFactory"/>
  19. <!--声明队列-->
  20. <rabbit:queue durable="true" auto-delete="false" exclusive="false" name="miaosha.queue"/>
  21.  
  22. <!--交换器和队列绑定-->
  23. <rabbit:direct-exchange name="miaosha.exchange">
  24. <rabbit:bindings>
  25. <rabbit:binding queue="miaosha.queue" key="miaosha.tag.key"/>
  26. </rabbit:bindings>
  27. </rabbit:direct-exchange>
  28.  
  29. <!--spring rabbitmqTemplate声明-->
  30. <rabbit:template id="rabbitTemplate"
  31. exchange="miaosha.exchange"
  32. routing-key="miaosha.tag.key"
  33. connection-factory="connectionFactory" />
  34.  
  35. <!--消息监听-->
  36. <bean id="miaoshaConsumer" class="com.seckill.mq.AmqpConsumer"/>
  37. <rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto">
  38. <rabbit:listener ref="miaoshaConsumer" queues="miaosha.queue"/>
  39. </rabbit:listener-container>
  40. </beans>
  1. /**秒杀结果**/
  2. miaosha:function(seckillId,md5,node){
  3. $.get('/seckill/'+seckillId+'/'+md5+'/result',{},function(result){
  4. if(result && result["success"]){
  5. var oData=result["data"];
  6. if(oData["state"]===1){
  7. node.html("<span class='label label-success'>下单成功</span>");
  8.  
  9. clearInterval(miaoshaTimer);
  10. }else{
  11. console.log("还在排队种...");
  12. }
  13. }
  14. })
  15. },
  16. /**执行秒杀**/
  17. seckill:function(seckillId,node){
  18.  
  19. //获取秒杀地址、控制node节点显示,执行秒杀
  20. node.hide().html("<button id='killBtn' class='btn btn-primary btn-lg'>开始秒杀</button>")
  21.  
  22. $.get('/seckill/'+seckillId+'/exposer',{},function(result){
  23.  
  24. if(result && result["success"]){
  25. //在回调函数中执行秒杀操作
  26. var exposer=result["data"];
  27. if(exposer["exposed"]){
  28. //秒杀已开始
  29. var md5=exposer["md5"];
  30. var killUrl='/seckill/'+seckillId+'/'+md5+'/execute';
  31. console.log(killUrl);
  32.  
  33. $("#killBtn").one('click',function(){
  34. //1、禁用秒杀按钮
  35. $(this).addClass('disabled');
  36. //2、执行秒杀操作
  37. $.post(killUrl,{},function(result){
  38. if(result && result["success"]){
  39. var killResult=result["data"];
  40. var state=killResult["state"];
  41. var stateInfo=killResult["stateInfo"];
  42.  
  43. node.html("<span class='label label-success'>"+stateInfo+"</span>");
  44. if(state===0){
  45. //已入队,客户端开始轮询
  46. miaoshaTimer=setInterval(function(){
  47. seckill.miaosha(seckillId,md5,node);
  48. },3000);
  49. }
  50. }
  51. })
  52.  
  53. });
  54.  
  55. node.show();
  56. }else{
  57. //秒杀未开始, 防止浏览器和服务器出现时间差,再次执行倒数计时
  58. var now = exposer['now'];
  59. var start = exposer['start'];
  60. var end = exposer['end'];
  61. seckill.countdown(seckillId, now, start, end);
  62. }
  63.  
  64. }else{
  65. console.log('result:'+result); //没有拿到秒杀地址
  66. }
  67.  
  68. })
  69.  
  70. }

 好了,贴了这么多代码,没有示意图怎么能行?

 

      秒杀下单增加排队机制来说对于完整的秒杀系统来说只是其中很少的一部分,这里也只是学习rabbitmq的一个过程。对于秒杀系统来说流量主要是查询多下单少。还需要引入redis,把库存量、商品信息能在秒杀开始前预处理。

 

     https://blog.csdn.net/sunweiguo1/article/details/80470792

 

版权声明:本文为sword-successful原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/sword-successful/p/10368820.html