思路
商品秒杀是典型的高并发场景,为了提高性能,减少数据库的访问次数可以把数据加载到redis中,在redis中进行商品的库存减少,而且不会存在线程安全问题,当redis中商品减少成功后,可以把消息推送到rabbitMQ中,实现异步同步到数据库,让数据库按照他自己本身的处理能力到rabbitmq中去取消息.
项目架构
项目架构
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- springboot 集成rabbitMQ的包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
交换机和队列全部在消费者端定义
@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", "抢购成功");
参考资料:
来源:CSDN
作者:thoughtCodes
链接:https://blog.csdn.net/xiamaocheng/article/details/104267787