Java中使用RabbitMQ传递对象

updated: 2021-10-20 20:46:13.145
url: https://hututu.fit/archives/java-rabbitmq-send-object
categories: java
tags: java | rabbitMQ

rabbitMQ中发送和接收的都是字符串/字节数组类型的消息

1.序列化对象

实体类需实现Serializable接口;
生产者和消费者中的包名、类名、属性名必须一致;
生产者和消费者使用的queue队列一致

1.1生产者

@Service
public class MQService {

    @Resource
    private AmqpTemplate amqpTemplate;

    public void sendGoodsToMq(Dog dog){
        //消息队列可以发送 字符串、字节数组、序列化对象
        amqpTemplate.convertAndSend("","queue_A",dog);
    }
}

1.2消费者

@Component
public class ConsumerService {

    @RabbitListener(queues = "queue_A")
    @RabbitHandler
    public void consumeMessage(Dog dog){
        System.out.println("dog---"+dog);
    }
}

2.序列化字节数组

实体类需实现Serializable接口;
生产者和消费者中的包名、类名、属性名必须一致;
生产者和消费者使用的queue队列一致

2.1 生产者

@Service
public class MQService {

    @Resource
    private AmqpTemplate amqpTemplate;

    public void sendGoodsToMq(Dog dog){
        //消息队列可以发送 字符串、字节数组、序列化对象
        byte[] bytes = SerializationUtils.serialize(dog);
        amqpTemplate.convertAndSend("","queue_A",bytes);
    }
}

2.2消费者

@Component
public class ConsumerService {

    @RabbitListener(queues = "queue_A")
    @RabbitHandler
    public void consumeMessage(byte[] bs){
        Dog dog = (Goods) SerializationUtils.deserialize(bs);
        System.out.println("byte[]---"+dog);
    }
}

3.JSON字符串

对象的属性名需一致

3.1 生产者

@Service
public class MQService {

    @Resource
    private AmqpTemplate amqpTemplate;

    public void sendGoodsToMq(Dog dog) throws JsonProcessingException {
        //消息队列可以发送 字符串、字节数组、序列化对象
        ObjectMapper objectMapper = new ObjectMapper();
        String msg = objectMapper.writeValueAsString(dog);
        amqpTemplate.convertAndSend("","queue_A",msg);
    }

}

3.2消费者

@Component
public class ReceiveService {

    @RabbitListener(queues = "queue_A")
    @RabbitHandler
    public void receiveMsg(String msg) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Dog dog = objectMapper.readValue(msg,Dog.class);
        System.out.println("String---"+msg);
    }
}