几个自动配置类:
1.RabbitAutoConfiguration
2.有自动配置了连接工厂 ConnectionFactory
3.RabbitProperties 封装了RabbitMQ的配置
4.RabiitTemlate:给RabbitMQ发送和接收消息
5.AmqpAdmin:RabbitMQ系统管理功能组件(可以创建exchange,queue,Binding)
6.@EnableRabbit+@RabbitListener 监听消息队列的内容
- 配置文件写法:
spring.rabbitmq.host=192.168.0.113 spring.rabbitmq.username=guest spring.rabbitmq.password=guest #端口5672默认可以不写 #spring.rabbitmq.virtual-host= 默认/可以不写
- 测试类:
@SpringBootTest public class Springboot002AmqpApplicationTests { @Autowired RabbitTemplate rabbitTemplate; /* 1.单播(点对点) public Message(byte[] body, MessageProperties messageProperties) { this.body = body; this.messageProperties = messageProperties; } * */ @Test public void contextLoads() { //交换器,路邮件,消息 //Message需要自己构造一个,定一消息体内容和消息头 //rabbitTemplate.send(exchange,routekey,message); //转法并发送,Object默认当成消息体,只需要传入要发送的对象,自动序列化保存发送给rabbitmq //rabbitTemplate.convertAndSend(exchange,routKey,object); Map <String ,Object>map = new HashMap<>(); map.put("msg","这是第一个消息"); map.put("data", Arrays.asList("helloWorld","123",true)); //对象被默认序列化后发送出去 //rabbitTemplate.convertAndSend("exchange.direct","springbootTest.news",map); //json发送MyAMQPConfig类配置 rabbitTemplate.convertAndSend("exchange.direct","springbootTest.news",new Book("西游记","吴承恩")); } //接收 @Test public void receive(){ Object o = rabbitTemplate.receiveAndConvert("springbootTest.news"); //打印数据类型 System.out.println(o.getClass()); System.out.println(o); } /* * 1.单播 * */ @Test public void setOneMsg(){ rabbitTemplate.convertAndSend("exchange.direct","springbootTest",new Book("水浒传","单播")); /* * 2.广播 * */ @Test public void setAllMsg(){ rabbitTemplate.convertAndSend("exchange.fanout","",new Book("红楼梦","曹雪芹")); }
发送消息时如不配置序列化方法则按照java默认序列化机制,则会造成发送编码不符合
解决方法:
json发送MyAMQPConfig类配置
@Configuration public class MyAMQPConfig { @Bean public MessageConverter messageConverter(){ return new Jackson2JsonMessageConverter(); } }