RabbitMQ开发流程
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
配置MQ
最简配置
spring:
rabbitmq:
host: mq的安装机器ip
port: 5672
username: admin
password: 123
创建队列
在配置类中创建队列对象。
@Configuration
public class SimpleQueueConfig {
@Bean
public Queue queue(){
}
}
生产者
- private RabbitTemplate rabbitTemplate; //rabbitmq操作对象
- convertAndSend : 发送方法
if (m > 0) {
Long maotai = stringRedisTemplate.opsForValue()
.decrement("maotai");//原子性redis操作
log.debug("抢购茅台一瓶,还剩:{}瓶", maotai);
s1 =System.currentTimeMillis();
//操作数据库修改数据
rabbitTemplate.convertAndSend("hello_queue",1);
s2 =System.currentTimeMillis();
log.debug("耗时:{}ms",(s2-s1));
return HttpResp.success("去库存成功:"+(s2-s1));
} else {
return HttpResp.failed("0");
}
消费者
- @RabbitListener(queues = “要监听的队列名称”)
- @RabbitHandler //要使用RabbitMQ处理的方法
@RabbitListener(queues = "hello_queue")
@Override
public void updateByBookIdMq(Long bookId) throws InterruptedException {
LambdaQueryWrapper<Store>
queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Store::getBook, bookId);
Store store = storeDao.selectOne(queryWrapper);
if (store.getNum() > 0) {
int left = store.getNum() - 1;
Thread.sleep(50);
store.setNum(left);
storeDao.updateById(store);
log.debug("数据库修改数据完成,库存量:{}", left);
}
}