前言
这篇文章主要介绍Rabbitmq的一个应用场景,以及如何使用SpringBoot进行整合。
场景介绍
假设某个电商系统中有商品服务负责MySQL中商品的增删改查,同时还有搜索服务负责Elasticsearch实现商品的搜索,Elasticsearch中的数据需要和MySQL中的数据进行同步。
这就需要两个服务之间进行通信,使用RabbitMQ可以实现。
业务流程:
- 商品服务对MySQL中的商品进行增删改
- 商品服务修改MySQL后,将修改商品的ID发送给MQ
- 搜索服务从MQ中读取商品ID
- 搜索服务通过商品服务查询商品信息
- 搜索服务将ES中的商品信息更新
SpringBoot整合Rabbitmq
1)在RabbitMQ新建Topic类型的交换机,名称:xray.mall.exchange
2)两个项目都导入starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2)配置RabbitMQ
发送方项目配置
rabbitmq:
username: guest
password: guest
host: 127.0.0.1
virtual-host: /
template:
exchange: xray.mall.exchange
publisher-confirms: true
接收方项目配置
rabbitmq:
addresses: 127.0.0.1:5672
username: guest
password: guest
3)配置队列
@Configuration
public class RabbitMQConfig {
@Bean
public Queue queueSave(){
return new Queue("queue_save");
}
@Bean
public Queue queueDelete(){
return new Queue("queue_delete");
}
}
发送和接收消息的核心代码:
发送方
//RabbitMQ的模板对象
@Autowired
private RabbitTemplate rabbitTemplate;
//发送消息到MQ 参数1 是交换机名称 参数2 是key 参数3 是数据
rabbitTemplate.convertAndSend("xray.mall.exchange","goods.save",goods.getId());
接受方
@Component
public class GoodsRabbitListener {
@Autowired
private GoodsFeign goodsFeign;
@Autowired
private GoodsRepository goodsRepository;
/**
* 配置监听器,bindings实现队列和交换机的绑定 @Queue配置队列 @Exchange配置交换机,key配置键
* 监听添加和更新
*/
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "queue_save",durable = "true"),
exchange = @Exchange(value = "xray.mall.exchange",
ignoreDeclarationExceptions = "true",
type = ExchangeTypes.TOPIC
),key={"goods.save"}))
public void receiveSave(Long id){
try {
System.out.println("保存id:" + id);
//通过feign调用Goods-service查询spu
JsonResult<Goods> res = goodsFeign.findGoodsById(id);
Goods goods = res.getData();
//保存到ES中
goodsRepository.save(goods);
System.out.println("save同步完成");
}catch (Exception ex){
ex.printStackTrace();
}
}
/**
* 监听删除
* /
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "queue_delete",durable = "true"),
exchange = @Exchange(value = "xray.mall.exchange",
ignoreDeclarationExceptions = "true",
type = ExchangeTypes.TOPIC
),key={"goods.delete"}))
public void receiveDelete(Long id){
try {
System.out.println("删除id:" + id);
//从ES删除
goodsRepository.deleteById(id);
System.out.println("delete同步完成");
}catch (Exception ex){
ex.printStackTrace();
}
}
}
结束
大家如果需要学习其他Java知识点,戳这里 超详细的Java知识点汇总