28、springboot整合RabbitMQ(2)
1、监听
1.1、监听队列
如订单系统和库存系统
订单系统下订单之后将消息存放在消息队列中
库存系统需要时刻进行监听消息队列的内容,有新的订单就需要进行库存相关的操作
此时模拟监听消息队列中的Book信息
监听类:
@RabbitListener监听相关的消息队列
@Service public class BookService { @RabbitListener(queues = "atguigu.news") public void receive(Book book){ System.out.println("收到消息:" + book); } }
开启关于RabbitMq注解
//开启基于注解RabbitMq模式 @EnableRabbit @SpringBootApplication public class AmqpApplication { public static void main(String[] args) { SpringApplication.run(AmqpApplication.class, args); } }
后台的监听结果
1.2、获取消息头、消息体相关的参数
import org.springframework.stereotype.Service; @Service public class BookService { @RabbitListener(queues = "atguigu.news") public void receive(Book book){ System.out.println("收到消息:" + book); } //import org.springframework.amqp.core.Message; @RabbitListener(queues = "atguigu") public void receive02(Message message){ System.out.println(message.getBody()); System.out.println(message.getMessageProperties()); } }
打印的数据
[B@2d4a67c8 MessageProperties [headers={__TypeId__=com.cr.amqp.pojo.Book}, contentType=application/json, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=true, receivedExchange=exchange.fanout, receivedRoutingKey=, deliveryTag=1, consumerTag=amq.ctag-193ojwCpIAgVmLfB52Prkg, consumerQueue=atguigu] 收到消息:com.cr.amqp.pojo.Book@74095f6e
2、创建
假设有些信道活着队列不存在的情况
可以使用AmqpAdmin进行创建交换器,转换规则、队列(Queue、Exchange、Binding)
@Autowired
AmqpAdmin amqpAdmin;
//创建交换器
@Autowired AmqpAdmin amqpAdmin; public void createExchange(){ //package org.springframework.amqp.core; //public interface Exchange extends Declarable amqpAdmin.declareExchange(new DirectExchange("amqp.exchange")); }
结果:
交换器的类:
创建队列:
amqpAdmin.declareQueue(new Queue("amqpadmin.queue"));
绑定规则:
//绑定规则 amqpAdmin.declareBinding(new Binding("amqpadmin.queue",Binding.DestinationType.QUEUE,"amqp.exchange","amqp.aa",null));