SpringBoot整合RabbitMQ
/** * 自动配置 * 1、RabbitAutoConfiguration * 2、有自动配置了连接工厂ConnectionFactory; * 3、RabbitProperties 封装了 RabbitMQ的配置 * 4、 RabbitTemplate :给RabbitMQ发送和接受消息; * 5、 AmqpAdmin : RabbitMQ系统管理功能组件; * AmqpAdmin:创建和删除 Queue,Exchange,Binding * 6、@EnableRabbit + @RabbitListener 监听消息队列的内容 * */
@EnableRabbit //开启基于注解的RabbitMQ模式
@SpringBootApplication
public class Springboot02AmqpApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot02AmqpApplication.class, args);
}
}
1、RabbitAutoConfiguration
2、有自动配置了连接工厂ConnectionFactory;
3、RabbitProperties 封装了 RabbitMQ的配置
4、 RabbitTemplate :给RabbitMQ发送和接受消息;
@Autowired
RabbitTemplate rabbitTemplate;
//发送数据
@Test
public void contextLoads() {
//rabbitTemplate.send(exchange,routeKey,message);
Map<String,Object> map = new HashMap<>();
map.put("msg","hello curry");
map.put("data", Arrays.asList("helloworld",123,true));
//默认使用application/x-java-serialized-object序列化规则
rabbitTemplate.convertAndSend("exchange.direct","atwyy.news",map);
}
//接收数据,如何将数据转为json发送
@Test
public void receive(){
Object receiveAndConvert = rabbitTemplate.receiveAndConvert("atwyy.news");
System.out.println(receiveAndConvert.getClass());
System.out.println(receiveAndConvert);
}
@Test
public void sendMsg(){
rabbitTemplate.convertAndSend("exchange.fanout","",new Book("围城","钱钟书"));
}
5、 AmqpAdmin : RabbitMQ系统管理功能组件;
AmqpAdmin:创建和删除 Queue,Exchange,Binding
@Autowired
AmqpAdmin amqpAdmin;
// //创建转换器
// @Test
// public void createExchange(){
// amqpAdmin.declareExchange(new DirectExchange("amqpadmin.exchange"));
// System.out.println("创建amqpadmin.exchange");
// }
// //创建队列
// @Test
// public void createQueue(){
// amqpAdmin.declareQueue(new Queue("amqpadmin.queue",true));
// System.out.println("创建amqpadmin.queue");
// }
// //绑定
// @Test
// public void createBinding(){
// amqpAdmin.declareBinding(new Binding("amqpadmin.queue", Binding.DestinationType.QUEUE,"amqpadmin.exchange","amqp.hh",null));
// }
6、@EnableRabbit + @RabbitListener 监听消息队列的内
@Service
public class BookService {
@RabbitListener(queues = "atwyy.news")
public void receive(Book book){
System.out.println("收到消息: " + book);
}
@RabbitListener(queues = "atwyy")
public void receive02(Message message){
System.out.println(message.getBody());
System.out.println(message.getMessageProperties());
}
}