一、RabbitMQ补充(以生产者和消费者举例)
1. 声明回调函数
//回调函数
RabbitTemplate.ConfirmCallback callback = (CorrelationData correlationData, boolean bl, String s) -> {
if (bl) {
}
};
2. 在控制层里的方法中实现具体的绑定
if (null != obj) {
//开启消息确认
rabbitTemplate.setMandatory(true);
//绑定回调函数
rabbitTemplate.setConfirmCallback(callback);
//创建对象
OrderDto orderDto = new OrderDto();
//拷贝到对象
BeanUtils.copyProperties(order, orderDto);
//创建关联数据对象
CorrelationData correlationData = new CorrelationData(orderDto.getOrderNum());
//将数据放入到MQ
rabbitTemplate.convertAndSend("meituanExchange", "order", orderDto, correlationData);
return true;
}
完成以上两步,就已经实现了将对象信息放到MQ中了。
接下来就是怎么将MQ中的数据取出来,并且实现功能了。
二、通过fegin调用生产者接口,且实现取出数据
1.1 首先在生产者这边的控制层定义实现的方法
@PutMapping("updateOrder/{orderNum}/{tag}")
public boolean updateOrder(@PathVariable("orderNum") String orderNum,
@PathVariable("tag") int tag) {
OrderEntity orderEntity = orderDao.findDistinctByOrderNum(orderNum);
orderEntity.setTag(tag);
orderEntity = orderDao.save(orderEntity);
if (null != orderEntity) {
return true;
}
return false;
}
这里使用的是RestFull风格。
1.2 在公共的模块包中实现该接口方法
@FeignClient(name = "order", url = "http://127.0.0.1:8006/order")
public interface IOrderService {
@PutMapping("updateOrder/{orderNum}/{tag}")
public boolean updateOrder(@PathVariable("orderNum") String orderNum,
@PathVariable("tag") int tag);
}
url为生产者的url地址加上端口号
1.3 在消费者服务层中导入
@Resource
private IOrderService orderService;
2 消费者从MQ中取数据且实现业务方法
@RabbitListener(queues = "meituanOrderQueue")
public void orderQueue(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, OrderDto orderDto) throws IOException {
if (null != orderDto) {
}
}
queues = “meituanOrderQueue”:是生产者中MQ的队列名
以上的内容就是通过RabbitMQ和fegin实现生产者到消费者的简单业务应用。将对象信息存入到MQ中,然后消费者从MQ中取出并且应用。