RabbitMQ代碼操做之發消息和序列化機制

幾個自動配置類:java

1.RabbitAutoConfiguration
2.有自動配置了鏈接工廠 ConnectionFactory
3.RabbitProperties 封裝了RabbitMQ的配置
4.RabiitTemlate:給RabbitMQ發送和接收消息
5.AmqpAdmin:RabbitMQ系統管理功能組件(能夠建立exchange,queue,Binding)
6.@EnableRabbit+@RabbitListener 監聽消息隊列的內容spring

 

  • 配置文件寫法:
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(); } }
相關文章
相關標籤/搜索