1.秒杀接口优化的思路
今天主要讲秒杀接口优化,就是对系统中 do_seckill 接口的优化。秒杀接口是系统中的核心接口,这个接口能承受的并发量直接决定了秒杀系统的性能。因为访问数据库是比较耗时的操作,所以秒杀优化的核心思路就是减少数据库的访问,具体思路如下:
- 在系统初始化的时候,把商品库存数量加载到 Redis 缓存中;
- 收到请求时,Redis 先预减库存,库存不足,直接返回,就不用访问数据库了,否则就进行下面的操作;
- 上面 Redis 预减判断有库存,就将这个请求加入消息队列中,返回排队中;
- 请求出队,减库存,生成订单;
- 前端轮询发起请求,查看是否秒杀成功;
既然用到了 RabbitMQ,首先要先安装,然后启动,步骤的话,善于利用搜索引擎嘿嘿!
2.Spring Boot 集成 RabbitMQ
2.1.添加依赖和配置
<!--RabbitMQ 依赖,RabbitMQ 是基于AMQP协议的--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency>
#rabbitmq
spring.rabbitmq.host=47.97.40.86
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/
#消费者数量,1的话就是串行
spring.rabbitmq.listener.simple.concurrency=10
spring.rabbitmq.listener.simple.max-concurrency=10
#连接每次取几个
spring.rabbitmq.listener.simple.prefetch=1
#默认消费者自动启动
spring.rabbitmq.listener.simple.auto-startup=true
#消费者消费失败,数据重新压回来,相当于重试
spring.rabbitmq.listener.simple.default-requeue-rejected= true
#重试的一些参数,根据场景微调
spring.rabbitmq.template.retry.enabled=true
spring.rabbitmq.template.retry.initial-interval=1000
spring.rabbitmq.template.retry.max-attempts=3
spring.rabbitmq.template.retry.max-interval=10000
spring.rabbitmq.template.retry.multiplier=1.0
注意!上面是用 guest 进行访问的,guest 不能远程连接,只能在本机,所以如果 MQ 不是本机的,要在远程 MQ 根路径的 etc/rabbitmq 目录下面新建如下配置文件:

