zoukankan      html  css  js  c++  java
  • 一、使用RabbitMQ传递对象

    一、使用RabbitMQ传递对象

    RabbitMQ是消息队列,发送和接收的都是字符串/字节数组类型的消息

    1.1 使用序列化对象

    要求:

    • 传递的对象实现序列化接口

    • 传递的对象的包名、类名、属性名必须一致

    • 消息提供者

      @Service
      public class MQService {
      
          @Resource
          private AmqpTemplate amqpTemplate;
      
          public void sendGoodsToMq(Goods goods){
              //消息队列可以发送 字符串、字节数组、序列化对象
              amqpTemplate.convertAndSend("","queue1",goods);
          }
      
      }
      
    • 消息消费者

      @Component
      @RabbitListener(queues = "queue1")
      public class ReceiveService {
      
          @RabbitHandler
          public void receiveMsg(Goods goods){
              System.out.println("Goods---"+goods);
          }
      
      }
      

    1.2 使用序列化字节数组

    要求:

    • 传递的对象实现序列化接口

    • 传递的对象的包名、类名、属性名必须一致

    • 消息提供者

      @Service
      public class MQService {
      
          @Resource
          private AmqpTemplate amqpTemplate;
      
          public void sendGoodsToMq(Goods goods){
              //消息队列可以发送 字符串、字节数组、序列化对象
              byte[] bytes = SerializationUtils.serialize(goods);
              amqpTemplate.convertAndSend("","queue1",bytes);
          }
      
      }
      
    • 消息消费者

      @Component
      @RabbitListener(queues = "queue1")
      public class ReceiveService {
      
          @RabbitHandler
          public void receiveMsg(byte[] bs){
              Goods goods = (Goods) SerializationUtils.deserialize(bs);
              System.out.println("byte[]---"+goods);
          }
      
      }
      

    1.3 使用JSON字符串传递

    要求:对象的属性名一致

    • 消息提供者

      @Service
      public class MQService {
      
          @Resource
          private AmqpTemplate amqpTemplate;
      
          public void sendGoodsToMq(Goods goods) throws JsonProcessingException {
              //消息队列可以发送 字符串、字节数组、序列化对象
              ObjectMapper objectMapper = new ObjectMapper();
              String msg = objectMapper.writeValueAsString(goods);
              amqpTemplate.convertAndSend("","queue1",msg);
          }
      
      }
      
    • 消息消费者

      @Component
      @RabbitListener(queues = "queue1")
      public class ReceiveService {
      
          @RabbitHandler
          public void receiveMsg(String msg) throws JsonProcessingException {
              ObjectMapper objectMapper = new ObjectMapper();
              Goods goods = objectMapper.readValue(msg,Goods.class);
              System.out.println("String---"+msg);
          }
      }
      

  • 相关阅读:
    C/C++ 编写一个通用的Makefile 来编译.c .cpp 或混编
    C/C++ 定义接口文件格式
    MySql存储过程例子1
    项目所遇问题
    linux下编译C++程序无法链接Mysql的问题
    linux 同步时间 调试core内核
    CentOS安装与更新git
    03 js基本数据类型、 js运算符1
    02 js运行原理 、js开发工具介绍 、js程序入门、 js基本语法
    01 js基本介绍
  • 原文地址:https://www.cnblogs.com/coderD/p/14263346.html
Copyright © 2011-2022 走看看