首先了解我的这篇博客:https://www.cnblogs.com/yanxiaoge/p/11379715.html(下面的基于这篇博客中的配置)
1、创建项目
自动配置
1、RabbitAutoConfiguration
2、有自动配置了连接工厂ConnectionFactory;
3、RabbitProperties 封装了RabbitMQ的配置
4、RabbitTemplate:给RabbitMQ发送和接受消息;
5、AmqpAdmin:RabbitMQ系统管理功能组件
2、使用
2.1 application.properties
#host、port、virtual-host默认值都是下面配置的(可以不写) spring.rabbitmq.host=localhost spring.rabbitmq.username=guest spring.rabbitmq.password=guest spring.rabbitmq.port=5672 spring.rabbitmq.virtual-host=/
2.2 测试消息的发送和接受
@Autowired public RabbitTemplate rabbitTemplate; @Test public void contextLoads() { //Message需要自己构造一个;定义消息体内容和消息头 //rabbitTemplate.send(exchange,routingKey,message); //object默认当做消息体,只需要传入要发送的object,自动序列化发送给rabbitmq //rabbitTemplate.convertAndSend(exchange,routingKey,Object); HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("1","1"); hashMap.put("2","2"); rabbitTemplate.convertAndSend("exchange.direct","queue1",hashMap); //指定的exchange.direct是配置的点对点的,如果其他的可以自己测试 } @Test public void test2() { HashMap<String,String> queue1 = (HashMap<String, String>) rabbitTemplate.receiveAndConvert("queue1"); //注意如果取出来的数据不是HashMap,不能强转 System.out.println(queue1.get("1")); }
2.3 自定义序列化转换器,将数据以json数据存入到队列中,测试方法按照上面的测试(如果报错某个class找不到,可以自己导入 jackson-databind这个jar包)
@Configuration public class MyAMQPConfig { @Bean public MessageConverter messageConverter(){ return new Jackson2JsonMessageConverter(); } }
2.4 监听消息队列
2.4.1 @EnableRabbit
@EnableRabbit //开启注解的 RabbitMQ 模式 @SpringBootApplication public class Springboot11Application { public static void main(String[] args) { SpringApplication.run(Springboot11Application.class, args); } }
2.4.2 @RabbitListener
package com.zy.springboot11.service; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Service; import java.util.HashMap; @Service public class HashMapService { @RabbitListener(queues = "queue1") public void receive(HashMap<String,String> hashMap){ System.out.println("收到消息"+hashMap.toString()); } @RabbitListener(queues = "queue2") public void receive2(Message message){ System.out.println(message.getMessageProperties()); System.out.println(message.getBody()); } }
2.4.3 测试
方式1、开启服务器,通过http://localhost:15672/#/queues 给消息队列发送消息
方式2:、直接通过springboot的测试方法,不用开启服务器,(测试方法中的监听器就会将数据读取出来)
2.5 代码创建Exchange、queue、绑定规则
@Autowired public AmqpAdmin amqpAdmin; @Test public void create(){ //创建Exchange //Exchage可以设置durable、autoDelete等 //amqpAdmin.declareExchange(new DirectExchange("testExchage.direct")); //创建queue //amqpAdmin.declareQueue(new Queue("test.queue")); //绑定 //amqpAdmin.declareBinding(new Binding("test.queue",Binding.DestinationType.QUEUE,"testExchage.direct","test.queue",null)); //删除绑定 //amqpAdmin.removeBinding(new Binding("test.queue",Binding.DestinationType.QUEUE,"testExchage.direct","test.queue",null)); //删除queue(绑定关系就解除了) //amqpAdmin.deleteQueue("test.queue"); //删除exchange //amqpAdmin.deleteExchange("testExchage.direct"); }