并写入:
2.2.定义配置类、创建消息发送者、消息接收者
配置类主要定义用到的队列、交换机、绑定规则,因为 RabbitMQ 的 Exchange 有不同绑定队列的模式,对应的发送者和接收者也不一样。最简单的是 direct 模式,直接和队列绑定,常用的还有 topic 和 fanout 模式,他们是将消息先发送给 Exchange 交换机上面,然后由交换机把消息发送到队列中,做了一个路由。
direct模式
direct 模式是直接和队列绑定的,这是最简单的模式。
配置类中:@Configuration public class MQConfig { // 队列 public static final String QUEUE_NAME = "queue"; /** * Direct模式 交换机Exchange,这里默认交换机,@Bean 注解是产生一个队列对象,给spring管理 **/ @Bean public Queue queue() { return new Queue(QUEUE_NAME, true); // 设置队列名称,是否持久化 } }发送者:
@Service public class MQSender { private static Logger log = LoggerFactory.getLogger(MQSender.class); //AmqpTemplate 接口定义了发送和接收消息的基本操作 @Autowired AmqpTemplate amqpTemplate; // direct 发送 public void send(Object message) { String msg = RedisService.beanToString(message); // 转成 String log.info("send message : " + msg); amqpTemplate.convertAndSend(MQConfig.QUEUE_NAME, msg); // 将消息msg发送到指定队列中 } }接收者:
@Service public class MQReceiver { private static Logger log = LoggerFactory.getLogger(MQReceiver.class); // direct 接收,@RabbitListener注解用于监听 queues 中指定的队列 @RabbitListener(queues = MQConfig.QUEUE_NAME) public void receive(String message) { log.info("receive message : " + message); } }在 TestController 中测试及结果:
@RequestMapping("mq") @ResponseBody public Result<String> mq() { sender.send("hello,ckj"); return Result.success("Hello,world"); }
topic 模式
可以理解为通配符匹配模式,看示例就知道了。
配置类中:@Configuration public class MQConfig { // 队列 public static final String QUEUE_NAME = "queue"; public static final String TOPIC_QUEUE1 = "topic.queue1"; public static final String TOPIC_QUEUE2 = "topic.queue2"; // 交换机 public static final String TOPIC_EXCHANGE = "topicExchange"; /** * Topic模式,这里需要创建队列,交换机,以及他们之间的BindingKey,*代表一个单词,#代表0个或多个单词 **/ @Bean public Queue topicQueue1() { return new Queue(TOPIC_QUEUE1, true); } @Bean public Queue topicQueue2() { return new Queue(TOPIC_QUEUE2, true); } @Bean public TopicExchange topicExchange(){ return new TopicExchange(TOPIC_EXCHANGE); } @Bean public Binding topicBinding1() { return BindingBuilder.bind(topicQueue1()).to(topicExchange()).with("topic.key1"); } @Bean public Binding topicBinding2() { return BindingBuilder.bind(topicQueue2()).to(topicExchange()).with("topic.#"); // topic 模式支持通配符 } }发送者:
// topic 发送,发送两个消息,第一个消息,两个队列都能收到,第二个消息,只有第二个队列能收到 public void sendTopic(Object message) { String msg = RedisService.beanToString(message); log.info("send topic message : " + msg); amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE, "topic.key1", msg + "1"); amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE, "topic.key2", msg + "2"); }接收者:
// topic 接收,分别监听队列1和队列2 @RabbitListener(queues = MQConfig.TOPIC_QUEUE1) public void receiveTopic1(String message) { log.info("topic queue1 message : " + message); } @RabbitListener(queues = MQConfig.TOPIC_QUEUE2) public void receiveTopic2(String message) { log.info("topic queue2 message : " + message); }测试结果:
@RequestMapping("mq/topic") @ResponseBody public Result<String> topic() { sender.sendTopic("hello,ckj"); return Result.success("Hello,world"); }
结果当然是,消息1可以发送到队列1、队列2,消息2只能发送到队列2。fanout 模式
fanout 模式类似于广播,它会将消息推送到所有队列。
配置类中,我们还是用上面 topic 的队列。交换机和绑定需要新建:// 交换机 public static final String FANOUT_EXCHANGE = "fanoutExchange"; /** * Fanout模式 交换机Exchange,广播模式,不需要key * */ @Bean public FanoutExchange fanoutExchange(){ return new FanoutExchange(FANOUT_EXCHANGE); } @Bean public Binding FanoutBinding1() { return BindingBuilder.bind(topicQueue1()).to(fanoutExchange()); } @Bean public Binding FanoutBinding2() { return BindingBuilder.bind(topicQueue2()).to(fanoutExchange()); }发送者:
// fanout public void sendFanout(Object message) { String msg = RedisService.beanToString(message); log.info("send fanout message : " + msg); amqpTemplate.convertAndSend(MQConfig.FANOUT_EXCHANGE, "", msg); }接收者还是用 topic 的。
测试以及结果:@RequestMapping("mq/fanout") @ResponseBody public Result<String> fanout() { sender.sendFanout("hello,ckj"); return Result.success("Hello,world"); }
至此,RabbitMQ 差不多就准备好了。下面就用这个来对秒杀接口进行优化,看看能用在什么地方。3.秒杀接口优化
根据第1部分的思路来。
首先,预加载商品库存到 Redis 中。SeckillController 实现 InitializingBean 接口,重写 afterPropertiesSet 方法,这个方法会在初始化的时候调用。
// 实现了 InitializingBean 接口重写的方法,系统启动的时候,就将数据存入Redis
@Override
public void afterPropertiesSet() throws Exception {
//加载所有秒杀商品
List<GoodsVo> goodsList = goodsService.listGoodsVo();
if(goodsList == null) return;
//存入Redis中,各秒杀商品的数量
for (GoodsVo goods : goodsList){
redisService.set(GoodsKey.seckillGoodsStock, "" + goods.getId(), goods.getStockCount());
}
}
- 在秒杀操作进行的时候,就可以先查询 Redis 缓存,进行预减,判断是否还有库存,就不用查数据库来判断了。如果没有库存,直接返回,如果还有库存,再判断是否已经秒杀到了,如果还能往下走,那就可以进行秒杀,将请求加入消息队列。
- 有库存,没秒杀过,封装秒杀消息,包含商品 id 和 user,将秒杀消息发送到队列。
配置类中这里直接用 direct 模式,新建秒杀队列。发送者如下:
秒杀消息入队:// 秒杀 public void sendSeckillMessage(SeckillMessage sm) { String msg = RedisService.beanToString(sm); log.info("send seckill message : " + msg); amqpTemplate.convertAndSend(MQConfig.SECKILL_QUEUE, msg); }
- 请求出队,接收者消费消息,这里就是在接收者中进行秒杀业务操作:
@RabbitListener(queues = MQConfig.SECKILL_QUEUE)
public void receive(String message) {
log.info("receive seckill message : " + message);
SeckillMessage sm = RedisService.stringToBean(message, SeckillMessage.class);
SeckillUser user = sm.getUser();
long goodsId = sm.getGoodsId();
// 判断库存
GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
int stock = goods.getStockCount();
if(stock <= 0) {
return;
}
//判断是否已经秒杀过了
SeckillOrder order = orderService.getSeckillOrderByUserIdGoodsId(user.getId(), goodsId);
if(order != null) {
return;
}
//有库存,没秒杀过,开始减库存 下订单
seckillService.seckill(user, goods);
}
- 前端进行轮询,查询秒杀结果
下面就是让前端做轮询操作。当秒杀返回 0,代表排队中,此时应该去发起轮询请求。

轮询查询结果成功时,判断返回的数据部分,是数字几:

此时,后端也是需要一个查询结果的接口的:
到这里,此时应该差不多了。但是仔细想想下面的部分代码:

如果有 10 个库存,前面 10 个请求已经将 stock 变成 0 了,当第 11 个请求过来时,stock 变成 -1,当第 12 个请求过来时,stock 变为 -2,啥意思?这里就是说,当库存变为负数时,后面还要去减,是没必要的,连 redis 访问也没必要了。那这里应该怎么办呢?
答案是做内存标记。
我们设置一个 map 集合,里面存放的是(商品 id——flase)键值对,代表那个商品没有秒杀完。在系统初始化的时候,存入这个 map。

当 Redis 预减库存后,发现库存是负数了,就可以把 map 集合中对应商品 value 值设置为 true,表示这个商品已经秒杀完。

这样,第 12 个以及后面的请求,连 redis 也不会访问了。又省一大堆事了!
/**返回:
* orderId:成功
* -1:秒杀失败
* 0: 排队中
* */
@RequestMapping(value = "result", method = RequestMethod.GET)
@ResponseBody
public Result<Long> seckillResult(Model model, SeckillUser user, @RequestParam("goodsId") long goodsId) {
model.addAttribute("user", user);
if(user == null) {
return Result.error(CodeMsg.SESSION_ERROR);
}
if(goodsId <= 0){
return Result.error(CodeMsg.GOODS_NOT_EXIST);
}
long result = seckillService.getSeckillResult(user.getId(), goodsId); // 如果成功,返回订单id
return Result.success(result);
}
