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


幾個自動配置類:

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();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM