Redis + RabbitMQ 解决秒杀高并发,实现异步处理

思路
商品秒杀是典型的高并发场景,为了提高性能,减少数据库的访问次数可以把数据加载到redis中,在redis中进行商品的库存减少,而且不会存在线程安全问题,当redis中商品减少成功后,可以把消息推送到rabbitMQ中,实现异步同步到数据库,让数据库按照他自己本身的处理能力到rabbitmq中去取消息.
项目架构

项目架构

 
    org.springframework.boot
    spring-boot-starter-parent
    2.0.5.RELEASE
    
  

  
    UTF-8
    1.8
    1.8
  

  
    
      org.springframework.boot
      spring-boot-starter-web
    
    
      org.springframework.boot
      spring-boot-starter-data-redis
    
    
      com.alibaba
      druid
      1.1.1
    
    
      com.baomidou
      mybatis-plus-boot-starter
      2.2.0
    
    
      mysql
      mysql-connector-java
    
    
    
      org.springframework.boot
      spring-boot-starter-amqp
    
  

 

交换机和队列全部在消费者端定义

@Configuration
public class RabbitmqConfig {



    public static final String SPIKE_QUEUE = "SPIKE_QUEUE";

    public static final String EXCHANGE_NAME = "SPIKE_EXCHANGE";

    /**
     * 交换机配置
     * ExchangeBuilder提供了fanout、direct、topic、header交换机类型的配置
     *
     * @return the exchange
     */
    @Bean
    public Exchange EXCHANGE_DIRECT() {
    //durable(true)持久化,消息队列重启后交换机仍然存在
        return ExchangeBuilder.directExchange(EXCHANGE_NAME).durable(false).build();
    }

    //声明队列
    @Bean
    public Queue QUEUE_INFORM_SMS() {
        Queue queue = new Queue(SPIKE_QUEUE);
        return queue;
    }

//    @Value("${spring.rabbitmq.customizeRoutingKey=spike}")
    private String routingKey="spike";


    /**
     * channel.queueBind(INFORM_QUEUE_SMS,"inform_exchange_topic","inform.#.sms.#");
     * 绑定队列到交换机 .
     *
     */
    @Bean
    public Binding BINDING_QUEUE_INFORM_SMS( ) {
        return BindingBuilder.bind(QUEUE_INFORM_SMS()).to(EXCHANGE_DIRECT()).with(routingKey).noargs();
    }


}

 

 

 

消费者端监听队列,接收消息(这里是取消息同步数据库)

@Component
public class SpikeHandler {

    @Autowired
    private IPhoneService phoneService;

    @RabbitListener(queues = {RabbitmqConfig.SPIKE_QUEUE})
    public void synchronizeDB(String message, Message message1, Channel channel) throws IOException {
        System.out.println("接收到的信息" + message);
        if (message == null || StringUtils.isEmpty(message)) {
            throw new RuntimeException("接收消息异常");
        }
        phoneService.update();
//        手动签收消息
        long deliveryTag = message1.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag,true);
    }
}

 rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_NAME, "spike", "抢购成功");

 

参考资料:

https://blog.csdn.net/weixin_45336205/article/details/104230478?utm_source=distribute.pc_category.none-task

 

 

你可能感兴趣的:(【ARCH-架构】)